From 0ea1a570f55d565480a992febca446c81af1290b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 09:01:41 +0000 Subject: [PATCH 01/22] ADFA-7238: Serialize PluginManager.loadPlugins() and make checkPluginId public loadPlugins() now runs under a Mutex, so overlapping calls (app start, the first installation, an install from the Add-ons Manager) run one after another instead of clearing loadFailures and loading the same files at once. The body is unchanged, moved into loadAllPlugins(). checkPluginId() loses `internal` so the app module can validate a plugin ID before it names a file after it (next commit). Not compiled or run in this environment (no Android SDK, no flox). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- .../androidide/plugins/manager/core/PluginIds.kt | 2 +- .../androidide/plugins/manager/core/PluginManager.kt | 10 +++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginIds.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginIds.kt index cd0910fe70..dc9f403d91 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginIds.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginIds.kt @@ -10,7 +10,7 @@ import org.adfa.constants.PLUGIN_ARCHIVE_EXTENSION * CoGo build. Uninstalling either would delete what it names. * Nullable because a `plugin.json` manifest without an ID parses to a null one. */ -internal fun checkPluginId(id: String?): Result = +fun checkPluginId(id: String?): Result = when { id.isNullOrEmpty() || id == "." || id == ".." || id.any { it == '/' || it == '\\' || it == '\u0000' } -> { Result.failure(IllegalArgumentException("Invalid plugin ID \"$id\": it must be a name, not a path")) diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt index 4f1dd0f8b7..e0b3ccf100 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt @@ -347,6 +347,7 @@ class PluginManager private constructor( private val statePersistScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private val statePersistMutex = Mutex() + private val loadMutex = Mutex() fun setTemplateReloadListener(listener: (() -> Unit)?) { this.templateReloadListener = listener @@ -401,7 +402,14 @@ class PluginManager private constructor( } } - suspend fun loadPlugins() = + /** + * Loads every plugin file of the plugins folder. Calls run one after another: they all clear + * [loadFailures] and load the same files, so two overlapping ones (the app start, a first + * installation, an install from the Add-ons Manager) would load a plugin twice at once. + */ + suspend fun loadPlugins() = loadMutex.withLock { loadAllPlugins() } + + private suspend fun loadAllPlugins() = withContext(Dispatchers.IO) { logger.info("Loading plugins from directory: ${pluginsDir.absolutePath}") From 94a0d1b1675d9e8612eee8c29a2a94a94a8d9446 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 09:01:42 +0000 Subject: [PATCH 02/22] ADFA-7238: Bundle plugins and templates and install them at first installation A build is "fat" when assets/plugins/*.cgp and assets/templates/*.cgt exist in the repo root; the default is thin and its output is unchanged. Build (app/build.gradle.kts) - Release: StageBundledAddons copies the files to intermediates/bundled-addons//{plugins,templates}, registered as a generated assets source dir for variants with bundled assets. - Debug: createAssetsZip() adds plugins/ and templates/ entries. - A missing or empty folder adds nothing and never fails the build. Install - AssetsInstaller gains listBundledAddons() / installedAddons(); AssetsInstallationHelper installs the 8 fixed entries plus one entry per bundled file in the same parallel phase, sizes taken from the listing for the progress total. Sources: APK assets (release), the split zip (debug). - BundledAddonInstaller copies to a "..partial" file in the target folder, then renames it into place, so an interrupted copy never leaves a truncated file. Plugins go to filesDir/plugins, templates to Environment.TEMPLATES_DIR. - BundledAddonsRecord (filesDir/bundled_addons.properties, atomic write) holds the bundle fingerprint (sha-256 over sorted entry names and sizes), bundled plugin IDs, template file names, and plugin load failures with a reported flag. API: read(), write(state), recordFailures(map), unreportedFailures(), markReported(). It is written last, after every copy succeeded; a thin build writes it too, with an empty bundle. - InstallationViewModel reloads plugins once after a successful asset phase (skipped when nothing was bundled or the plugin system is not up), records bundled plugins with getLoadError(id) != null as unreported failures, and completes the setup regardless. MainActivity.onResume claims unreported failures with markReported() and shows one flashError bar listing them. Decisions - Plugin file naming happens on the device, not at build time: the plugin ID lives in the binary AndroidManifest of the .cgp, which Gradle cannot read simply. The installer reads it with PluginLoader.getPluginMetadata() from the copied scratch file, validates it with checkPluginId() and names the file with PluginBuildFiles.fileStem(), as the Add-ons Manager does. - A bundled plugin whose manifest is unreadable or whose ID is invalid fails the installation like any other missing asset: it is a build defect. - The fingerprint ignores file content, so a rebuilt add-on with the same name and size is not noticed (cheap enough to recompute at every start). - msg_bundled_plugins_failed is English only; the 12 locale folders are not touched and fall back to English (MissingTranslation is already ignored). - Not done here: re-sync at app start (ADFA-7239), removal warning (ADFA-7240). A plugin already in pluginsDir under another build of the same ID is not replaced. Tests: bundle listing (none, some, many, zip source), thin = 8 entries, fingerprint, temp-then-rename install, record round trip / atomicity / mark-once, startup and failure recording, record written only after all copies succeed. Not compiled or run in this environment (no Android SDK, no flox). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- .gitignore | 2 + ARCHITECTURE.md | 1 + app/build.gradle.kts | 54 +++++ .../androidide/activities/MainActivity.kt | 23 +++ .../assets/AssetsInstallationHelper.kt | 62 ++++-- .../androidide/assets/AssetsInstaller.kt | 12 ++ .../androidide/assets/BaseAssetsInstaller.kt | 37 ++++ .../assets/BundledAssetsInstaller.kt | 10 +- .../androidide/assets/SplitAssetsInstaller.kt | 10 +- .../androidide/assets/addons/AtomicFiles.kt | 48 +++++ .../androidide/assets/addons/BundleSources.kt | 69 +++++++ .../assets/addons/BundledAddonInstaller.kt | 63 ++++++ .../androidide/assets/addons/BundledAddons.kt | 85 ++++++++ .../assets/addons/BundledAddonsRecord.kt | 135 +++++++++++++ .../assets/addons/BundledPluginStartup.kt | 39 ++++ .../viewmodel/InstallationViewModel.kt | 23 +++ .../AssetsInstallationHelperBundleTest.kt | 155 +++++++++++++++ .../addons/BundledAddonInstallerTest.kt | 124 ++++++++++++ .../assets/addons/BundledAddonsRecordTest.kt | 136 +++++++++++++ .../assets/addons/BundledAddonsTest.kt | 185 ++++++++++++++++++ .../assets/addons/BundledPluginStartupTest.kt | 103 ++++++++++ resources/src/main/res/values/strings.xml | 2 + 22 files changed, 1360 insertions(+), 18 deletions(-) create mode 100644 app/src/main/java/com/itsaky/androidide/assets/addons/AtomicFiles.kt create mode 100644 app/src/main/java/com/itsaky/androidide/assets/addons/BundleSources.kt create mode 100644 app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt create mode 100644 app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt create mode 100644 app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonsRecord.kt create mode 100644 app/src/main/java/com/itsaky/androidide/assets/addons/BundledPluginStartup.kt create mode 100644 app/src/test/java/com/itsaky/androidide/assets/AssetsInstallationHelperBundleTest.kt create mode 100644 app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt create mode 100644 app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsRecordTest.kt create mode 100644 app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsTest.kt create mode 100644 app/src/test/java/com/itsaky/androidide/assets/addons/BundledPluginStartupTest.kt diff --git a/.gitignore b/.gitignore index 1673ebc78e..8fc9c08799 100755 --- a/.gitignore +++ b/.gitignore @@ -173,6 +173,8 @@ lsp/kotlin/src/main/resources/stdlib-index.json # Large asset files (bootstrap, SDK archives, databases, dependencies) assets/core.cgt +assets/plugins/*.cgp +assets/templates/*.cgt assets/bootstrap-*.zip assets/android-sdk-*.zip assets/release/**/data/**/*.zip.br diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 04c6b3ecf2..c7d1269d4d 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -107,6 +107,7 @@ These structural facts shape every module. Day-to-day build *commands* live in ` - **ABI product flavors.** Every Android module *except* `:plugin-api` and `:subprojects:sqlite-js` gets two flavors on the `abi` dimension — `v7` (`armeabi-v7a`) and `v8` (`arm64-v8a`) — defined centrally. There is no flavorless variant; tasks are `assembleV8Debug`, `assembleV7Release`, etc. - **SDK levels** (`build-logic/.../build/config/BuildConfig.kt`): `COMPILE_SDK=36`, `MIN_SDK=28`, `TARGET_SDK=28`. **`TARGET_SDK` is deliberately pinned at 28:** higher targets enforce W^X (write-xor-execute), which blocks executing code from app-writable files. That is fatal for an on-device IDE that compiles and runs code (Gradle, `javac`, Termux binaries), so it is a hard requirement, not tech debt. `MIN_SDK_FOR_APPS_BUILT_WITH_COGO=16` is the floor for the apps a *user* builds with CoGo — distinct from CoGo's own `MIN_SDK`. - **Native asset bundling.** The on-device LLM (`llama-impl`) ships as a per-flavor native AAR, wired through the root `build.gradle.kts` (`bundleLlamaV8Assets` / `assembleV8Assets`, …); prebuilt per-flavor assets live under `assets/release/v7/` and `assets/release/v8/`. +- **Bundled add-ons** (ADFA-7238). A build is *fat* when `assets/plugins/*.cgp` and `assets/templates/*.cgt` exist in the repo root: release builds put them in the APK assets as `plugins/` and `templates/` (`StageBundledAddons` in `app/build.gradle.kts`), and `createAssetsZip()` adds the same entries to the debug `assets-.zip`. A missing or empty folder is the thin build, whose output is unchanged. First-run setup (`AssetsInstallationHelper`) lists the bundle (`assets/addons/BundledAddons`), installs each file in the same parallel phase through `BundledAddonInstaller` (scratch file, then rename; a plugin lands in `filesDir/plugins` as `-.cgp`, a template in `Environment.TEMPLATES_DIR`), and writes `filesDir/bundled_addons.properties` last (`BundledAddonsRecord`: bundle fingerprint, bundled plugin IDs and template files, plugin load failures not yet reported to the user). `InstallationViewModel` then reloads the plugins once, and `MainActivity` shows one error bar for the recorded failures. - **sqlite-js for apps built with CoGo** (ADFA-7082). `subprojects:sqlite-js` builds the AAR that the JavaScript-in-SQLite project template depends on: the sqlite-js release vendored (see its README), for arm64-v8a and armeabi-v7a, minSdk 26, without core-library desugaring. Nothing in CoGo depends on it. Its default entry point runs no code stored in a database; loading stored functions is a separate entry point, only for databases the app made, since loading runs their code. `test-sqlite-js.yml` runs its host tests on pull requests. The manual `release-sqlite-js.yml` publishes it to the moving `sqlite-js-latest` release, from which dev-assets fetches it into the template, as it fetches `plugin-api-latest` for the plugin template. - **Native lib compression** (ADFA-2306, ADFA-4729). The app manifest hard-codes `android:extractNativeLibs="true"` (required: the installer must materialize libs in `nativeLibraryDir`, e.g. `libshizuku.so` is an executable the adb shell runs from there). That attribute overrides the `jniLibs.useLegacyPackaging` DSL, so AGP packages `lib//*.so` deflate-compressed in **every** APK — ~5.9 MB smaller (`libtree-sitter-kotlin.so` alone is 4.18 MB → 339 kB). The trap is the `recompressApk` post-step (release always, debug in CI only): its no-compress lists in `app/build.gradle.kts` must NOT contain `"so"`, or it silently re-stores the libs and undoes the saving — which is what ADFA-2306 fixed for release and ADFA-4729 for CI debug. Locally built debug APKs (including the e2e farm's) never run that step and were always fine. - **Quick Build shares the Gradle distribution's toolchain** (ADFA-4931). `:app`'s `quickBuildDaemonZip` leaves the Kotlin compiler and eight other jars out of the daemon zip, because the on-device Gradle distribution already carries them; `QuickBuildArtifactStager` links them in at provision time. That makes the daemon's Kotlin version the distribution's, so `:quickbuild:daemon` takes its Kotlin artifacts at `org.adfa.constants.GRADLE_DISTRIBUTION_KOTLIN_VERSION`, and `:app:quickBuildDistJarCheck` fails the build when the distribution it packages lacks a linked jar. See [ADR 0016](docs/adr/0016-quick-build-compiles-outside-gradle.md). diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 55c5fdec0f..d60fe816f0 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -691,10 +691,49 @@ val quickBuildDaemonZip = } } +// A fat build bundles add-ons: the *.cgp files of assets/plugins and the *.cgt files of +// assets/templates, put in the APK assets as plugins/ and templates/. A folder that is +// missing or empty bundles nothing, and the build is the thin one. Plugin files keep their names: +// the installer names each after the plugin ID in its manifest, which Gradle does not read. +abstract class StageBundledAddons : DefaultTask() { + @get:InputFiles + @get:PathSensitive(PathSensitivity.NAME_ONLY) + abstract val pluginFiles: ConfigurableFileCollection + + @get:InputFiles + @get:PathSensitive(PathSensitivity.NAME_ONLY) + abstract val templateFiles: ConfigurableFileCollection + + @get:OutputDirectory + abstract val outputDirectory: DirectoryProperty + + @TaskAction + fun stage() { + val out = outputDirectory.get().asFile + out.deleteRecursively() + out.mkdirs() + pluginFiles.files.filter { !it.name.startsWith(".") }.forEach { it.copyTo(File(out, "plugins/${it.name}")) } + templateFiles.files.filter { !it.name.startsWith(".") }.forEach { it.copyTo(File(out, "templates/${it.name}")) } + } +} + androidComponents.onVariants { variant -> val variantName = variant.name.replaceFirstChar(Char::uppercaseChar) val flavorName = variant.flavorName!! + if (hasBundledAssets(variant)) { + val stageBundledAddons = + tasks.register("stage${variantName}BundledAddons") { + pluginFiles.from(fileTree(rootProject.file("assets/plugins")) { include("*.cgp") }) + templateFiles.from(fileTree(rootProject.file("assets/templates")) { include("*.cgt") }) + outputDirectory.set(layout.buildDirectory.dir("intermediates/bundled-addons/${variant.name}")) + } + variant.sources.assets?.addGeneratedSourceDirectory( + stageBundledAddons, + StageBundledAddons::outputDirectory, + ) + } + val copyRuntimeAar = tasks.register("copy${variantName}QuickBuildRuntimeAar") { val runtimeProject = rootProject.project(":quickbuild:runtime") @@ -1038,6 +1077,21 @@ fun createAssetsZip(arch: String) { filePath.inputStream().use { input -> input.copyTo(zipOut) } zipOut.closeEntry() } + + // Add-ons of a fat build, as plugins/ and templates/; none in a thin one. + arrayOf("plugins" to "cgp", "templates" to "cgt").forEach { (dirName, extension) -> + sourceDir + .resolve(dirName) + .listFiles { file -> file.isFile && !file.name.startsWith(".") && file.extension.equals(extension, ignoreCase = true) } + .orEmpty() + .sortedBy { it.name } + .forEach { file -> + project.logger.lifecycle("Zipping bundled add-on $dirName/${file.name} from ${file.absolutePath}") + zipOut.putNextEntry(ZipEntry("$dirName/${file.name}")) + file.inputStream().use { input -> input.copyTo(zipOut) } + zipOut.closeEntry() + } + } } project.logger.lifecycle("Created ${zipFile.name} at ${zipFile.parentFile.absolutePath}") } diff --git a/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt index 9c7067929e..1d10d22ecc 100755 --- a/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt @@ -47,6 +47,7 @@ import com.itsaky.androidide.analytics.IAnalyticsManager import com.itsaky.androidide.analytics.depth import com.itsaky.androidide.analytics.selector import com.itsaky.androidide.app.EdgeToEdgeIDEActivity +import com.itsaky.androidide.assets.addons.BundledAddonsRecord import com.itsaky.androidide.databinding.ActivityMainBinding import com.itsaky.androidide.deeplink.ConsumedRequests import com.itsaky.androidide.fragments.MainFragment @@ -336,6 +337,28 @@ class MainActivity : EdgeToEdgeIDEActivity() { super.onResume() MainScreenActions.register(this) feedbackButtonManager?.loadFabPosition() + reportBundledPluginFailures() + } + + /** + * Tells the user once which plugins bundled with the build did not start. Marking them reported + * is what claims them, so a quick pause and resume cannot show the bar twice; the cost is that a + * screen destroyed between the claim and the bar loses the message. + */ + private fun reportBundledPluginFailures() { + lifecycleScope.launch { + val failures = + withContext(Dispatchers.IO) { + runCatching { BundledAddonsRecord.inFilesDir(filesDir).markReported() }.getOrDefault(emptyList()) + } + if (failures.isEmpty()) return@launch + flashError( + getString( + string.msg_bundled_plugins_failed, + failures.joinToString("\n") { "${it.pluginId}: ${it.message}" }, + ), + ) + } } override fun onPause() { diff --git a/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt b/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt index 47962fe751..ef01348467 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt @@ -5,6 +5,11 @@ import android.os.StatFs import androidx.annotation.WorkerThread import com.aayushatharva.brotli4j.Brotli4jLoader import com.itsaky.androidide.app.configuration.IDEBuildConfigProvider +import com.itsaky.androidide.assets.addons.BundledAddonKind +import com.itsaky.androidide.assets.addons.BundledAddons +import com.itsaky.androidide.assets.addons.BundledAddonsRecord +import com.itsaky.androidide.assets.addons.BundledAddonsState +import com.itsaky.androidide.assets.addons.BundledEntry import com.itsaky.androidide.resources.R import com.itsaky.androidide.utils.ContainedPathResolver import com.itsaky.androidide.utils.ContainedPathResolver.Resolution @@ -15,6 +20,7 @@ import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.isActive import kotlinx.coroutines.joinAll import kotlinx.coroutines.launch @@ -69,6 +75,22 @@ object AssetsInstallationHelper { private val ASSETS_INSTALLER = AssetsInstaller.CURRENT_INSTALLER const val BOOTSTRAP_ENTRY_NAME = "bootstrap.zip" + /** The entries every build installs. Add-ons a build bundles come on top, see [entriesToInstall]. */ + internal val expectedEntries = + listOf( + GRADLE_DISTRIBUTION_ARCHIVE_NAME, + ANDROID_SDK_ZIP, + DOCUMENTATION_DB, + LOCAL_MAVEN_REPO_ARCHIVE_ZIP_NAME, + BOOTSTRAP_ENTRY_NAME, + GRADLE_API_NAME_JAR_ZIP, + PLUGIN_ARTIFACTS_ZIP, + TEMPLATE_CORE_ARCHIVE, + ) + + /** [expectedEntries], then each of [bundled]; a thin build, with none, installs [expectedEntries] alone. */ + internal fun entriesToInstall(bundled: List): List = expectedEntries + bundled.map { it.entryName } + suspend fun install( context: Context, onProgress: AssetsInstallerProgressConsumer = {}, @@ -124,18 +146,6 @@ object AssetsInstallationHelper { val buildConfig = IDEBuildConfigProvider.getInstance() val cpuArch = buildConfig.cpuArch - val expectedEntries = - arrayOf( - GRADLE_DISTRIBUTION_ARCHIVE_NAME, - ANDROID_SDK_ZIP, - DOCUMENTATION_DB, - LOCAL_MAVEN_REPO_ARCHIVE_ZIP_NAME, - BOOTSTRAP_ENTRY_NAME, - GRADLE_API_NAME_JAR_ZIP, - PLUGIN_ARTIFACTS_ZIP, - TEMPLATE_CORE_ARCHIVE, - ) - val stagingDir = Files.createTempDirectory(UUID.randomUUID().toString()) logger.debug("Staging directory ({}): {}", cpuArch, stagingDir) @@ -160,17 +170,19 @@ object AssetsInstallationHelper { logAndRethrow("I/O error during preInstall", e) } + val bundledAddons = ASSETS_INSTALLER.listBundledAddons(context) + val entries = entriesToInstall(bundledAddons) + val entrySizes: Map = - expectedEntries.associateWith { entry -> - ASSETS_INSTALLER.expectedSize(entry) - } + expectedEntries.associateWith { entry -> ASSETS_INSTALLER.expectedSize(entry) } + + bundledAddons.associate { it.entryName to it.size } val totalSize = entrySizes.values.sum() val entryStatusMap = ConcurrentHashMap() val installerJobs = - expectedEntries.map { entry -> + entries.map { entry -> async { entryStatusMap[entry] = STATUS_INSTALLING @@ -233,6 +245,24 @@ object AssetsInstallationHelper { // then cancel progress updater progressUpdater.cancel() + + // joinAll() does not rethrow a failed child, and returns at once when they have all + // finished already: without this a failed copy would still get its record written. + ensureActive() + + // Last, and only here, so a record means every file of the bundle is in place. + val installed = ASSETS_INSTALLER.installedAddons() + BundledAddonsRecord.inFilesDir(context.filesDir).write( + BundledAddonsState( + fingerprint = BundledAddons.fingerprint(bundledAddons), + pluginIds = installed.mapNotNull { it.pluginId }.sorted(), + templateFiles = + installed + .filter { it.kind == BundledAddonKind.TEMPLATE } + .map { it.file.name } + .sorted(), + ), + ) } finally { // Always run postInstall so zip/FS resources are closed (e.g. SplitAssetsInstaller.zipFile), // and always clean up the staging dir -- on any exit path, including a preInstall diff --git a/app/src/main/java/com/itsaky/androidide/assets/AssetsInstaller.kt b/app/src/main/java/com/itsaky/androidide/assets/AssetsInstaller.kt index 422cb543cd..d33376d9ac 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/AssetsInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/AssetsInstaller.kt @@ -4,6 +4,8 @@ import android.content.Context import androidx.annotation.WorkerThread import com.itsaky.androidide.BuildConfig import com.itsaky.androidide.app.configuration.CpuArch +import com.itsaky.androidide.assets.addons.BundledEntry +import com.itsaky.androidide.assets.addons.InstalledAddon import java.nio.file.Path /** @@ -74,4 +76,14 @@ sealed interface AssetsInstaller { * @return The expected size in bytes, or 0 if unknown. */ fun expectedSize(entryName: String): Long + + /** + * Lists the add-on files (plugins and templates) this build bundles; none for a thin build. + * Call it once per installation, after [preInstall]: it also forgets the add-ons a previous + * installation reported through [installedAddons]. + */ + fun listBundledAddons(context: Context): List + + /** The add-ons [doInstall] has put in place since [listBundledAddons]. */ + fun installedAddons(): List } diff --git a/app/src/main/java/com/itsaky/androidide/assets/BaseAssetsInstaller.kt b/app/src/main/java/com/itsaky/androidide/assets/BaseAssetsInstaller.kt index b0ded95a38..8393c8e6aa 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/BaseAssetsInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/BaseAssetsInstaller.kt @@ -1,17 +1,54 @@ package com.itsaky.androidide.assets import android.content.Context +import com.itsaky.androidide.assets.addons.BundleSource +import com.itsaky.androidide.assets.addons.BundledAddonInstaller +import com.itsaky.androidide.assets.addons.BundledAddons +import com.itsaky.androidide.assets.addons.BundledEntry +import com.itsaky.androidide.assets.addons.InstalledAddon +import com.itsaky.androidide.plugins.manager.loaders.PluginLoader import com.itsaky.androidide.utils.Environment import com.termux.shared.termux.TermuxConstants import org.slf4j.LoggerFactory import java.io.File +import java.io.InputStream import java.nio.file.Path +import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit import kotlin.concurrent.thread import kotlin.system.measureTimeMillis abstract class BaseAssetsInstaller : AssetsInstaller { private val logger = LoggerFactory.getLogger(BaseAssetsInstaller::class.java) + private val installedByEntry = ConcurrentHashMap() + + /** Where this installer's bundled add-ons are read from. */ + protected abstract fun bundleSource(context: Context): BundleSource + + override fun listBundledAddons(context: Context): List { + installedByEntry.clear() + return BundledAddons.list(bundleSource(context)) + } + + override fun installedAddons(): List = installedByEntry.values.toList() + + /** Installs the bundled add-on [entryName] (`plugins/` or `templates/`) read from [input]. */ + protected fun installBundledAddon( + context: Context, + entryName: String, + input: InputStream, + ) { + val (kind, fileName) = + BundledAddons.parse(entryName) ?: throw IllegalStateException("Unknown entry: $entryName") + val installer = + BundledAddonInstaller( + // The folder PluginManager loads from. + pluginsDir = File(context.filesDir, "plugins"), + templatesDir = Environment.TEMPLATES_DIR, + readPluginId = { PluginLoader(context, it).getPluginMetadata()?.id }, + ) + installedByEntry[entryName] = installer.install(kind, fileName, input) + } override suspend fun postInstall( context: Context, diff --git a/app/src/main/java/com/itsaky/androidide/assets/BundledAssetsInstaller.kt b/app/src/main/java/com/itsaky/androidide/assets/BundledAssetsInstaller.kt index a01d15a636..eef570e4b9 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/BundledAssetsInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/BundledAssetsInstaller.kt @@ -4,6 +4,9 @@ import android.content.Context import androidx.annotation.WorkerThread import com.aayushatharva.brotli4j.decoder.BrotliInputStream import com.itsaky.androidide.app.configuration.CpuArch +import com.itsaky.androidide.assets.addons.AssetManagerBundleSource +import com.itsaky.androidide.assets.addons.BundleSource +import com.itsaky.androidide.assets.addons.BundledAddons import com.itsaky.androidide.managers.ToolsManager import com.itsaky.androidide.resources.R import com.itsaky.androidide.utils.Environment @@ -169,11 +172,16 @@ data object BundledAssetsInstaller : BaseAssetsInstaller() { } else -> { - throw IllegalStateException("Unknown entry: $entryName") + if (!BundledAddons.isAddonEntry(entryName)) { + throw IllegalStateException("Unknown entry: $entryName") + } + assets.open(entryName).use { installBundledAddon(context, entryName, it) } } } } + override fun bundleSource(context: Context): BundleSource = AssetManagerBundleSource(context.assets) + override fun expectedSize(entryName: String): Long = when (entryName) { GRADLE_DISTRIBUTION_ARCHIVE_NAME -> 63399283L diff --git a/app/src/main/java/com/itsaky/androidide/assets/SplitAssetsInstaller.kt b/app/src/main/java/com/itsaky/androidide/assets/SplitAssetsInstaller.kt index dcafab5900..8c49061ba6 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/SplitAssetsInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/SplitAssetsInstaller.kt @@ -3,6 +3,9 @@ package com.itsaky.androidide.assets import android.content.Context import androidx.annotation.WorkerThread import com.itsaky.androidide.app.configuration.CpuArch +import com.itsaky.androidide.assets.addons.BundleSource +import com.itsaky.androidide.assets.addons.BundledAddons +import com.itsaky.androidide.assets.addons.ZipBundleSource import com.itsaky.androidide.resources.R import com.itsaky.androidide.utils.Environment import com.itsaky.androidide.utils.TerminalInstaller @@ -174,7 +177,10 @@ data object SplitAssetsInstaller : BaseAssetsInstaller() { } else -> { - throw IllegalStateException("Unknown entry: $entryName") + if (!BundledAddons.isAddonEntry(entryName)) { + throw IllegalStateException("Unknown entry: $entryName") + } + installBundledAddon(context, entryName, zipInput) } } } @@ -182,6 +188,8 @@ data object SplitAssetsInstaller : BaseAssetsInstaller() { logger.info("Extraction of '{}' completed in {}ms", entry.name, time) } + override fun bundleSource(context: Context): BundleSource = ZipBundleSource(zipFile) + override suspend fun postInstall( context: Context, stagingDir: Path, diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/AtomicFiles.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/AtomicFiles.kt new file mode 100644 index 0000000000..8b654f5aae --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/AtomicFiles.kt @@ -0,0 +1,48 @@ +package com.itsaky.androidide.assets.addons + +import java.io.File +import java.io.IOException +import java.nio.file.AtomicMoveNotSupportedException +import java.nio.file.Files +import java.nio.file.StandardCopyOption +import java.util.UUID + +internal object AtomicFiles { + /** Moves [temp] to [dest], replacing it, in one step where the filesystem can. */ + fun moveInto( + temp: File, + dest: File, + ) { + try { + Files.move(temp.toPath(), dest.toPath(), StandardCopyOption.ATOMIC_MOVE) + } catch (e: AtomicMoveNotSupportedException) { + Files.move(temp.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING) + } + } + + /** + * Fills a scratch file next to the destination with [write], then lets [finalName] pick the + * destination's name from it and moves it there. The scratch name ends in `.partial`, which no + * loader of plugins or templates reads, and the scratch file is deleted on any failure, so an + * interrupted copy never leaves a truncated file under a final name. + */ + fun writeInto( + destDir: File, + write: (File) -> Unit, + finalName: (File) -> String, + ): File { + if (!destDir.isDirectory && !destDir.mkdirs() && !destDir.isDirectory) { + throw IOException("Could not create ${destDir.absolutePath}") + } + val temp = File(destDir, ".${UUID.randomUUID()}.partial") + try { + write(temp) + val dest = File(destDir, finalName(temp)) + moveInto(temp, dest) + return dest + } finally { + // Gone already after a successful move; only a failure leaves it. + temp.delete() + } + } +} diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSources.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSources.kt new file mode 100644 index 0000000000..bbf904787d --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSources.kt @@ -0,0 +1,69 @@ +package com.itsaky.androidide.assets.addons + +import android.content.res.AssetManager +import java.io.FileNotFoundException +import java.io.IOException +import java.io.InputStream +import java.util.zip.ZipFile + +/** The bundle of a release build: `plugins/` and `templates/` in the APK assets. */ +class AssetManagerBundleSource( + private val assets: AssetManager, +) : BundleSource { + override fun names(dir: String): List = assets.list(dir)?.toList().orEmpty() + + override fun size( + dir: String, + name: String, + ): Long = + try { + assets.openFd("$dir/$name").use { it.length } + } catch (e: IOException) { + // openFd refuses an asset the APK stores compressed; count the bytes instead. + assets.open("$dir/$name").use { input -> input.countBytes() } + } + + override fun open( + dir: String, + name: String, + ): InputStream = assets.open("$dir/$name") +} + +/** The bundle of a debug build: `plugins/` and `templates/` entries of the split assets zip. */ +class ZipBundleSource( + private val zip: ZipFile, +) : BundleSource { + override fun names(dir: String): List = + zip + .entries() + .asSequence() + .filter { !it.isDirectory && it.name.startsWith("$dir/") } + .map { it.name.removePrefix("$dir/") } + .filter { it.isNotEmpty() && '/' !in it } + .toList() + + override fun size( + dir: String, + name: String, + ): Long = entry(dir, name).size + + override fun open( + dir: String, + name: String, + ): InputStream = zip.getInputStream(entry(dir, name)) + + private fun entry( + dir: String, + name: String, + ) = zip.getEntry("$dir/$name") ?: throw FileNotFoundException("Entry '$dir/$name' not found in assets zip file") +} + +private fun InputStream.countBytes(): Long { + val buffer = ByteArray(DEFAULT_BUFFER_SIZE) + var total = 0L + while (true) { + val read = read(buffer) + if (read < 0) return total + total += read + } +} diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt new file mode 100644 index 0000000000..d4d3c80df9 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt @@ -0,0 +1,63 @@ +package com.itsaky.androidide.assets.addons + +import com.itsaky.androidide.plugins.manager.core.PluginBuildFiles +import com.itsaky.androidide.plugins.manager.core.checkPluginId +import org.adfa.constants.PLUGIN_ARCHIVE_EXTENSION +import java.io.File +import java.io.IOException +import java.io.InputStream + +/** An add-on file that reached its folder. [pluginId] is set for a plugin. */ +data class InstalledAddon( + val kind: BundledAddonKind, + val file: File, + val pluginId: String?, +) + +/** + * Copies bundled add-on files into place. A plugin lands in [pluginsDir] as + * `-.cgp`, the name an install from the Add-ons Manager gives it, and a template in + * [templatesDir] under its bundled name. + * + * The plugin ID is only in the plugin's manifest, so the name is chosen on the device, from the + * copied file ([readPluginId]), and not at build time. The bundle then needs no manifest reader in + * Gradle, and the naming rule stays in [PluginBuildFiles.fileStem]. + */ +class BundledAddonInstaller( + private val pluginsDir: File, + private val templatesDir: File, + private val readPluginId: (File) -> String?, +) { + fun install( + kind: BundledAddonKind, + fileName: String, + input: InputStream, + ): InstalledAddon = + when (kind) { + BundledAddonKind.PLUGIN -> installPlugin(input) + BundledAddonKind.TEMPLATE -> { + val file = AtomicFiles.writeInto(templatesDir, { input.copyToFile(it) }, { fileName }) + InstalledAddon(kind, file, null) + } + } + + private fun installPlugin(input: InputStream): InstalledAddon { + var pluginId: String? = null + val file = + AtomicFiles.writeInto( + pluginsDir, + { input.copyToFile(it) }, + { copy -> + val id = readPluginId(copy) ?: throw IOException("Bundled plugin has no readable manifest") + checkPluginId(id).getOrThrow() + pluginId = id + "${PluginBuildFiles.fileStem(id, copy)}.$PLUGIN_ARCHIVE_EXTENSION" + }, + ) + return InstalledAddon(BundledAddonKind.PLUGIN, file, pluginId) + } + + private fun InputStream.copyToFile(dest: File) { + dest.outputStream().use { out -> copyTo(out) } + } +} diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt new file mode 100644 index 0000000000..dcf61fc5b8 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt @@ -0,0 +1,85 @@ +package com.itsaky.androidide.assets.addons + +import org.adfa.constants.PLUGIN_ARCHIVE_EXTENSION +import org.adfa.constants.TEMPLATE_ARCHIVE_EXTENSION +import java.io.InputStream +import java.security.MessageDigest + +/** The add-on kinds a build can bundle, each in a folder of its own in the APK assets or the debug zip. */ +enum class BundledAddonKind( + val dir: String, + val extension: String, +) { + PLUGIN("plugins", PLUGIN_ARCHIVE_EXTENSION), + TEMPLATE("templates", TEMPLATE_ARCHIVE_EXTENSION), +} + +/** One bundled add-on file: [fileName] inside the [kind] folder, [size] bytes. */ +data class BundledEntry( + val kind: BundledAddonKind, + val fileName: String, + val size: Long, +) { + /** The name the installers and the progress list know it by: `plugins/`. */ + val entryName: String get() = "${kind.dir}/$fileName" +} + +/** Where the bundle is read from: APK assets in a release build, the split assets zip in a debug one. */ +interface BundleSource { + /** File names directly inside [dir], or none when the folder is absent. */ + fun names(dir: String): List + + fun size( + dir: String, + name: String, + ): Long + + fun open( + dir: String, + name: String, + ): InputStream +} + +object BundledAddons { + /** True for an entry name that [BundledEntry.entryName] could have produced. */ + fun isAddonEntry(entryName: String): Boolean = parse(entryName) != null + + /** The kind and file name of [entryName], or null when it names no add-on file. */ + fun parse(entryName: String): Pair? { + val kind = BundledAddonKind.values().firstOrNull { entryName.startsWith("${it.dir}/") } ?: return null + val fileName = entryName.removePrefix("${kind.dir}/") + return if (isAddonFile(kind, fileName)) kind to fileName else null + } + + /** + * Every add-on file [source] holds, plugins first, each kind in name order. A thin build has + * none. Other files in the folders, and any path below them, are not add-ons. + */ + fun list(source: BundleSource): List = + BundledAddonKind.values().flatMap { kind -> + source + .names(kind.dir) + .filter { isAddonFile(kind, it) } + .sorted() + .map { BundledEntry(kind, it, source.size(kind.dir, it)) } + } + + /** + * Identifies a bundle by its entry names and sizes, in any order: sha-256, hex. Cheap enough to + * recompute at every start. A rebuilt add-on that keeps its name and size is not noticed. The + * empty bundle has a fingerprint too, so a thin build can be told from a missing record. + */ + fun fingerprint(entries: List): String { + val digest = MessageDigest.getInstance("SHA-256") + entries + .map { "${it.entryName}\t${it.size}\n" } + .sorted() + .forEach { digest.update(it.toByteArray(Charsets.UTF_8)) } + return digest.digest().joinToString("") { "%02x".format(it) } + } + + private fun isAddonFile( + kind: BundledAddonKind, + fileName: String, + ): Boolean = '/' !in fileName && !fileName.startsWith(".") && fileName.endsWith(".${kind.extension}", ignoreCase = true) +} diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonsRecord.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonsRecord.kt new file mode 100644 index 0000000000..908f535230 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonsRecord.kt @@ -0,0 +1,135 @@ +package com.itsaky.androidide.assets.addons + +import java.io.File +import java.io.IOException +import java.util.Properties +import java.util.UUID + +/** A bundled plugin that did not load, and whether the user has been told. */ +data class BundledPluginFailure( + val pluginId: String, + val message: String, + val reported: Boolean = false, +) + +/** What the first installation took from the build's bundle. */ +data class BundledAddonsState( + /** [BundledAddons.fingerprint] of the bundle that was installed. */ + val fingerprint: String, + val pluginIds: List = emptyList(), + val templateFiles: List = emptyList(), + val failures: List = emptyList(), +) + +/** + * The record of an installed bundle: which plugins and templates came from the build, and which + * bundled plugins failed to load. Kept in a properties file, as `plugin_crash_counts.properties` is. + * + * [write] runs only after every bundle file is in place, so a record exists only for a complete + * install, and replaces the file in one step. A missing or unreadable file reads as no record. + * The installation writes it for a thin build too, with an empty bundle. + */ +class BundledAddonsRecord( + private val file: File, +) { + @Synchronized + fun read(): BundledAddonsState? { + if (!file.isFile) return null + return try { + val props = Properties() + file.inputStream().use { props.load(it) } + val fingerprint = props.getProperty(FINGERPRINT) ?: return null + BundledAddonsState( + fingerprint = fingerprint, + pluginIds = props.indexed(PLUGIN), + templateFiles = props.indexed(TEMPLATE), + failures = props.failures(), + ) + } catch (e: IOException) { + null + } catch (e: IllegalArgumentException) { + // Properties.load on a malformed escape. + null + } + } + + /** Replaces the record with [state]; failures it carries are kept as given. */ + @Synchronized + fun write(state: BundledAddonsState) { + val props = Properties() + props.setProperty(FINGERPRINT, state.fingerprint) + state.pluginIds.forEachIndexed { n, id -> props.setProperty("$PLUGIN.$n", id) } + state.templateFiles.forEachIndexed { n, name -> props.setProperty("$TEMPLATE.$n", name) } + state.failures.forEachIndexed { n, failure -> + props.setProperty("$FAILURE.$n.id", failure.pluginId) + props.setProperty("$FAILURE.$n.message", failure.message) + props.setProperty("$FAILURE.$n.reported", failure.reported.toString()) + } + + file.parentFile?.mkdirs() + val temp = File(file.parentFile, ".${file.name}.${UUID.randomUUID()}.tmp") + try { + temp.outputStream().use { props.store(it, null) } + AtomicFiles.moveInto(temp, file) + } finally { + temp.delete() + } + } + + /** + * Stores [failures] (plugin ID to message) as unreported, replacing any earlier ones. + * Does nothing when there is no record: failures belong to an installed bundle. + */ + @Synchronized + fun recordFailures(failures: Map) { + val state = read() ?: return + write(state.copy(failures = failures.map { (id, message) -> BundledPluginFailure(id, message) })) + } + + /** The failures the user has not been told about, in the order recorded. */ + @Synchronized + fun unreportedFailures(): List = read()?.failures.orEmpty().filterNot { it.reported } + + /** Marks every recorded failure as told, and returns those that were not before. */ + @Synchronized + fun markReported(): List { + val state = read() ?: return emptyList() + val pending = state.failures.filterNot { it.reported } + if (pending.isNotEmpty()) { + write(state.copy(failures = state.failures.map { it.copy(reported = true) })) + } + return pending + } + + private fun Properties.indexed(prefix: String): List { + val values = ArrayList() + while (true) { + values += getProperty("$prefix.${values.size}") ?: return values + } + } + + private fun Properties.failures(): List { + val failures = ArrayList() + while (true) { + val n = failures.size + val id = getProperty("$FAILURE.$n.id") ?: return failures + failures += + BundledPluginFailure( + pluginId = id, + message = getProperty("$FAILURE.$n.message").orEmpty(), + reported = getProperty("$FAILURE.$n.reported") == "true", + ) + } + } + + companion object { + const val FILE_NAME = "bundled_addons.properties" + + private const val FINGERPRINT = "fingerprint" + private const val PLUGIN = "plugin" + private const val TEMPLATE = "template" + private const val FAILURE = "failure" + + fun inFilesDir(filesDir: File) = BundledAddonsRecord(File(filesDir, FILE_NAME)) + } +} diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledPluginStartup.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledPluginStartup.kt new file mode 100644 index 0000000000..e272c0bde5 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledPluginStartup.kt @@ -0,0 +1,39 @@ +package com.itsaky.androidide.assets.addons + +import kotlin.coroutines.cancellation.CancellationException + +/** + * Starts the plugins a first installation copied from the bundle, and records those that did not + * load, for the main screen to report once ([BundledAddonsRecord.markReported]). + * + * A failure here never fails the setup: [start] returns normally whatever the plugins do. + */ +class BundledPluginStartup( + private val record: BundledAddonsRecord, + private val reloadPlugins: suspend () -> Unit, + private val loadError: (pluginId: String) -> String?, +) { + suspend fun start() { + val pluginIds = record.read()?.pluginIds.orEmpty() + // A thin build copied no plugin, so there is nothing to start. + if (pluginIds.isEmpty()) return + + val reloadFailure = + try { + reloadPlugins() + null + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + e.message ?: e.toString() + } + + val failures = + pluginIds + .mapNotNull { id -> (reloadFailure ?: loadError(id))?.let { id to it } } + .toMap() + if (failures.isNotEmpty()) { + record.recordFailures(failures) + } + } +} diff --git a/app/src/main/java/com/itsaky/androidide/viewmodel/InstallationViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodel/InstallationViewModel.kt index 6c07509ed3..ac1570880a 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodel/InstallationViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodel/InstallationViewModel.kt @@ -7,8 +7,11 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.itsaky.androidide.app.configuration.IJdkDistributionProvider import com.itsaky.androidide.assets.AssetsInstallationHelper +import com.itsaky.androidide.assets.addons.BundledAddonsRecord +import com.itsaky.androidide.assets.addons.BundledPluginStartup import com.itsaky.androidide.events.InstallationEvent import com.itsaky.androidide.models.StorageInfo +import com.itsaky.androidide.plugins.manager.core.PluginManager import com.itsaky.androidide.resources.R import com.itsaky.androidide.utils.Environment import com.itsaky.androidide.utils.bytesToGigabytes @@ -37,6 +40,7 @@ import kotlin.coroutines.cancellation.CancellationException // All-default constructor, so the default ViewModel factory still finds a no-arg one. class InstallationViewModel( private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, + private val startBundledPlugins: suspend (Context) -> Unit = { startBundledPluginsWithManager(it) }, ) : ViewModel() { private val log = LoggerFactory.getLogger(InstallationViewModel::class.java) @@ -95,6 +99,15 @@ class InstallationViewModel( val distributionProvider = IJdkDistributionProvider.getInstance() distributionProvider.loadDistributions() + // Plugins from the build's bundle; the setup completes whatever they do. + try { + startBundledPlugins(context) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("Could not start the bundled plugins", e) + } + _state.update { InstallationComplete } } @@ -177,3 +190,13 @@ class InstallationViewModel( return@withContext true } } + +/** Without the plugin system (not initialized yet) there is nothing to start; the files stay for the next start. */ +private suspend fun startBundledPluginsWithManager(context: Context) { + val manager = PluginManager.getInstance() ?: return + BundledPluginStartup( + record = BundledAddonsRecord.inFilesDir(context.filesDir), + reloadPlugins = { manager.loadPlugins() }, + loadError = manager::getLoadError, + ).start() +} diff --git a/app/src/test/java/com/itsaky/androidide/assets/AssetsInstallationHelperBundleTest.kt b/app/src/test/java/com/itsaky/androidide/assets/AssetsInstallationHelperBundleTest.kt new file mode 100644 index 0000000000..b284d5851e --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/assets/AssetsInstallationHelperBundleTest.kt @@ -0,0 +1,155 @@ +package com.itsaky.androidide.assets + +import android.content.Context +import com.aayushatharva.brotli4j.Brotli4jLoader +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.app.configuration.CpuArch +import com.itsaky.androidide.app.configuration.IDEBuildConfigProvider +import com.itsaky.androidide.assets.addons.BundledAddonKind +import com.itsaky.androidide.assets.addons.BundledAddons +import com.itsaky.androidide.assets.addons.BundledAddonsRecord +import com.itsaky.androidide.assets.addons.BundledAddonsState +import com.itsaky.androidide.assets.addons.BundledEntry +import com.itsaky.androidide.assets.addons.InstalledAddon +import io.mockk.Runs +import io.mockk.coEvery +import io.mockk.every +import io.mockk.just +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.mockkStatic +import io.mockk.unmockkAll +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File +import java.io.IOException + +/** + * The bundle record is written last and only for a complete installation. Like the other tests of + * the helper, this relies on AssetsInstaller.CURRENT_INSTALLER being SplitAssetsInstaller, which + * only holds for debug builds: run it via :app:testV8DebugUnitTest. + */ +class AssetsInstallationHelperBundleTest { + @get:Rule + val tempFolder = TemporaryFolder() + + private val ctx: Context = mockk(relaxed = true) + private val helper = AssetsInstallationHelper + private lateinit var filesDir: File + + @Before + fun setUp() { + filesDir = tempFolder.newFolder("files") + every { ctx.filesDir } returns filesDir + + mockkObject(helper) + every { + helper["checkStorageAccessibility"](any(), any()) + } returns null + + mockkObject(IDEBuildConfigProvider.Companion) + mockkStatic(Brotli4jLoader::class) + val provider = mockk(relaxed = true) + every { provider.cpuArch } returns CpuArch.AARCH64 + every { IDEBuildConfigProvider.getInstance() } returns provider + every { Brotli4jLoader.ensureAvailability() } just Runs + + mockkObject(SplitAssetsInstaller) + coEvery { SplitAssetsInstaller.preInstall(any(), any()) } just Runs + coEvery { SplitAssetsInstaller.postInstall(any(), any()) } just Runs + } + + @After + fun tearDown() { + unmockkAll() + } + + private val record get() = BundledAddonsRecord.inFilesDir(filesDir) + + private val bundle = + listOf( + BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 10L), + BundledEntry(BundledAddonKind.PLUGIN, "b.cgp", 20L), + BundledEntry(BundledAddonKind.TEMPLATE, "t.cgt", 30L), + ) + + private fun installed(name: String) = + when { + name.endsWith(".cgt") -> InstalledAddon(BundledAddonKind.TEMPLATE, File(filesDir, name), null) + else -> InstalledAddon(BundledAddonKind.PLUGIN, File(filesDir, "$name-hash.cgp"), "id.${name.removeSuffix(".cgp")}") + } + + @Test + fun `every entry is installed, then the record is written`() = + runBlocking { + val seen = java.util.concurrent.ConcurrentHashMap.newKeySet() + every { SplitAssetsInstaller.listBundledAddons(any()) } returns bundle + every { SplitAssetsInstaller.installedAddons() } returns bundle.map { installed(it.fileName) } + coEvery { SplitAssetsInstaller.doInstall(any(), any(), any(), any()) } coAnswers { + assertThat(record.read()).isNull() + seen += arg(3) + } + + val result = helper.install(ctx) + + assertThat(result).isEqualTo(AssetsInstallationHelper.Result.Success) + assertThat(seen).containsExactlyElementsIn(AssetsInstallationHelper.entriesToInstall(bundle)) + assertThat(record.read()) + .isEqualTo( + BundledAddonsState( + fingerprint = BundledAddons.fingerprint(bundle), + pluginIds = listOf("id.a", "id.b"), + templateFiles = listOf("t.cgt"), + ), + ) + } + + @Test + fun `a thin build installs the eight entries and records an empty bundle`() = + runBlocking { + val seen = java.util.concurrent.ConcurrentHashMap.newKeySet() + every { SplitAssetsInstaller.listBundledAddons(any()) } returns emptyList() + every { SplitAssetsInstaller.installedAddons() } returns emptyList() + coEvery { SplitAssetsInstaller.doInstall(any(), any(), any(), any()) } coAnswers { seen += arg(3) } + + helper.install(ctx) + + assertThat(seen).containsExactlyElementsIn(AssetsInstallationHelper.expectedEntries) + assertThat(seen).hasSize(8) + assertThat(record.read()).isEqualTo(BundledAddonsState(fingerprint = BundledAddons.fingerprint(emptyList()))) + } + + @Test + fun `no record is written when one bundled copy fails`() = + runBlocking { + every { SplitAssetsInstaller.listBundledAddons(any()) } returns bundle + every { SplitAssetsInstaller.installedAddons() } returns bundle.map { installed(it.fileName) } + coEvery { SplitAssetsInstaller.doInstall(any(), any(), any(), any()) } coAnswers { + if (arg(3) == "plugins/b.cgp") throw IOException("disk full") + } + + val result = helper.install(ctx) + + assertThat(result).isInstanceOf(AssetsInstallationHelper.Result.Failure::class.java) + assertThat(record.read()).isNull() + assertThat(File(filesDir, BundledAddonsRecord.FILE_NAME).exists()).isFalse() + } + + @Test + fun `no record is written when a fixed entry fails`() = + runBlocking { + every { SplitAssetsInstaller.listBundledAddons(any()) } returns bundle + every { SplitAssetsInstaller.installedAddons() } returns bundle.map { installed(it.fileName) } + coEvery { SplitAssetsInstaller.doInstall(any(), any(), any(), any()) } coAnswers { + if (arg(3) == "bootstrap.zip") throw IOException("disk full") + } + + helper.install(ctx) + + assertThat(record.read()).isNull() + } +} diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt new file mode 100644 index 0000000000..9e216edb68 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt @@ -0,0 +1,124 @@ +package com.itsaky.androidide.assets.addons + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.plugins.manager.core.PluginBuildFiles +import org.junit.Assert.assertThrows +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.ByteArrayInputStream +import java.io.File +import java.io.IOException +import java.io.InputStream + +class BundledAddonInstallerTest { + @get:Rule + val tempFolder = TemporaryFolder() + + private lateinit var pluginsDir: File + private lateinit var templatesDir: File + + @Before + fun setUp() { + pluginsDir = File(tempFolder.root, "plugins") + templatesDir = File(tempFolder.root, "templates") + } + + private fun installer(readPluginId: (File) -> String? = { "com.example.plugin" }) = BundledAddonInstaller(pluginsDir, templatesDir, readPluginId) + + private fun bytes(text: String): InputStream = ByteArrayInputStream(text.toByteArray()) + + /** Delivers [first], then fails, like a copy cut short. */ + private fun failingAfter(first: String): InputStream = + object : InputStream() { + private val head = first.toByteArray() + private var pos = 0 + + override fun read(): Int = if (pos < head.size) head[pos++].toInt() else throw IOException("cut short") + } + + @Test + fun `a plugin is installed as pluginId-hash dot cgp`() { + val installed = installer().install(BundledAddonKind.PLUGIN, "whatever.cgp", bytes("plugin bytes")) + + val expectedStem = PluginBuildFiles.fileStem("com.example.plugin", installed.file) + assertThat(installed.file.name).isEqualTo("$expectedStem.cgp") + assertThat(installed.file.name).startsWith("com.example.plugin-") + assertThat(installed.file.parentFile).isEqualTo(pluginsDir) + assertThat(installed.file.readText()).isEqualTo("plugin bytes") + assertThat(installed.pluginId).isEqualTo("com.example.plugin") + assertThat(pluginsDir.list()!!.toList()).containsExactly(installed.file.name) + } + + @Test + fun `the same plugin bytes always get the same name and another build another one`() { + val first = installer().install(BundledAddonKind.PLUGIN, "a.cgp", bytes("one")).file.name + val again = installer().install(BundledAddonKind.PLUGIN, "a.cgp", bytes("one")).file.name + val other = installer().install(BundledAddonKind.PLUGIN, "a.cgp", bytes("two")).file.name + + assertThat(again).isEqualTo(first) + assertThat(other).isNotEqualTo(first) + } + + @Test + fun `a template is installed under its bundled name`() { + val installed = installer().install(BundledAddonKind.TEMPLATE, "starter.cgt", bytes("template bytes")) + + assertThat(installed.file).isEqualTo(File(templatesDir, "starter.cgt")) + assertThat(installed.file.readText()).isEqualTo("template bytes") + assertThat(installed.pluginId).isNull() + assertThat(templatesDir.list()!!.toList()).containsExactly("starter.cgt") + } + + @Test + fun `an installed template replaces an older file of its name`() { + templatesDir.mkdirs() + File(templatesDir, "starter.cgt").writeText("old") + + installer().install(BundledAddonKind.TEMPLATE, "starter.cgt", bytes("new")) + + assertThat(File(templatesDir, "starter.cgt").readText()).isEqualTo("new") + assertThat(templatesDir.list()!!.toList()).containsExactly("starter.cgt") + } + + @Test + fun `a plugin copy that fails leaves no file behind`() { + assertThrows(IOException::class.java) { + installer().install(BundledAddonKind.PLUGIN, "a.cgp", failingAfter("truncated")) + } + + assertThat(pluginsDir.list()!!.toList()).isEmpty() + } + + @Test + fun `a template copy that fails leaves no partial file and keeps the old one`() { + templatesDir.mkdirs() + File(templatesDir, "starter.cgt").writeText("old") + + assertThrows(IOException::class.java) { + installer().install(BundledAddonKind.TEMPLATE, "starter.cgt", failingAfter("truncated")) + } + + assertThat(templatesDir.list()!!.toList()).containsExactly("starter.cgt") + assertThat(File(templatesDir, "starter.cgt").readText()).isEqualTo("old") + } + + @Test + fun `a plugin without a readable manifest is refused and leaves no file`() { + assertThrows(IOException::class.java) { + installer(readPluginId = { null }).install(BundledAddonKind.PLUGIN, "a.cgp", bytes("not a plugin")) + } + + assertThat(pluginsDir.list()!!.toList()).isEmpty() + } + + @Test + fun `a plugin whose ID is a path is refused and leaves no file`() { + assertThrows(IllegalArgumentException::class.java) { + installer(readPluginId = { "../escape" }).install(BundledAddonKind.PLUGIN, "a.cgp", bytes("plugin")) + } + + assertThat(pluginsDir.list()!!.toList()).isEmpty() + } +} diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsRecordTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsRecordTest.kt new file mode 100644 index 0000000000..f3869ba61c --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsRecordTest.kt @@ -0,0 +1,136 @@ +package com.itsaky.androidide.assets.addons + +import com.google.common.truth.Truth.assertThat +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File + +class BundledAddonsRecordTest { + @get:Rule + val tempFolder = TemporaryFolder() + + private lateinit var file: File + private lateinit var record: BundledAddonsRecord + + private val state = + BundledAddonsState( + fingerprint = "abc123", + pluginIds = listOf("com.example.one", "com.example.two"), + templateFiles = listOf("starter.cgt"), + ) + + @Before + fun setUp() { + file = File(tempFolder.root, "files/bundled_addons.properties") + record = BundledAddonsRecord(file) + } + + @Test + fun `no file reads as no record`() { + assertThat(record.read()).isNull() + assertThat(record.unreportedFailures()).isEmpty() + assertThat(record.markReported()).isEmpty() + } + + @Test + fun `a written record reads back`() { + record.write(state) + + assertThat(BundledAddonsRecord(file).read()).isEqualTo(state) + } + + @Test + fun `a thin record reads back with an empty bundle`() { + val thin = BundledAddonsState(fingerprint = BundledAddons.fingerprint(emptyList())) + + record.write(thin) + + assertThat(record.read()).isEqualTo(thin) + } + + @Test + fun `writing replaces the whole record and leaves no temporary file`() { + record.write(state) + record.recordFailures(mapOf("com.example.one" to "boom")) + + val next = BundledAddonsState(fingerprint = "def456", pluginIds = listOf("com.example.three")) + record.write(next) + + assertThat(record.read()).isEqualTo(next) + assertThat(file.parentFile!!.list()!!.toList()).containsExactly(file.name) + } + + @Test + fun `an unreadable file reads as no record`() { + file.parentFile!!.mkdirs() + file.writeText("pluginX=\\u12") + + assertThat(record.read()).isNull() + } + + @Test + fun `a file without a fingerprint reads as no record`() { + file.parentFile!!.mkdirs() + file.writeText("plugin.0=com.example.one\n") + + assertThat(record.read()).isNull() + } + + @Test + fun `failures are stored unreported and kept with the bundle`() { + record.write(state) + + record.recordFailures(linkedMapOf("com.example.one" to "boom", "com.example.two" to "bang")) + + assertThat(record.unreportedFailures()) + .containsExactly( + BundledPluginFailure("com.example.one", "boom", reported = false), + BundledPluginFailure("com.example.two", "bang", reported = false), + ).inOrder() + assertThat(record.read()!!.copy(failures = emptyList())).isEqualTo(state) + } + + @Test + fun `failures with odd characters survive`() { + record.write(state) + val message = "line one\nline two = \"quoted\" \\ back: é" + + record.recordFailures(mapOf("com.example.one" to message)) + + assertThat(record.unreportedFailures().single().message).isEqualTo(message) + } + + @Test + fun `markReported hands the failures out once`() { + record.write(state) + record.recordFailures(mapOf("com.example.one" to "boom")) + + val first = record.markReported() + val second = record.markReported() + + assertThat(first).containsExactly(BundledPluginFailure("com.example.one", "boom", reported = false)) + assertThat(second).isEmpty() + assertThat(record.unreportedFailures()).isEmpty() + assertThat(record.read()!!.failures).containsExactly(BundledPluginFailure("com.example.one", "boom", reported = true)) + } + + @Test + fun `a new failure after a report is unreported again`() { + record.write(state) + record.recordFailures(mapOf("com.example.one" to "boom")) + record.markReported() + + record.recordFailures(mapOf("com.example.two" to "bang")) + + assertThat(record.unreportedFailures()).containsExactly(BundledPluginFailure("com.example.two", "bang", reported = false)) + } + + @Test + fun `recording failures without a record does nothing`() { + record.recordFailures(mapOf("com.example.one" to "boom")) + + assertThat(file.exists()).isFalse() + } +} diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsTest.kt new file mode 100644 index 0000000000..f9b2923fe2 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsTest.kt @@ -0,0 +1,185 @@ +package com.itsaky.androidide.assets.addons + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.assets.AssetsInstallationHelper +import org.adfa.constants.ANDROID_SDK_ZIP +import org.adfa.constants.DOCUMENTATION_DB +import org.adfa.constants.GRADLE_API_NAME_JAR_ZIP +import org.adfa.constants.GRADLE_DISTRIBUTION_ARCHIVE_NAME +import org.adfa.constants.LOCAL_MAVEN_REPO_ARCHIVE_ZIP_NAME +import org.adfa.constants.TEMPLATE_CORE_ARCHIVE +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.ByteArrayInputStream +import java.io.InputStream +import java.util.zip.ZipEntry +import java.util.zip.ZipFile +import java.util.zip.ZipOutputStream + +class BundledAddonsTest { + @get:Rule + val tempFolder = TemporaryFolder() + + private class FakeSource( + private val files: Map>, + ) : BundleSource { + override fun names(dir: String) = files[dir]?.keys?.toList().orEmpty() + + override fun size( + dir: String, + name: String, + ) = files.getValue(dir).getValue(name) + + override fun open( + dir: String, + name: String, + ): InputStream = ByteArrayInputStream(ByteArray(0)) + } + + private fun source( + plugins: Map = emptyMap(), + templates: Map = emptyMap(), + ) = FakeSource(mapOf("plugins" to plugins, "templates" to templates)) + + @Test + fun `a thin bundle lists nothing`() { + assertThat(BundledAddons.list(source())).isEmpty() + } + + @Test + fun `a thin build installs exactly the eight fixed entries`() { + assertThat(AssetsInstallationHelper.entriesToInstall(emptyList())) + .containsExactly( + GRADLE_DISTRIBUTION_ARCHIVE_NAME, + ANDROID_SDK_ZIP, + DOCUMENTATION_DB, + LOCAL_MAVEN_REPO_ARCHIVE_ZIP_NAME, + "bootstrap.zip", + GRADLE_API_NAME_JAR_ZIP, + "plugin-artifacts.zip", + TEMPLATE_CORE_ARCHIVE, + ).inOrder() + } + + @Test + fun `a fat build installs the fixed entries then each bundled file`() { + val bundled = BundledAddons.list(source(plugins = mapOf("a.cgp" to 5L), templates = mapOf("t.cgt" to 7L))) + + val entries = AssetsInstallationHelper.entriesToInstall(bundled) + + assertThat(entries).hasSize(10) + assertThat(entries.take(8)).containsExactlyElementsIn(AssetsInstallationHelper.entriesToInstall(emptyList())).inOrder() + assertThat(entries.takeLast(2)).containsExactly("plugins/a.cgp", "templates/t.cgt").inOrder() + } + + @Test + fun `some entries carry their size and sort by name, plugins first`() { + val entries = + BundledAddons.list( + source( + plugins = mapOf("b.cgp" to 20L, "a.cgp" to 10L), + templates = mapOf("t.cgt" to 30L), + ), + ) + + assertThat(entries) + .containsExactly( + BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 10L), + BundledEntry(BundledAddonKind.PLUGIN, "b.cgp", 20L), + BundledEntry(BundledAddonKind.TEMPLATE, "t.cgt", 30L), + ).inOrder() + assertThat(entries.map { it.entryName }).containsExactly("plugins/a.cgp", "plugins/b.cgp", "templates/t.cgt").inOrder() + } + + @Test + fun `many entries are all listed`() { + val plugins = (1..200).associate { "p$it.cgp" to it.toLong() } + val templates = (1..150).associate { "t$it.cgt" to it.toLong() } + + assertThat(BundledAddons.list(source(plugins, templates))).hasSize(350) + } + + @Test + fun `files that are not add-ons of their folder are ignored`() { + val entries = + BundledAddons.list( + source( + plugins = mapOf("a.cgp" to 1L, "readme.txt" to 2L, "t.cgt" to 3L, ".hidden.cgp" to 4L, "sub/b.cgp" to 5L, "UPPER.CGP" to 6L), + templates = mapOf("t.cgt" to 7L, "a.cgp" to 8L), + ), + ) + + assertThat(entries.map { it.entryName }).containsExactly("plugins/UPPER.CGP", "plugins/a.cgp", "templates/t.cgt").inOrder() + } + + @Test + fun `parse recognizes only the names a listing produces`() { + assertThat(BundledAddons.parse("plugins/a.cgp")).isEqualTo(BundledAddonKind.PLUGIN to "a.cgp") + assertThat(BundledAddons.parse("templates/t.cgt")).isEqualTo(BundledAddonKind.TEMPLATE to "t.cgt") + assertThat(BundledAddons.parse("plugins/t.cgt")).isNull() + assertThat(BundledAddons.parse("plugins/../a.cgp")).isNull() + assertThat(BundledAddons.parse("core.cgt")).isNull() + assertThat(BundledAddons.parse("plugin-artifacts.zip")).isNull() + } + + @Test + fun `the fingerprint is stable for the same bundle in any order`() { + val a = BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 10L) + val t = BundledEntry(BundledAddonKind.TEMPLATE, "t.cgt", 30L) + + assertThat(BundledAddons.fingerprint(listOf(a, t))).isEqualTo(BundledAddons.fingerprint(listOf(t, a))) + assertThat(BundledAddons.fingerprint(listOf(a, t))).isEqualTo(BundledAddons.fingerprint(listOf(a, t))) + } + + @Test + fun `the fingerprint changes with a name, a size, a kind or an entry`() { + val a = BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 10L) + val base = BundledAddons.fingerprint(listOf(a)) + + assertThat(BundledAddons.fingerprint(listOf(a.copy(fileName = "b.cgp")))).isNotEqualTo(base) + assertThat(BundledAddons.fingerprint(listOf(a.copy(size = 11L)))).isNotEqualTo(base) + assertThat(BundledAddons.fingerprint(listOf(a.copy(kind = BundledAddonKind.TEMPLATE, fileName = "a.cgt")))).isNotEqualTo(base) + assertThat(BundledAddons.fingerprint(listOf(a, BundledEntry(BundledAddonKind.TEMPLATE, "t.cgt", 1L)))).isNotEqualTo(base) + assertThat(BundledAddons.fingerprint(emptyList())).isNotEqualTo(base) + } + + @Test + fun `the empty bundle has a fingerprint`() { + assertThat(BundledAddons.fingerprint(emptyList())).matches("[0-9a-f]{64}") + } + + @Test + fun `a zip source lists only the direct files of a folder, with their sizes`() { + val zipFile = tempFolder.newFile("assets.zip") + ZipOutputStream(zipFile.outputStream()).use { zip -> + listOf("bootstrap.zip" to 3, "plugins/a.cgp" to 5, "plugins/nested/b.cgp" to 9, "templates/t.cgt" to 7).forEach { (name, size) -> + zip.putNextEntry(ZipEntry(name)) + zip.write(ByteArray(size)) + zip.closeEntry() + } + } + + ZipFile(zipFile).use { zip -> + val entries = BundledAddons.list(ZipBundleSource(zip)) + + assertThat(entries) + .containsExactly( + BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 5L), + BundledEntry(BundledAddonKind.TEMPLATE, "t.cgt", 7L), + ).inOrder() + assertThat(ZipBundleSource(zip).open("plugins", "a.cgp").use { it.readBytes() }).hasLength(5) + } + } + + @Test + fun `a zip source without the folders lists nothing`() { + val zipFile = tempFolder.newFile("thin.zip") + ZipOutputStream(zipFile.outputStream()).use { zip -> + zip.putNextEntry(ZipEntry("bootstrap.zip")) + zip.closeEntry() + } + + ZipFile(zipFile).use { assertThat(BundledAddons.list(ZipBundleSource(it))).isEmpty() } + } +} diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledPluginStartupTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledPluginStartupTest.kt new file mode 100644 index 0000000000..0237d88eff --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledPluginStartupTest.kt @@ -0,0 +1,103 @@ +package com.itsaky.androidide.assets.addons + +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertThrows +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File + +class BundledPluginStartupTest { + @get:Rule + val tempFolder = TemporaryFolder() + + private lateinit var record: BundledAddonsRecord + private var reloads = 0 + + @Before + fun setUp() { + record = BundledAddonsRecord(File(tempFolder.root, "bundled_addons.properties")) + reloads = 0 + } + + private fun startup( + reload: suspend () -> Unit = { reloads++ }, + loadError: (String) -> String? = { null }, + ) = BundledPluginStartup(record, reload, loadError) + + private fun writeBundle(vararg pluginIds: String) = record.write(BundledAddonsState("fp", pluginIds.toList())) + + @Test + fun `no record or a thin one starts nothing`() { + runBlocking { + startup().start() + record.write(BundledAddonsState("fp")) + startup().start() + + assertThat(reloads).isEqualTo(0) + } + } + + @Test + fun `a bundle with plugins reloads once and records nothing when all load`() { + runBlocking { + writeBundle("a", "b") + + startup().start() + + assertThat(reloads).isEqualTo(1) + assertThat(record.unreportedFailures()).isEmpty() + } + } + + @Test + fun `only bundled plugins that report a load error are recorded, unreported`() { + runBlocking { + writeBundle("a", "b") + val errors = mapOf("b" to "needs a newer IDE", "other" to "not ours") + + startup(loadError = errors::get).start() + + assertThat(record.unreportedFailures()).containsExactly(BundledPluginFailure("b", "needs a newer IDE", reported = false)) + } + } + + @Test + fun `a reload that throws is recorded for every bundled plugin and does not escape`() { + runBlocking { + writeBundle("a", "b") + + startup(reload = { throw IllegalStateException("registry broken") }).start() + + assertThat(record.unreportedFailures().map { it.pluginId to it.message }) + .containsExactly("a" to "registry broken", "b" to "registry broken") + } + } + + @Test + fun `cancellation is not swallowed`() { + writeBundle("a") + + assertThrows(CancellationException::class.java) { + runBlocking { startup(reload = { throw CancellationException("stop") }).start() } + } + assertThat(record.unreportedFailures()).isEmpty() + } + + @Test + fun `a failure is reported once`() { + runBlocking { + writeBundle("a") + startup(loadError = { "boom" }).start() + + val first = record.markReported() + val second = record.markReported() + + assertThat(first.map { it.pluginId }).containsExactly("a") + assertThat(second).isEmpty() + } + } +} diff --git a/resources/src/main/res/values/strings.xml b/resources/src/main/res/values/strings.xml index ce99d1624d..b29987ca32 100644 --- a/resources/src/main/res/values/strings.xml +++ b/resources/src/main/res/values/strings.xml @@ -109,6 +109,8 @@ Missing installation files. %1$s installation might be corrupt or incomplete. Assets file \'%1$s\' not found. Copy it to %2$s, then restart %3$s. + + Some plugins that came with the app did not start:\n%1$s The picked file is not a directory. Please wait for a moment. Not enough storage available for installation. An additional %1$.1fGB is required on the internal storage partition. You currently have %2$.1fGB available. From 56974f55cdb9fc40914823d2477d396d2d486cdc Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 15:48:14 +0000 Subject: [PATCH 03/22] ADFA-7238: Report a bundled plugin with an unreadable manifest instead of failing setup A bundled plugin whose manifest could not be read, or whose ID was invalid, threw from the asset phase and failed the whole IDE setup. The design says a bad bundled plugin must never block setup. - BundledAddonInstaller returns such a plugin as an InstalledAddon with no file and a failure message (keyed by its bundled file name); a write error such as a full disk still propagates. A throwing manifest reader counts as unreadable. - The installation stores those failures in the record, so the main screen lists them in the same error bar as plugins that failed to load. - recordFailures now merges: failures under other keys are kept, so the plugin reload after setup no longer erases the install-time ones. Tests updated and added for both. Not compiled or run in this environment (no Android SDK, no flox), so the new tests have not been shown to fail without the fix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- .../assets/AssetsInstallationHelper.kt | 8 ++- .../assets/addons/BundledAddonInstaller.kt | 46 +++++++++++------ .../assets/addons/BundledAddonsRecord.kt | 6 ++- .../addons/BundledAddonInstallerTest.kt | 50 ++++++++++++------- .../assets/addons/BundledAddonsRecordTest.kt | 12 +++++ 5 files changed, 86 insertions(+), 36 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt b/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt index ef01348467..8808482853 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt @@ -10,6 +10,7 @@ import com.itsaky.androidide.assets.addons.BundledAddons import com.itsaky.androidide.assets.addons.BundledAddonsRecord import com.itsaky.androidide.assets.addons.BundledAddonsState import com.itsaky.androidide.assets.addons.BundledEntry +import com.itsaky.androidide.assets.addons.BundledPluginFailure import com.itsaky.androidide.resources.R import com.itsaky.androidide.utils.ContainedPathResolver import com.itsaky.androidide.utils.ContainedPathResolver.Resolution @@ -259,8 +260,13 @@ object AssetsInstallationHelper { templateFiles = installed .filter { it.kind == BundledAddonKind.TEMPLATE } - .map { it.file.name } + .mapNotNull { it.file?.name } .sorted(), + // Plugins rejected while copying; the main screen reports them with load failures. + failures = + installed + .mapNotNull { addon -> addon.failure?.let { BundledPluginFailure(addon.sourceName ?: "?", it) } } + .sortedBy { it.pluginId }, ), ) } finally { diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt index d4d3c80df9..82f5ee7438 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt @@ -7,11 +7,17 @@ import java.io.File import java.io.IOException import java.io.InputStream -/** An add-on file that reached its folder. [pluginId] is set for a plugin. */ +/** + * A bundled add-on after installation. [pluginId] is set for a plugin that reached its folder. A + * plugin whose manifest names no valid ID has no [file] and carries a [failure] instead, with the + * bundled file name in [sourceName]: it is reported to the user, and must not fail the setup. + */ data class InstalledAddon( val kind: BundledAddonKind, - val file: File, + val file: File?, val pluginId: String?, + val failure: String? = null, + val sourceName: String? = null, ) /** @@ -34,29 +40,41 @@ class BundledAddonInstaller( input: InputStream, ): InstalledAddon = when (kind) { - BundledAddonKind.PLUGIN -> installPlugin(input) + BundledAddonKind.PLUGIN -> installPlugin(fileName, input) BundledAddonKind.TEMPLATE -> { val file = AtomicFiles.writeInto(templatesDir, { input.copyToFile(it) }, { fileName }) InstalledAddon(kind, file, null) } } - private fun installPlugin(input: InputStream): InstalledAddon { + private fun installPlugin( + fileName: String, + input: InputStream, + ): InstalledAddon { var pluginId: String? = null val file = - AtomicFiles.writeInto( - pluginsDir, - { input.copyToFile(it) }, - { copy -> - val id = readPluginId(copy) ?: throw IOException("Bundled plugin has no readable manifest") - checkPluginId(id).getOrThrow() - pluginId = id - "${PluginBuildFiles.fileStem(id, copy)}.$PLUGIN_ARCHIVE_EXTENSION" - }, - ) + try { + AtomicFiles.writeInto( + pluginsDir, + { input.copyToFile(it) }, + { copy -> + val id = runCatching { readPluginId(copy) }.getOrNull() ?: throw RejectedPluginException("it has no readable manifest") + checkPluginId(id).onFailure { throw RejectedPluginException(it.message ?: "invalid plugin ID") } + pluginId = id + "${PluginBuildFiles.fileStem(id, copy)}.$PLUGIN_ARCHIVE_EXTENSION" + }, + ) + } catch (e: RejectedPluginException) { + // writeInto has deleted the scratch copy. A write error (disk full) still propagates. + return InstalledAddon(BundledAddonKind.PLUGIN, null, null, failure = e.message, sourceName = fileName) + } return InstalledAddon(BundledAddonKind.PLUGIN, file, pluginId) } + private class RejectedPluginException( + message: String, + ) : IOException(message) + private fun InputStream.copyToFile(dest: File) { dest.outputStream().use { out -> copyTo(out) } } diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonsRecord.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonsRecord.kt index 908f535230..4d2029ec88 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonsRecord.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonsRecord.kt @@ -77,13 +77,15 @@ class BundledAddonsRecord( } /** - * Stores [failures] (plugin ID to message) as unreported, replacing any earlier ones. + * Stores [failures] (plugin ID to message) as unreported. A failure already recorded under + * another key (a plugin rejected while copying) is kept; one under the same key is replaced. * Does nothing when there is no record: failures belong to an installed bundle. */ @Synchronized fun recordFailures(failures: Map) { val state = read() ?: return - write(state.copy(failures = failures.map { (id, message) -> BundledPluginFailure(id, message) })) + val kept = state.failures.filterNot { it.pluginId in failures } + write(state.copy(failures = kept + failures.map { (id, message) -> BundledPluginFailure(id, message) })) } /** The failures the user has not been told about, in the order recorded. */ diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt index 9e216edb68..0616586a91 100644 --- a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt @@ -42,20 +42,20 @@ class BundledAddonInstallerTest { fun `a plugin is installed as pluginId-hash dot cgp`() { val installed = installer().install(BundledAddonKind.PLUGIN, "whatever.cgp", bytes("plugin bytes")) - val expectedStem = PluginBuildFiles.fileStem("com.example.plugin", installed.file) - assertThat(installed.file.name).isEqualTo("$expectedStem.cgp") - assertThat(installed.file.name).startsWith("com.example.plugin-") - assertThat(installed.file.parentFile).isEqualTo(pluginsDir) - assertThat(installed.file.readText()).isEqualTo("plugin bytes") + val expectedStem = PluginBuildFiles.fileStem("com.example.plugin", installed.file!!) + assertThat(installed.file!!.name).isEqualTo("$expectedStem.cgp") + assertThat(installed.file!!.name).startsWith("com.example.plugin-") + assertThat(installed.file!!.parentFile).isEqualTo(pluginsDir) + assertThat(installed.file!!.readText()).isEqualTo("plugin bytes") assertThat(installed.pluginId).isEqualTo("com.example.plugin") - assertThat(pluginsDir.list()!!.toList()).containsExactly(installed.file.name) + assertThat(pluginsDir.list()!!.toList()).containsExactly(installed.file!!.name) } @Test fun `the same plugin bytes always get the same name and another build another one`() { - val first = installer().install(BundledAddonKind.PLUGIN, "a.cgp", bytes("one")).file.name - val again = installer().install(BundledAddonKind.PLUGIN, "a.cgp", bytes("one")).file.name - val other = installer().install(BundledAddonKind.PLUGIN, "a.cgp", bytes("two")).file.name + val first = installer().install(BundledAddonKind.PLUGIN, "a.cgp", bytes("one")).file!!.name + val again = installer().install(BundledAddonKind.PLUGIN, "a.cgp", bytes("one")).file!!.name + val other = installer().install(BundledAddonKind.PLUGIN, "a.cgp", bytes("two")).file!!.name assertThat(again).isEqualTo(first) assertThat(other).isNotEqualTo(first) @@ -65,8 +65,8 @@ class BundledAddonInstallerTest { fun `a template is installed under its bundled name`() { val installed = installer().install(BundledAddonKind.TEMPLATE, "starter.cgt", bytes("template bytes")) - assertThat(installed.file).isEqualTo(File(templatesDir, "starter.cgt")) - assertThat(installed.file.readText()).isEqualTo("template bytes") + assertThat(installed.file!!).isEqualTo(File(templatesDir, "starter.cgt")) + assertThat(installed.file!!.readText()).isEqualTo("template bytes") assertThat(installed.pluginId).isNull() assertThat(templatesDir.list()!!.toList()).containsExactly("starter.cgt") } @@ -105,20 +105,32 @@ class BundledAddonInstallerTest { } @Test - fun `a plugin without a readable manifest is refused and leaves no file`() { - assertThrows(IOException::class.java) { - installer(readPluginId = { null }).install(BundledAddonKind.PLUGIN, "a.cgp", bytes("not a plugin")) - } + fun `a plugin without a readable manifest is reported, not thrown, and leaves no file`() { + val result = installer(readPluginId = { null }).install(BundledAddonKind.PLUGIN, "a.cgp", bytes("not a plugin")) + assertThat(result.file).isNull() + assertThat(result.pluginId).isNull() + assertThat(result.sourceName).isEqualTo("a.cgp") + assertThat(result.failure).isNotNull() assertThat(pluginsDir.list()!!.toList()).isEmpty() } @Test - fun `a plugin whose ID is a path is refused and leaves no file`() { - assertThrows(IllegalArgumentException::class.java) { - installer(readPluginId = { "../escape" }).install(BundledAddonKind.PLUGIN, "a.cgp", bytes("plugin")) - } + fun `a plugin whose manifest reader throws is reported, not thrown`() { + val result = + installer(readPluginId = { throw IllegalStateException("bad zip") }) + .install(BundledAddonKind.PLUGIN, "a.cgp", bytes("not a plugin")) + + assertThat(result.failure).isNotNull() + assertThat(pluginsDir.list()!!.toList()).isEmpty() + } + + @Test + fun `a plugin whose ID is a path is reported, not thrown, and leaves no file`() { + val result = installer(readPluginId = { "../escape" }).install(BundledAddonKind.PLUGIN, "a.cgp", bytes("plugin")) + assertThat(result.file).isNull() + assertThat(result.failure).contains("../escape") assertThat(pluginsDir.list()!!.toList()).isEmpty() } } diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsRecordTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsRecordTest.kt index f3869ba61c..b453d631cf 100644 --- a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsRecordTest.kt +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsRecordTest.kt @@ -127,6 +127,18 @@ class BundledAddonsRecordTest { assertThat(record.unreportedFailures()).containsExactly(BundledPluginFailure("com.example.two", "bang", reported = false)) } + @Test + fun `recording load failures keeps failures recorded under other keys`() { + record.write(state.copy(failures = listOf(BundledPluginFailure("broken.cgp", "it has no readable manifest")))) + + record.recordFailures(mapOf("com.example.one" to "boom")) + + assertThat(record.unreportedFailures()).containsExactly( + BundledPluginFailure("broken.cgp", "it has no readable manifest"), + BundledPluginFailure("com.example.one", "boom"), + ) + } + @Test fun `recording failures without a record does nothing`() { record.recordFailures(mapOf("com.example.one" to "boom")) From 8625acc3e190ed23a5865e6da5d584bd0035177b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 16:59:33 +0000 Subject: [PATCH 04/22] ADFA-7238: Fix lint errors the formatter cannot fix Spotless reported lines over 140 characters in BundledAddonInstaller and BundledAddonsTest; wrapped. No behaviour change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- .../assets/addons/BundledAddonInstaller.kt | 4 +++- .../androidide/assets/addons/BundledAddonsTest.kt | 13 +++++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt index 82f5ee7438..2fcfcf3278 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt @@ -58,7 +58,9 @@ class BundledAddonInstaller( pluginsDir, { input.copyToFile(it) }, { copy -> - val id = runCatching { readPluginId(copy) }.getOrNull() ?: throw RejectedPluginException("it has no readable manifest") + val id = + runCatching { readPluginId(copy) }.getOrNull() + ?: throw RejectedPluginException("it has no readable manifest") checkPluginId(id).onFailure { throw RejectedPluginException(it.message ?: "invalid plugin ID") } pluginId = id "${PluginBuildFiles.fileStem(id, copy)}.$PLUGIN_ARCHIVE_EXTENSION" diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsTest.kt index f9b2923fe2..fc5413dd1e 100644 --- a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsTest.kt +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsTest.kt @@ -105,7 +105,15 @@ class BundledAddonsTest { val entries = BundledAddons.list( source( - plugins = mapOf("a.cgp" to 1L, "readme.txt" to 2L, "t.cgt" to 3L, ".hidden.cgp" to 4L, "sub/b.cgp" to 5L, "UPPER.CGP" to 6L), + plugins = + mapOf( + "a.cgp" to 1L, + "readme.txt" to 2L, + "t.cgt" to 3L, + ".hidden.cgp" to 4L, + "sub/b.cgp" to 5L, + "UPPER.CGP" to 6L, + ), templates = mapOf("t.cgt" to 7L, "a.cgp" to 8L), ), ) @@ -153,7 +161,8 @@ class BundledAddonsTest { fun `a zip source lists only the direct files of a folder, with their sizes`() { val zipFile = tempFolder.newFile("assets.zip") ZipOutputStream(zipFile.outputStream()).use { zip -> - listOf("bootstrap.zip" to 3, "plugins/a.cgp" to 5, "plugins/nested/b.cgp" to 9, "templates/t.cgt" to 7).forEach { (name, size) -> + val entries = listOf("bootstrap.zip" to 3, "plugins/a.cgp" to 5, "plugins/nested/b.cgp" to 9, "templates/t.cgt" to 7) + entries.forEach { (name, size) -> zip.putNextEntry(ZipEntry(name)) zip.write(ByteArray(size)) zip.closeEntry() From 367c45581e15e8f7a53828d2205fbf33c4bce88d Mon Sep 17 00:00:00 2001 From: ADFA Date: Sat, 21 Nov 2026 17:01:52 +0000 Subject: [PATCH 05/22] style: spotless reformat, no functional change --- .../androidide/assets/addons/BundledAddonInstaller.kt | 5 ++++- .../assets/AssetsInstallationHelperBundleTest.kt | 8 ++++++-- .../androidide/assets/addons/BundledAddonInstallerTest.kt | 6 +++++- flox/base/.flox/env/manifest.lock | 7 ++++--- flox/base/.flox/env/manifest.toml | 3 ++- 5 files changed, 21 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt index 2fcfcf3278..d2c43655f1 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt @@ -40,7 +40,10 @@ class BundledAddonInstaller( input: InputStream, ): InstalledAddon = when (kind) { - BundledAddonKind.PLUGIN -> installPlugin(fileName, input) + BundledAddonKind.PLUGIN -> { + installPlugin(fileName, input) + } + BundledAddonKind.TEMPLATE -> { val file = AtomicFiles.writeInto(templatesDir, { input.copyToFile(it) }, { fileName }) InstalledAddon(kind, file, null) diff --git a/app/src/test/java/com/itsaky/androidide/assets/AssetsInstallationHelperBundleTest.kt b/app/src/test/java/com/itsaky/androidide/assets/AssetsInstallationHelperBundleTest.kt index b284d5851e..46d7a5b4f4 100644 --- a/app/src/test/java/com/itsaky/androidide/assets/AssetsInstallationHelperBundleTest.kt +++ b/app/src/test/java/com/itsaky/androidide/assets/AssetsInstallationHelperBundleTest.kt @@ -86,7 +86,9 @@ class AssetsInstallationHelperBundleTest { @Test fun `every entry is installed, then the record is written`() = runBlocking { - val seen = java.util.concurrent.ConcurrentHashMap.newKeySet() + val seen = + java.util.concurrent.ConcurrentHashMap + .newKeySet() every { SplitAssetsInstaller.listBundledAddons(any()) } returns bundle every { SplitAssetsInstaller.installedAddons() } returns bundle.map { installed(it.fileName) } coEvery { SplitAssetsInstaller.doInstall(any(), any(), any(), any()) } coAnswers { @@ -111,7 +113,9 @@ class AssetsInstallationHelperBundleTest { @Test fun `a thin build installs the eight entries and records an empty bundle`() = runBlocking { - val seen = java.util.concurrent.ConcurrentHashMap.newKeySet() + val seen = + java.util.concurrent.ConcurrentHashMap + .newKeySet() every { SplitAssetsInstaller.listBundledAddons(any()) } returns emptyList() every { SplitAssetsInstaller.installedAddons() } returns emptyList() coEvery { SplitAssetsInstaller.doInstall(any(), any(), any(), any()) } coAnswers { seen += arg(3) } diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt index 0616586a91..997cd12faf 100644 --- a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt @@ -25,7 +25,11 @@ class BundledAddonInstallerTest { templatesDir = File(tempFolder.root, "templates") } - private fun installer(readPluginId: (File) -> String? = { "com.example.plugin" }) = BundledAddonInstaller(pluginsDir, templatesDir, readPluginId) + private fun installer( + readPluginId: (File) -> String? = { + "com.example.plugin" + }, + ) = BundledAddonInstaller(pluginsDir, templatesDir, readPluginId) private fun bytes(text: String): InputStream = ByteArrayInputStream(text.toByteArray()) diff --git a/flox/base/.flox/env/manifest.lock b/flox/base/.flox/env/manifest.lock index c95da03f9f..f606a0bbcf 100644 --- a/flox/base/.flox/env/manifest.lock +++ b/flox/base/.flox/env/manifest.lock @@ -1,13 +1,14 @@ { "lockfile-version": 1, "manifest": { - "version": 1, + "schema-version": "1.11.0", "install": { "android-studio-tools": { "pkg-path": "android-studio-tools" }, "awscli2": { - "pkg-path": "awscli2" + "pkg-path": "awscli2", + "outputs": "all" }, "gh": { "pkg-path": "gh" @@ -551,4 +552,4 @@ "priority": 5 } ] -} \ No newline at end of file +} diff --git a/flox/base/.flox/env/manifest.toml b/flox/base/.flox/env/manifest.toml index 84f81eee24..228f5b0541 100644 --- a/flox/base/.flox/env/manifest.toml +++ b/flox/base/.flox/env/manifest.toml @@ -6,7 +6,7 @@ ## ## ------------------------------------------------------------------- # Flox manifest version managed by Flox CLI -version = 1 +schema-version = "1.11.0" ## Install Packages -------------------------------------------------- @@ -19,6 +19,7 @@ jdk17.pkg-path = "jdk17" android-studio-tools.pkg-path = "android-studio-tools" gh.pkg-path = "gh" awscli2.pkg-path = "awscli2" +awscli2.outputs = "all" # gum.pkg-path = "gum" # gum.version = "^0.14.5" From 45f0eb053b74e2f676bd9b986e448bde79afbe13 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 17:03:01 +0000 Subject: [PATCH 06/22] Revert flox manifest changes swept in by the Spotless apply workflow The workflow commits with `git commit -am`, which picked up the flox base environment files that `flox activate` upgraded on the runner (manifest schema version, awscli2 outputs). They are unrelated to this branch; restore them to their stage versions. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- flox/base/.flox/env/manifest.lock | 7 +++---- flox/base/.flox/env/manifest.toml | 3 +-- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/flox/base/.flox/env/manifest.lock b/flox/base/.flox/env/manifest.lock index f606a0bbcf..c95da03f9f 100644 --- a/flox/base/.flox/env/manifest.lock +++ b/flox/base/.flox/env/manifest.lock @@ -1,14 +1,13 @@ { "lockfile-version": 1, "manifest": { - "schema-version": "1.11.0", + "version": 1, "install": { "android-studio-tools": { "pkg-path": "android-studio-tools" }, "awscli2": { - "pkg-path": "awscli2", - "outputs": "all" + "pkg-path": "awscli2" }, "gh": { "pkg-path": "gh" @@ -552,4 +551,4 @@ "priority": 5 } ] -} +} \ No newline at end of file diff --git a/flox/base/.flox/env/manifest.toml b/flox/base/.flox/env/manifest.toml index 228f5b0541..84f81eee24 100644 --- a/flox/base/.flox/env/manifest.toml +++ b/flox/base/.flox/env/manifest.toml @@ -6,7 +6,7 @@ ## ## ------------------------------------------------------------------- # Flox manifest version managed by Flox CLI -schema-version = "1.11.0" +version = 1 ## Install Packages -------------------------------------------------- @@ -19,7 +19,6 @@ jdk17.pkg-path = "jdk17" android-studio-tools.pkg-path = "android-studio-tools" gh.pkg-path = "gh" awscli2.pkg-path = "awscli2" -awscli2.outputs = "all" # gum.pkg-path = "gum" # gum.version = "^0.14.5" From 58082be522227659405d241bcffc86fbfa705802 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 17:34:08 +0000 Subject: [PATCH 07/22] ADFA-7238: Fix review findings - BundledAddonsRecord.inFilesDir returns one shared instance per file. Every caller made its own instance before, so @Synchronized locked nothing across the setup and the main screen, which both read, change and rewrite the record. - A bundled template named core.cgt (any case) is ignored: core.cgt is installed by its own entry into the same folder, in the same parallel phase. - The release build takes bundled files with the extension in any case, as the debug zip already did. - An Error thrown while reading a plugin's manifest is no longer reported as an unreadable manifest; only exceptions are. - Correct the comment on ensureActive() after joinAll(): a failed copy has already cancelled the scope, so the call is a safeguard, not the fix. Tests added for the shared record and the core.cgt exclusion. Not compiled or run in this environment. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- app/build.gradle.kts | 15 +++++++++++++-- .../androidide/assets/AssetsInstallationHelper.kt | 4 ++-- .../assets/addons/BundledAddonInstaller.kt | 7 +++++-- .../androidide/assets/addons/BundledAddons.kt | 8 +++++++- .../assets/addons/BundledAddonsRecord.kt | 8 +++++++- .../assets/addons/BundledAddonsRecordTest.kt | 7 +++++++ .../androidide/assets/addons/BundledAddonsTest.kt | 8 ++++++++ 7 files changed, 49 insertions(+), 8 deletions(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index d60fe816f0..40504e120f 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -717,6 +717,16 @@ abstract class StageBundledAddons : DefaultTask() { } } +/** A bundled add-on file: directly in its folder, not hidden, with [extension] in any case. */ +fun isBundledAddon( + element: FileTreeElement, + extension: String, +): Boolean = + !element.isDirectory && + element.relativePath.segments.size == 1 && + !element.name.startsWith(".") && + element.name.endsWith(".$extension", ignoreCase = true) + androidComponents.onVariants { variant -> val variantName = variant.name.replaceFirstChar(Char::uppercaseChar) val flavorName = variant.flavorName!! @@ -724,8 +734,9 @@ androidComponents.onVariants { variant -> if (hasBundledAssets(variant)) { val stageBundledAddons = tasks.register("stage${variantName}BundledAddons") { - pluginFiles.from(fileTree(rootProject.file("assets/plugins")) { include("*.cgp") }) - templateFiles.from(fileTree(rootProject.file("assets/templates")) { include("*.cgt") }) + // Top-level files only, extension in any case, as the debug zip takes them. + pluginFiles.from(fileTree(rootProject.file("assets/plugins")) { include { isBundledAddon(it, "cgp") } }) + templateFiles.from(fileTree(rootProject.file("assets/templates")) { include { isBundledAddon(it, "cgt") } }) outputDirectory.set(layout.buildDirectory.dir("intermediates/bundled-addons/${variant.name}")) } variant.sources.assets?.addGeneratedSourceDirectory( diff --git a/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt b/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt index 8808482853..e6d07cc638 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt @@ -247,8 +247,8 @@ object AssetsInstallationHelper { // then cancel progress updater progressUpdater.cancel() - // joinAll() does not rethrow a failed child, and returns at once when they have all - // finished already: without this a failed copy would still get its record written. + // A failed copy has already cancelled this scope, so joinAll() throws; this keeps the record + // unwritable after any failure even if that changes. ensureActive() // Last, and only here, so a record means every file of the bundle is in place. diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt index d2c43655f1..cb263c33bf 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt @@ -62,8 +62,11 @@ class BundledAddonInstaller( { input.copyToFile(it) }, { copy -> val id = - runCatching { readPluginId(copy) }.getOrNull() - ?: throw RejectedPluginException("it has no readable manifest") + try { + readPluginId(copy) + } catch (e: Exception) { + null + } ?: throw RejectedPluginException("it has no readable manifest") checkPluginId(id).onFailure { throw RejectedPluginException(it.message ?: "invalid plugin ID") } pluginId = id "${PluginBuildFiles.fileStem(id, copy)}.$PLUGIN_ARCHIVE_EXTENSION" diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt index dcf61fc5b8..c2071fccc6 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt @@ -2,6 +2,7 @@ package com.itsaky.androidide.assets.addons import org.adfa.constants.PLUGIN_ARCHIVE_EXTENSION import org.adfa.constants.TEMPLATE_ARCHIVE_EXTENSION +import org.adfa.constants.TEMPLATE_CORE_ARCHIVE import java.io.InputStream import java.security.MessageDigest @@ -81,5 +82,10 @@ object BundledAddons { private fun isAddonFile( kind: BundledAddonKind, fileName: String, - ): Boolean = '/' !in fileName && !fileName.startsWith(".") && fileName.endsWith(".${kind.extension}", ignoreCase = true) + ): Boolean = + '/' !in fileName && + !fileName.startsWith(".") && + fileName.endsWith(".${kind.extension}", ignoreCase = true) && + // core.cgt is installed by its own entry into the same folder. + !(kind == BundledAddonKind.TEMPLATE && fileName.equals(TEMPLATE_CORE_ARCHIVE, ignoreCase = true)) } diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonsRecord.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonsRecord.kt index 4d2029ec88..33f8590df6 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonsRecord.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonsRecord.kt @@ -4,6 +4,7 @@ import java.io.File import java.io.IOException import java.util.Properties import java.util.UUID +import java.util.concurrent.ConcurrentHashMap /** A bundled plugin that did not load, and whether the user has been told. */ data class BundledPluginFailure( @@ -132,6 +133,11 @@ class BundledAddonsRecord( private const val TEMPLATE = "template" private const val FAILURE = "failure" - fun inFilesDir(filesDir: File) = BundledAddonsRecord(File(filesDir, FILE_NAME)) + // One instance per file, so @Synchronized serializes every caller: the setup and the main screen + // both read, change and rewrite the file. + private val instances = ConcurrentHashMap() + + fun inFilesDir(filesDir: File): BundledAddonsRecord = + instances.computeIfAbsent(File(filesDir, FILE_NAME).canonicalPath) { BundledAddonsRecord(File(it)) } } } diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsRecordTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsRecordTest.kt index b453d631cf..ce5e77bf0f 100644 --- a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsRecordTest.kt +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsRecordTest.kt @@ -145,4 +145,11 @@ class BundledAddonsRecordTest { assertThat(file.exists()).isFalse() } + + @Test + fun `every caller of one files folder shares one record, so its lock covers them all`() { + val filesDir = File(tempFolder.root, "files") + + assertThat(BundledAddonsRecord.inFilesDir(filesDir)).isSameInstanceAs(BundledAddonsRecord.inFilesDir(File(filesDir, "."))) + } } diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsTest.kt index fc5413dd1e..1e76ed089d 100644 --- a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsTest.kt +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsTest.kt @@ -121,6 +121,14 @@ class BundledAddonsTest { assertThat(entries.map { it.entryName }).containsExactly("plugins/UPPER.CGP", "plugins/a.cgp", "templates/t.cgt").inOrder() } + @Test + fun `a bundled template named like the core template is ignored`() { + val templates = mapOf("core.cgt" to 1L, "Core.CGT" to 2L, "t.cgt" to 3L) + val entries = BundledAddons.list(source(templates = templates)) + + assertThat(entries.map { it.entryName }).containsExactly("templates/t.cgt") + } + @Test fun `parse recognizes only the names a listing produces`() { assertThat(BundledAddons.parse("plugins/a.cgp")).isEqualTo(BundledAddonKind.PLUGIN to "a.cgp") From ddec4d2f1ffeaf95542beba96f88388343152c7b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 18:21:29 +0000 Subject: [PATCH 08/22] ADFA-7238: Address review findings - MainActivity: show the bundled-plugin failure bar (flashErrorAwaitShown) before marking failures reported; guard against a concurrent report - PluginManager: record an activation failure in loadFailures so getLoadError reports it - PluginManager: loadAllPlugins skips files already loaded, so a plugin is not activated twice; load errors of loaded plugins are kept - BundledAddonInstaller: reject a plugin ID whose file name exceeds 255 UTF-8 bytes, with a test - app/build.gradle.kts: never bundle core.cgt (release staging and debug zip), as BundledAddons.isAddonFile - .gitignore: ignore uppercase *.CGP / *.CGT in the bundle folders Not compiled or tested in this environment (no Android SDK). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- .gitignore | 2 + app/build.gradle.kts | 11 +++++- .../androidide/activities/MainActivity.kt | 38 ++++++++++++------- .../assets/addons/BundledAddonInstaller.kt | 11 +++++- .../addons/BundledAddonInstallerTest.kt | 10 +++++ .../plugins/manager/core/PluginManager.kt | 12 ++++-- 6 files changed, 64 insertions(+), 20 deletions(-) diff --git a/.gitignore b/.gitignore index 8fc9c08799..553a7825fd 100755 --- a/.gitignore +++ b/.gitignore @@ -174,7 +174,9 @@ lsp/kotlin/src/main/resources/stdlib-index.json # Large asset files (bootstrap, SDK archives, databases, dependencies) assets/core.cgt assets/plugins/*.cgp +assets/plugins/*.CGP assets/templates/*.cgt +assets/templates/*.CGT assets/bootstrap-*.zip assets/android-sdk-*.zip assets/release/**/data/**/*.zip.br diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 40504e120f..051408c215 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -725,7 +725,9 @@ fun isBundledAddon( !element.isDirectory && element.relativePath.segments.size == 1 && !element.name.startsWith(".") && - element.name.endsWith(".$extension", ignoreCase = true) + element.name.endsWith(".$extension", ignoreCase = true) && + // core.cgt has its own asset entry; same rule as BundledAddons.isAddonFile. + !element.name.equals("core.cgt", ignoreCase = true) androidComponents.onVariants { variant -> val variantName = variant.name.replaceFirstChar(Char::uppercaseChar) @@ -1093,7 +1095,12 @@ fun createAssetsZip(arch: String) { arrayOf("plugins" to "cgp", "templates" to "cgt").forEach { (dirName, extension) -> sourceDir .resolve(dirName) - .listFiles { file -> file.isFile && !file.name.startsWith(".") && file.extension.equals(extension, ignoreCase = true) } + .listFiles { file -> + file.isFile && + !file.name.startsWith(".") && + file.extension.equals(extension, ignoreCase = true) && + !file.name.equals("core.cgt", ignoreCase = true) + } .orEmpty() .sortedBy { it.name } .forEach { file -> diff --git a/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt index 1d10d22ecc..7ccbc6204e 100755 --- a/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt @@ -80,6 +80,7 @@ import com.itsaky.androidide.utils.UrlManager import com.itsaky.androidide.utils.applyBottomWindowInsetsPadding import com.itsaky.androidide.utils.findValidProjects import com.itsaky.androidide.utils.flashError +import com.itsaky.androidide.utils.flashErrorAwaitShown import com.itsaky.androidide.utils.flashInfo import com.itsaky.androidide.utils.hasVisibleDialog import com.itsaky.androidide.utils.recordProjectOpenedBookkeeping @@ -110,6 +111,7 @@ class MainActivity : EdgeToEdgeIDEActivity() { private val analyticsManager: IAnalyticsManager by inject() private val recentProjectRepository: RecentProjectRepository by inject() private var feedbackButtonManager: FeedbackButtonManager? = null + private var reportingBundledFailures = false // Where the current touch on the toolbar began; null outside a touch (e.g. a TalkBack // long-press), which counts as the app name. @@ -341,23 +343,31 @@ class MainActivity : EdgeToEdgeIDEActivity() { } /** - * Tells the user once which plugins bundled with the build did not start. Marking them reported - * is what claims them, so a quick pause and resume cannot show the bar twice; the cost is that a - * screen destroyed between the claim and the bar loses the message. + * Tells the user once which plugins bundled with the build did not start. The failures are + * marked reported only after the bar is shown, so a screen destroyed first reports them next + * time; [reportingBundledFailures] keeps a resume during the report from starting a second one. */ private fun reportBundledPluginFailures() { + if (reportingBundledFailures) return + reportingBundledFailures = true lifecycleScope.launch { - val failures = - withContext(Dispatchers.IO) { - runCatching { BundledAddonsRecord.inFilesDir(filesDir).markReported() }.getOrDefault(emptyList()) - } - if (failures.isEmpty()) return@launch - flashError( - getString( - string.msg_bundled_plugins_failed, - failures.joinToString("\n") { "${it.pluginId}: ${it.message}" }, - ), - ) + try { + val record = BundledAddonsRecord.inFilesDir(filesDir) + val failures = + withContext(Dispatchers.IO) { + runCatching { record.unreportedFailures() }.getOrDefault(emptyList()) + } + if (failures.isEmpty()) return@launch + flashErrorAwaitShown( + getString( + string.msg_bundled_plugins_failed, + failures.joinToString("\n") { "${it.pluginId}: ${it.message}" }, + ), + ) + withContext(Dispatchers.IO) { runCatching { record.markReported() } } + } finally { + reportingBundledFailures = false + } } } diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt index cb263c33bf..630421b3f6 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt @@ -68,8 +68,13 @@ class BundledAddonInstaller( null } ?: throw RejectedPluginException("it has no readable manifest") checkPluginId(id).onFailure { throw RejectedPluginException(it.message ?: "invalid plugin ID") } + val name = "${PluginBuildFiles.fileStem(id, copy)}.$PLUGIN_ARCHIVE_EXTENSION" + // 255 bytes is the longest file name the file system takes. + if (name.toByteArray(Charsets.UTF_8).size > MAX_FILE_NAME_BYTES) { + throw RejectedPluginException("its plugin ID is too long") + } pluginId = id - "${PluginBuildFiles.fileStem(id, copy)}.$PLUGIN_ARCHIVE_EXTENSION" + name }, ) } catch (e: RejectedPluginException) { @@ -79,6 +84,10 @@ class BundledAddonInstaller( return InstalledAddon(BundledAddonKind.PLUGIN, file, pluginId) } + private companion object { + const val MAX_FILE_NAME_BYTES = 255 + } + private class RejectedPluginException( message: String, ) : IOException(message) diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt index 997cd12faf..619f2ae14e 100644 --- a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt @@ -137,4 +137,14 @@ class BundledAddonInstallerTest { assertThat(result.failure).contains("../escape") assertThat(pluginsDir.list()!!.toList()).isEmpty() } + + @Test + fun `a plugin whose ID is too long for a file name is reported, not thrown, and leaves no file`() { + val result = + installer(readPluginId = { "a".repeat(300) }).install(BundledAddonKind.PLUGIN, "a.cgp", bytes("plugin")) + + assertThat(result.file).isNull() + assertThat(result.failure).contains("too long") + assertThat(pluginsDir.list()!!.toList()).isEmpty() + } } diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt index e0b3ccf100..07599e736e 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt @@ -419,14 +419,19 @@ class PluginManager private constructor( // After loading all plugins, verify documentation for already loaded plugins verifyDocumentationForLoadedPlugins() - val pluginFiles = + val allFiles = pluginsDir.listFiles { file -> file.isFile && file.name.endsWith(".$PLUGIN_ARCHIVE_EXTENSION", ignoreCase = true) } ?: return@withContext - logger.info("Found ${pluginFiles.size} plugin files") + // Loading a file again would replace its entry without deactivating the old instance. + val loadedPaths = loadedPlugins.values.map { it.apkPath }.toSet() + val pluginFiles = allFiles.filter { it.absolutePath !in loadedPaths } - loadFailures.clear() + logger.info("Found ${allFiles.size} plugin files, ${pluginFiles.size} not loaded yet") + + // Keep what a loaded plugin failed at (activation), which a skipped file cannot report again. + loadFailures.keys.removeAll { it !in loadedPlugins } // Load plugins in parallel val loadJobs = @@ -754,6 +759,7 @@ class PluginManager private constructor( notifyLanguageContributionsChanged(plugin) }.onFailure { e -> logger.error("Failed to activate plugin: ${manifest.id}", e) + loadFailures[manifest.id] = e.message ?: e.toString() loadedPlugin.isEnabled = false savePluginState(manifest.id, false) } From 72d01e8476612c30c04bd7beea1ef53ae5bad543 Mon Sep 17 00:00:00 2001 From: ADFA Date: Sat, 21 Nov 2026 18:28:27 +0000 Subject: [PATCH 09/22] style: spotless reformat, no functional change --- app/build.gradle.kts | 3 +-- flox/base/.flox/env/manifest.lock | 7 ++++--- flox/base/.flox/env/manifest.toml | 3 ++- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 051408c215..d6da53f67c 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -1100,8 +1100,7 @@ fun createAssetsZip(arch: String) { !file.name.startsWith(".") && file.extension.equals(extension, ignoreCase = true) && !file.name.equals("core.cgt", ignoreCase = true) - } - .orEmpty() + }.orEmpty() .sortedBy { it.name } .forEach { file -> project.logger.lifecycle("Zipping bundled add-on $dirName/${file.name} from ${file.absolutePath}") diff --git a/flox/base/.flox/env/manifest.lock b/flox/base/.flox/env/manifest.lock index c95da03f9f..f606a0bbcf 100644 --- a/flox/base/.flox/env/manifest.lock +++ b/flox/base/.flox/env/manifest.lock @@ -1,13 +1,14 @@ { "lockfile-version": 1, "manifest": { - "version": 1, + "schema-version": "1.11.0", "install": { "android-studio-tools": { "pkg-path": "android-studio-tools" }, "awscli2": { - "pkg-path": "awscli2" + "pkg-path": "awscli2", + "outputs": "all" }, "gh": { "pkg-path": "gh" @@ -551,4 +552,4 @@ "priority": 5 } ] -} \ No newline at end of file +} diff --git a/flox/base/.flox/env/manifest.toml b/flox/base/.flox/env/manifest.toml index 84f81eee24..228f5b0541 100644 --- a/flox/base/.flox/env/manifest.toml +++ b/flox/base/.flox/env/manifest.toml @@ -6,7 +6,7 @@ ## ## ------------------------------------------------------------------- # Flox manifest version managed by Flox CLI -version = 1 +schema-version = "1.11.0" ## Install Packages -------------------------------------------------- @@ -19,6 +19,7 @@ jdk17.pkg-path = "jdk17" android-studio-tools.pkg-path = "android-studio-tools" gh.pkg-path = "gh" awscli2.pkg-path = "awscli2" +awscli2.outputs = "all" # gum.pkg-path = "gum" # gum.version = "^0.14.5" From 310ddfa7b576f933cbe6c671eed0a271f618129d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 18:28:50 +0000 Subject: [PATCH 10/22] Revert flox manifest changes swept in by the Spotless apply workflow The workflow commits with `git commit -am`, which picked up the flox base environment files that `flox activate` upgraded on the runner (manifest schema version, awscli2 outputs). They are unrelated to this branch; restore them to their stage versions. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- flox/base/.flox/env/manifest.lock | 7 +++---- flox/base/.flox/env/manifest.toml | 3 +-- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/flox/base/.flox/env/manifest.lock b/flox/base/.flox/env/manifest.lock index f606a0bbcf..c95da03f9f 100644 --- a/flox/base/.flox/env/manifest.lock +++ b/flox/base/.flox/env/manifest.lock @@ -1,14 +1,13 @@ { "lockfile-version": 1, "manifest": { - "schema-version": "1.11.0", + "version": 1, "install": { "android-studio-tools": { "pkg-path": "android-studio-tools" }, "awscli2": { - "pkg-path": "awscli2", - "outputs": "all" + "pkg-path": "awscli2" }, "gh": { "pkg-path": "gh" @@ -552,4 +551,4 @@ "priority": 5 } ] -} +} \ No newline at end of file diff --git a/flox/base/.flox/env/manifest.toml b/flox/base/.flox/env/manifest.toml index 228f5b0541..84f81eee24 100644 --- a/flox/base/.flox/env/manifest.toml +++ b/flox/base/.flox/env/manifest.toml @@ -6,7 +6,7 @@ ## ## ------------------------------------------------------------------- # Flox manifest version managed by Flox CLI -schema-version = "1.11.0" +version = 1 ## Install Packages -------------------------------------------------- @@ -19,7 +19,6 @@ jdk17.pkg-path = "jdk17" android-studio-tools.pkg-path = "android-studio-tools" gh.pkg-path = "gh" awscli2.pkg-path = "awscli2" -awscli2.outputs = "all" # gum.pkg-path = "gum" # gum.version = "^0.14.5" From ebb53294a25ec736294642375bdc6a7406f25f8d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 18:31:27 +0000 Subject: [PATCH 11/22] ADFA-7238: Report bundled failures only once shown; clear recovered activation errors - Activity.flashErrorAwaitShown / flashSuccessAwaitShown now return whether the bar finished appearing. MainActivity marks bundled-plugin failures reported only then, so a screen that goes away first reports them on a later resume. A bar slower than the 3 s timeout may be shown twice; a lost report is the worse failure. - PluginManager clears a plugin's load error after a later successful activation. Not compiled or tested in this environment (no Android SDK). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- .../androidide/activities/MainActivity.kt | 20 ++++++++++--------- .../androidide/utils/FlashbarActivityUtils.kt | 7 ++++--- .../plugins/manager/core/PluginManager.kt | 1 + 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt index 7ccbc6204e..4a01e38e31 100755 --- a/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt @@ -344,8 +344,9 @@ class MainActivity : EdgeToEdgeIDEActivity() { /** * Tells the user once which plugins bundled with the build did not start. The failures are - * marked reported only after the bar is shown, so a screen destroyed first reports them next - * time; [reportingBundledFailures] keeps a resume during the report from starting a second one. + * marked reported only once the bar has finished appearing, so a screen that goes away first + * reports them next time; [reportingBundledFailures] keeps a resume during the report from + * starting a second one. */ private fun reportBundledPluginFailures() { if (reportingBundledFailures) return @@ -358,13 +359,14 @@ class MainActivity : EdgeToEdgeIDEActivity() { runCatching { record.unreportedFailures() }.getOrDefault(emptyList()) } if (failures.isEmpty()) return@launch - flashErrorAwaitShown( - getString( - string.msg_bundled_plugins_failed, - failures.joinToString("\n") { "${it.pluginId}: ${it.message}" }, - ), - ) - withContext(Dispatchers.IO) { runCatching { record.markReported() } } + val shown = + this@MainActivity.flashErrorAwaitShown( + getString( + string.msg_bundled_plugins_failed, + failures.joinToString("\n") { "${it.pluginId}: ${it.message}" }, + ), + ) + if (shown) withContext(Dispatchers.IO) { runCatching { record.markReported() } } } finally { reportingBundledFailures = false } diff --git a/common/src/main/java/com/itsaky/androidide/utils/FlashbarActivityUtils.kt b/common/src/main/java/com/itsaky/androidide/utils/FlashbarActivityUtils.kt index 82e4f3e6d0..672bef9f2e 100644 --- a/common/src/main/java/com/itsaky/androidide/utils/FlashbarActivityUtils.kt +++ b/common/src/main/java/com/itsaky/androidide/utils/FlashbarActivityUtils.kt @@ -166,14 +166,15 @@ fun Activity.flashInfoLong(msg: String?) = showFlashBar(msg, IconType.INFO, dura * [FLASH_SHOWN_TIMEOUT_MS] elapses) instead of firing-and-forgetting - for callers (e.g. a * one-shot screen about to finish()) that need the message to be visible before proceeding, * rather than guessing a fixed delay that may or may not outlast the real animation. + * Returns whether the bar finished appearing: false for a `null` [msg] or on timeout. */ private suspend fun Activity.showFlashBarAwaitShown( msg: Any?, iconType: IconType, gravity: Flashbar.Gravity = TOP, duration: Long = Flashbar.DURATION_SHORT, -) { - val builder = configureFlashbar(msg, iconType, gravity, duration) ?: return +): Boolean { + val builder = configureFlashbar(msg, iconType, gravity, duration) ?: return false val shown = CompletableDeferred() builder.barShowListener( @@ -192,7 +193,7 @@ private suspend fun Activity.showFlashBarAwaitShown( ) runOnUiThread { builder.build().show() } - withTimeoutOrNull(FLASH_SHOWN_TIMEOUT_MS) { shown.await() } + return withTimeoutOrNull(FLASH_SHOWN_TIMEOUT_MS) { shown.await() } != null } suspend fun Activity.flashSuccessAwaitShown(msg: String?) = showFlashBarAwaitShown(msg, IconType.SUCCESS) diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt index 07599e736e..96b2fb32dc 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt @@ -757,6 +757,7 @@ class PluginManager private constructor( buildActionManager.registerManifestActions(manifest.id, manifest.name, manifest) lifecycleDispatcher.notifyActivated(manifest.id) notifyLanguageContributionsChanged(plugin) + loadFailures.remove(manifest.id) }.onFailure { e -> logger.error("Failed to activate plugin: ${manifest.id}", e) loadFailures[manifest.id] = e.message ?: e.toString() From 86573c02bdcaca717406c999ebabfde0b2c93392 Mon Sep 17 00:00:00 2001 From: ADFA Date: Sat, 21 Nov 2026 18:33:57 +0000 Subject: [PATCH 12/22] style: spotless reformat, no functional change --- flox/base/.flox/env/manifest.lock | 7 ++++--- flox/base/.flox/env/manifest.toml | 3 ++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/flox/base/.flox/env/manifest.lock b/flox/base/.flox/env/manifest.lock index c95da03f9f..f606a0bbcf 100644 --- a/flox/base/.flox/env/manifest.lock +++ b/flox/base/.flox/env/manifest.lock @@ -1,13 +1,14 @@ { "lockfile-version": 1, "manifest": { - "version": 1, + "schema-version": "1.11.0", "install": { "android-studio-tools": { "pkg-path": "android-studio-tools" }, "awscli2": { - "pkg-path": "awscli2" + "pkg-path": "awscli2", + "outputs": "all" }, "gh": { "pkg-path": "gh" @@ -551,4 +552,4 @@ "priority": 5 } ] -} \ No newline at end of file +} diff --git a/flox/base/.flox/env/manifest.toml b/flox/base/.flox/env/manifest.toml index 84f81eee24..228f5b0541 100644 --- a/flox/base/.flox/env/manifest.toml +++ b/flox/base/.flox/env/manifest.toml @@ -6,7 +6,7 @@ ## ## ------------------------------------------------------------------- # Flox manifest version managed by Flox CLI -version = 1 +schema-version = "1.11.0" ## Install Packages -------------------------------------------------- @@ -19,6 +19,7 @@ jdk17.pkg-path = "jdk17" android-studio-tools.pkg-path = "android-studio-tools" gh.pkg-path = "gh" awscli2.pkg-path = "awscli2" +awscli2.outputs = "all" # gum.pkg-path = "gum" # gum.version = "^0.14.5" From edcd3a96b43d371a010ce82c86a28aee7ff0a3b9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 18:34:34 +0000 Subject: [PATCH 13/22] Revert flox manifest changes swept in by the Spotless apply workflow The workflow commits with `git commit -am`, which picked up the flox base environment files that `flox activate` upgraded on the runner (manifest schema version, awscli2 outputs). They are unrelated to this branch; restore them to their stage versions. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- flox/base/.flox/env/manifest.lock | 7 +++---- flox/base/.flox/env/manifest.toml | 3 +-- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/flox/base/.flox/env/manifest.lock b/flox/base/.flox/env/manifest.lock index f606a0bbcf..c95da03f9f 100644 --- a/flox/base/.flox/env/manifest.lock +++ b/flox/base/.flox/env/manifest.lock @@ -1,14 +1,13 @@ { "lockfile-version": 1, "manifest": { - "schema-version": "1.11.0", + "version": 1, "install": { "android-studio-tools": { "pkg-path": "android-studio-tools" }, "awscli2": { - "pkg-path": "awscli2", - "outputs": "all" + "pkg-path": "awscli2" }, "gh": { "pkg-path": "gh" @@ -552,4 +551,4 @@ "priority": 5 } ] -} +} \ No newline at end of file diff --git a/flox/base/.flox/env/manifest.toml b/flox/base/.flox/env/manifest.toml index 228f5b0541..84f81eee24 100644 --- a/flox/base/.flox/env/manifest.toml +++ b/flox/base/.flox/env/manifest.toml @@ -6,7 +6,7 @@ ## ## ------------------------------------------------------------------- # Flox manifest version managed by Flox CLI -schema-version = "1.11.0" +version = 1 ## Install Packages -------------------------------------------------- @@ -19,7 +19,6 @@ jdk17.pkg-path = "jdk17" android-studio-tools.pkg-path = "android-studio-tools" gh.pkg-path = "gh" awscli2.pkg-path = "awscli2" -awscli2.outputs = "all" # gum.pkg-path = "gum" # gum.version = "^0.14.5" From 3267017da1493fb6aee7c417933a2f5b9346fd68 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 18:42:46 +0000 Subject: [PATCH 14/22] ADFA-7238: Fix load-failure pruning to check keys, not values `it !in loadedPlugins` on a ConcurrentHashMap calls contains(), which is containsValue(), so every load failure was pruned; the Kotlin compiler rejects it (KT-18053) and the Build Universal APK job failed. Use containsKey. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- .../com/itsaky/androidide/plugins/manager/core/PluginManager.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt index 96b2fb32dc..206a1d5e47 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt @@ -431,7 +431,7 @@ class PluginManager private constructor( logger.info("Found ${allFiles.size} plugin files, ${pluginFiles.size} not loaded yet") // Keep what a loaded plugin failed at (activation), which a skipped file cannot report again. - loadFailures.keys.removeAll { it !in loadedPlugins } + loadFailures.keys.removeAll { !loadedPlugins.containsKey(it) } // Load plugins in parallel val loadJobs = From 7671ff98c893a1b31753907d84852e5334272d1e Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 21:15:02 -0800 Subject: [PATCH 15/22] ADFA-7238: Load brotli for real before the bundle test mocks Brotli4jLoader AssetsInstallationHelperBundleTest mocked Brotli4jLoader statically without first loading the native library. When it was the first test in the JVM to touch that class, the loader's static initializer ran while being recorded by MockK, cached "unavailable", and 9 later brotli tests failed (BrotliDictionaryDecodeTest, CompressedTemplateTest x6, BrotliContentSourceTest x2). Add the guard AssetsInstallationHelperTest already has. Verified with a temporary JUnit suite that ran this test before the three brotli classes: 9 of 16 fail without the guard, 28 of 28 pass with it. The full :app:testV8DebugUnitTest passes with it, 1823 of 1823. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- .../assets/AssetsInstallationHelperBundleTest.kt | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/app/src/test/java/com/itsaky/androidide/assets/AssetsInstallationHelperBundleTest.kt b/app/src/test/java/com/itsaky/androidide/assets/AssetsInstallationHelperBundleTest.kt index 46d7a5b4f4..d203a4780b 100644 --- a/app/src/test/java/com/itsaky/androidide/assets/AssetsInstallationHelperBundleTest.kt +++ b/app/src/test/java/com/itsaky/androidide/assets/AssetsInstallationHelperBundleTest.kt @@ -43,6 +43,15 @@ class AssetsInstallationHelperBundleTest { @Before fun setUp() { + // Load the brotli native for real before mocking Brotli4jLoader, as AssetsInstallationHelperTest + // does: a JVM whose first sight of that class is the mocked one caches "unavailable", and every + // later brotli test fails. + try { + Brotli4jLoader.ensureAvailability() + } catch (e: UnsatisfiedLinkError) { + println("brotli native unavailable on this host, continuing: ${e.message}") + } + filesDir = tempFolder.newFolder("files") every { ctx.filesDir } returns filesDir From 34d016ea687eda4916cadeb921bfb313e381f3c6 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 08:49:09 -0800 Subject: [PATCH 16/22] ADFA-7238: Drop the staging task's output folder, which AGP replaces addGeneratedSourceDirectory sets StageBundledAddons' outputDirectory itself, to build/generated/assets/, so the intermediates/bundled-addons folder set at registration was never used and sent readers to an empty folder. A comment now says where the output goes. Checked by running stageV8ReleaseBundledAddons with a plugin, a template and a core.cgt decoy: both add-ons land in build/generated/assets/stageV8ReleaseBundledAddons, the decoy is skipped, and no intermediates/bundled-addons folder appears. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- app/build.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index d6da53f67c..d5c9382d8b 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -739,8 +739,8 @@ androidComponents.onVariants { variant -> // Top-level files only, extension in any case, as the debug zip takes them. pluginFiles.from(fileTree(rootProject.file("assets/plugins")) { include { isBundledAddon(it, "cgp") } }) templateFiles.from(fileTree(rootProject.file("assets/templates")) { include { isBundledAddon(it, "cgt") } }) - outputDirectory.set(layout.buildDirectory.dir("intermediates/bundled-addons/${variant.name}")) } + // AGP sets the task's outputDirectory: build/generated/assets/. variant.sources.assets?.addGeneratedSourceDirectory( stageBundledAddons, StageBundledAddons::outputDirectory, From eb8f522170c0e1f63acbdf9b953fbe5d90263bca Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 13:30:54 -0800 Subject: [PATCH 17/22] ADFA-7238: Index the bundle, so listing it opens no add-on The bundle was listed by asking each add-on file for its size, and fingerprinted by names and sizes. A release APK stores .cgp/.cgt compressed, so each size meant inflating the whole file; ADFA-7239 lists the bundle at every start, which would inflate every bundled add-on before plugins load. And two builds of a plugin can have the same size: two Random XKCD builds a minute apart are both 5,042,949 bytes, so a bundle change like that would go unnoticed. The build now writes bundled-addons.tsv beside plugins/ and templates/ (StageBundledAddons for release, createAssetsZip for debug): one line per add-on, entry name, size and SHA-256; empty in a thin build. - BundledAddons.list reads the index; a bundle without a valid one (an older debug zip) is still listed from its folders. - The fingerprint includes each entry's SHA-256, so a same-size rebuild changes it. Without an index it is unchanged. - BundledAddonInstaller checks each copy against its SHA-256 and rejects a mismatch, plugin or template, reported like a plugin with no readable manifest. The failure message now names plugins or templates. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- ARCHITECTURE.md | 2 +- app/build.gradle.kts | 43 ++++++- .../assets/AssetsInstallationHelper.kt | 2 +- .../androidide/assets/BaseAssetsInstaller.kt | 10 +- .../androidide/assets/addons/BundleSources.kt | 13 +- .../assets/addons/BundledAddonInstaller.kt | 52 ++++++-- .../androidide/assets/addons/BundledAddons.kt | 53 +++++++- .../addons/BundledAddonInstallerTest.kt | 54 ++++++++ .../assets/addons/BundledAddonsTest.kt | 121 +++++++++++++++++- resources/src/main/res/values/strings.xml | 2 +- 10 files changed, 322 insertions(+), 30 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index c7d1269d4d..3c8b5273c3 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -107,7 +107,7 @@ These structural facts shape every module. Day-to-day build *commands* live in ` - **ABI product flavors.** Every Android module *except* `:plugin-api` and `:subprojects:sqlite-js` gets two flavors on the `abi` dimension — `v7` (`armeabi-v7a`) and `v8` (`arm64-v8a`) — defined centrally. There is no flavorless variant; tasks are `assembleV8Debug`, `assembleV7Release`, etc. - **SDK levels** (`build-logic/.../build/config/BuildConfig.kt`): `COMPILE_SDK=36`, `MIN_SDK=28`, `TARGET_SDK=28`. **`TARGET_SDK` is deliberately pinned at 28:** higher targets enforce W^X (write-xor-execute), which blocks executing code from app-writable files. That is fatal for an on-device IDE that compiles and runs code (Gradle, `javac`, Termux binaries), so it is a hard requirement, not tech debt. `MIN_SDK_FOR_APPS_BUILT_WITH_COGO=16` is the floor for the apps a *user* builds with CoGo — distinct from CoGo's own `MIN_SDK`. - **Native asset bundling.** The on-device LLM (`llama-impl`) ships as a per-flavor native AAR, wired through the root `build.gradle.kts` (`bundleLlamaV8Assets` / `assembleV8Assets`, …); prebuilt per-flavor assets live under `assets/release/v7/` and `assets/release/v8/`. -- **Bundled add-ons** (ADFA-7238). A build is *fat* when `assets/plugins/*.cgp` and `assets/templates/*.cgt` exist in the repo root: release builds put them in the APK assets as `plugins/` and `templates/` (`StageBundledAddons` in `app/build.gradle.kts`), and `createAssetsZip()` adds the same entries to the debug `assets-.zip`. A missing or empty folder is the thin build, whose output is unchanged. First-run setup (`AssetsInstallationHelper`) lists the bundle (`assets/addons/BundledAddons`), installs each file in the same parallel phase through `BundledAddonInstaller` (scratch file, then rename; a plugin lands in `filesDir/plugins` as `-.cgp`, a template in `Environment.TEMPLATES_DIR`), and writes `filesDir/bundled_addons.properties` last (`BundledAddonsRecord`: bundle fingerprint, bundled plugin IDs and template files, plugin load failures not yet reported to the user). `InstallationViewModel` then reloads the plugins once, and `MainActivity` shows one error bar for the recorded failures. +- **Bundled add-ons** (ADFA-7238). A build is *fat* when `assets/plugins/*.cgp` and `assets/templates/*.cgt` exist in the repo root: release builds put them in the APK assets as `plugins/` and `templates/` (`StageBundledAddons` in `app/build.gradle.kts`), and `createAssetsZip()` adds the same entries to the debug `assets-.zip`. Both also write the bundle index `bundled-addons.tsv` (one line per add-on: entry name, size, SHA-256; empty in a thin build), so the app lists and fingerprints the bundle without opening an add-on, which a release APK stores compressed, and a rebuilt add-on of the same size changes the fingerprint. A bundle without a valid index, such as an older debug zip, is listed from its folders by name and size. A missing or empty folder is the thin build. First-run setup (`AssetsInstallationHelper`) lists the bundle (`assets/addons/BundledAddons`), installs each file in the same parallel phase through `BundledAddonInstaller` (scratch file, then rename; a plugin lands in `filesDir/plugins` as `-.cgp`, a template in `Environment.TEMPLATES_DIR`; a copy whose SHA-256 differs from the index is rejected and reported like a plugin with no readable manifest), and writes `filesDir/bundled_addons.properties` last (`BundledAddonsRecord`: bundle fingerprint, bundled plugin IDs and template files, plugin load failures not yet reported to the user). `InstallationViewModel` then reloads the plugins once, and `MainActivity` shows one error bar for the recorded failures. - **sqlite-js for apps built with CoGo** (ADFA-7082). `subprojects:sqlite-js` builds the AAR that the JavaScript-in-SQLite project template depends on: the sqlite-js release vendored (see its README), for arm64-v8a and armeabi-v7a, minSdk 26, without core-library desugaring. Nothing in CoGo depends on it. Its default entry point runs no code stored in a database; loading stored functions is a separate entry point, only for databases the app made, since loading runs their code. `test-sqlite-js.yml` runs its host tests on pull requests. The manual `release-sqlite-js.yml` publishes it to the moving `sqlite-js-latest` release, from which dev-assets fetches it into the template, as it fetches `plugin-api-latest` for the plugin template. - **Native lib compression** (ADFA-2306, ADFA-4729). The app manifest hard-codes `android:extractNativeLibs="true"` (required: the installer must materialize libs in `nativeLibraryDir`, e.g. `libshizuku.so` is an executable the adb shell runs from there). That attribute overrides the `jniLibs.useLegacyPackaging` DSL, so AGP packages `lib//*.so` deflate-compressed in **every** APK — ~5.9 MB smaller (`libtree-sitter-kotlin.so` alone is 4.18 MB → 339 kB). The trap is the `recompressApk` post-step (release always, debug in CI only): its no-compress lists in `app/build.gradle.kts` must NOT contain `"so"`, or it silently re-stores the libs and undoes the saving — which is what ADFA-2306 fixed for release and ADFA-4729 for CI debug. Locally built debug APKs (including the e2e farm's) never run that step and were always fine. - **Quick Build shares the Gradle distribution's toolchain** (ADFA-4931). `:app`'s `quickBuildDaemonZip` leaves the Kotlin compiler and eight other jars out of the daemon zip, because the on-device Gradle distribution already carries them; `QuickBuildArtifactStager` links them in at provision time. That makes the daemon's Kotlin version the distribution's, so `:quickbuild:daemon` takes its Kotlin artifacts at `org.adfa.constants.GRADLE_DISTRIBUTION_KOTLIN_VERSION`, and `:app:quickBuildDistJarCheck` fails the build when the distribution it packages lacks a linked jar. See [ADR 0016](docs/adr/0016-quick-build-compiles-outside-gradle.md). diff --git a/app/build.gradle.kts b/app/build.gradle.kts index d5c9382d8b..8a65c564e7 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -26,6 +26,8 @@ import java.net.URI import java.net.URL import java.nio.file.Files import java.nio.file.StandardCopyOption +import java.security.DigestInputStream +import java.security.DigestOutputStream import java.security.MessageDigest import java.util.Properties import java.util.zip.CRC32 @@ -695,6 +697,9 @@ val quickBuildDaemonZip = // assets/templates, put in the APK assets as plugins/ and templates/. A folder that is // missing or empty bundles nothing, and the build is the thin one. Plugin files keep their names: // the installer names each after the plugin ID in its manifest, which Gradle does not read. +// Beside them goes the bundle index, bundled-addons.tsv (BundledAddons.INDEX_FILE): one line per +// add-on, "/\t\t", empty in a thin build. The app lists and fingerprints +// the bundle from it, so it opens no add-on at start-up and notices a rebuild of the same size. abstract class StageBundledAddons : DefaultTask() { @get:InputFiles @get:PathSensitive(PathSensitivity.NAME_ONLY) @@ -712,8 +717,31 @@ abstract class StageBundledAddons : DefaultTask() { val out = outputDirectory.get().asFile out.deleteRecursively() out.mkdirs() - pluginFiles.files.filter { !it.name.startsWith(".") }.forEach { it.copyTo(File(out, "plugins/${it.name}")) } - templateFiles.files.filter { !it.name.startsWith(".") }.forEach { it.copyTo(File(out, "templates/${it.name}")) } + val index = StringBuilder() + pluginFiles.files + .filter { !it.name.startsWith(".") } + .sortedBy { it.name } + .forEach { index.append(stage(it, "plugins", out)) } + templateFiles.files + .filter { !it.name.startsWith(".") } + .sortedBy { it.name } + .forEach { index.append(stage(it, "templates", out)) } + File(out, "bundled-addons.tsv").writeText(index.toString()) + } + + /** Copies [file] into [dir] of [out], hashing it on the way, and returns its index line. */ + private fun stage( + file: File, + dir: String, + out: File, + ): String { + val dest = File(out, "$dir/${file.name}") + dest.parentFile.mkdirs() + val digest = MessageDigest.getInstance("SHA-256") + file.inputStream().use { input -> + DigestOutputStream(dest.outputStream(), digest).use { output -> input.copyTo(output) } + } + return "$dir/${file.name}\t${dest.length()}\t${digest.digest().joinToString("") { "%02x".format(it) }}\n" } } @@ -1091,7 +1119,9 @@ fun createAssetsZip(arch: String) { zipOut.closeEntry() } - // Add-ons of a fat build, as plugins/ and templates/; none in a thin one. + // Add-ons of a fat build, as plugins/ and templates/; none in a thin one. Then the + // bundle index, as StageBundledAddons writes it for a release build. + val index = StringBuilder() arrayOf("plugins" to "cgp", "templates" to "cgt").forEach { (dirName, extension) -> sourceDir .resolve(dirName) @@ -1104,11 +1134,16 @@ fun createAssetsZip(arch: String) { .sortedBy { it.name } .forEach { file -> project.logger.lifecycle("Zipping bundled add-on $dirName/${file.name} from ${file.absolutePath}") + val digest = MessageDigest.getInstance("SHA-256") zipOut.putNextEntry(ZipEntry("$dirName/${file.name}")) - file.inputStream().use { input -> input.copyTo(zipOut) } + file.inputStream().use { input -> DigestInputStream(input, digest).copyTo(zipOut) } zipOut.closeEntry() + index.append("$dirName/${file.name}\t${file.length()}\t${digest.digest().joinToString("") { "%02x".format(it) }}\n") } } + zipOut.putNextEntry(ZipEntry("bundled-addons.tsv")) + zipOut.write(index.toString().toByteArray(Charsets.UTF_8)) + zipOut.closeEntry() } project.logger.lifecycle("Created ${zipFile.name} at ${zipFile.parentFile.absolutePath}") } diff --git a/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt b/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt index e6d07cc638..ffb0ac1d03 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt @@ -262,7 +262,7 @@ object AssetsInstallationHelper { .filter { it.kind == BundledAddonKind.TEMPLATE } .mapNotNull { it.file?.name } .sorted(), - // Plugins rejected while copying; the main screen reports them with load failures. + // Add-ons rejected while copying; the main screen reports them with load failures. failures = installed .mapNotNull { addon -> addon.failure?.let { BundledPluginFailure(addon.sourceName ?: "?", it) } } diff --git a/app/src/main/java/com/itsaky/androidide/assets/BaseAssetsInstaller.kt b/app/src/main/java/com/itsaky/androidide/assets/BaseAssetsInstaller.kt index 8393c8e6aa..55f8bdaf56 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/BaseAssetsInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/BaseAssetsInstaller.kt @@ -22,12 +22,18 @@ abstract class BaseAssetsInstaller : AssetsInstaller { private val logger = LoggerFactory.getLogger(BaseAssetsInstaller::class.java) private val installedByEntry = ConcurrentHashMap() + // Content hashes from the bundle index, by entry name, for the copies to check. + private val sha256ByEntry = ConcurrentHashMap() + /** Where this installer's bundled add-ons are read from. */ protected abstract fun bundleSource(context: Context): BundleSource override fun listBundledAddons(context: Context): List { installedByEntry.clear() - return BundledAddons.list(bundleSource(context)) + sha256ByEntry.clear() + return BundledAddons.list(bundleSource(context)).onEach { entry -> + entry.sha256?.let { sha256ByEntry[entry.entryName] = it } + } } override fun installedAddons(): List = installedByEntry.values.toList() @@ -47,7 +53,7 @@ abstract class BaseAssetsInstaller : AssetsInstaller { templatesDir = Environment.TEMPLATES_DIR, readPluginId = { PluginLoader(context, it).getPluginMetadata()?.id }, ) - installedByEntry[entryName] = installer.install(kind, fileName, input) + installedByEntry[entryName] = installer.install(kind, fileName, input, sha256ByEntry[entryName]) } override suspend fun postInstall( diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSources.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSources.kt index bbf904787d..12ef9c6d5e 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSources.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSources.kt @@ -19,7 +19,8 @@ class AssetManagerBundleSource( try { assets.openFd("$dir/$name").use { it.length } } catch (e: IOException) { - // openFd refuses an asset the APK stores compressed; count the bytes instead. + // openFd refuses an asset the APK stores compressed; count the bytes instead. Only a bundle + // without an index asks for sizes, and every release build writes one. assets.open("$dir/$name").use { input -> input.countBytes() } } @@ -27,6 +28,13 @@ class AssetManagerBundleSource( dir: String, name: String, ): InputStream = assets.open("$dir/$name") + + override fun index(): String? = + try { + assets.open(BundledAddons.INDEX_FILE).bufferedReader().use { it.readText() } + } catch (e: FileNotFoundException) { + null + } } /** The bundle of a debug build: `plugins/` and `templates/` entries of the split assets zip. */ @@ -52,6 +60,9 @@ class ZipBundleSource( name: String, ): InputStream = zip.getInputStream(entry(dir, name)) + override fun index(): String? = + zip.getEntry(BundledAddons.INDEX_FILE)?.let { entry -> zip.getInputStream(entry).bufferedReader().use { it.readText() } } + private fun entry( dir: String, name: String, diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt index 630421b3f6..77a69bc353 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt @@ -6,11 +6,14 @@ import org.adfa.constants.PLUGIN_ARCHIVE_EXTENSION import java.io.File import java.io.IOException import java.io.InputStream +import java.security.DigestInputStream +import java.security.MessageDigest /** * A bundled add-on after installation. [pluginId] is set for a plugin that reached its folder. A - * plugin whose manifest names no valid ID has no [file] and carries a [failure] instead, with the - * bundled file name in [sourceName]: it is reported to the user, and must not fail the setup. + * plugin whose manifest names no valid ID, or an add-on whose content differs from the bundle + * index, has no [file] and carries a [failure] instead, with the bundled file name in + * [sourceName]: it is reported to the user, and must not fail the setup. */ data class InstalledAddon( val kind: BundledAddonKind, @@ -34,25 +37,47 @@ class BundledAddonInstaller( private val templatesDir: File, private val readPluginId: (File) -> String?, ) { + /** + * Copies [input] into place. With [sha256] (hex, from the bundle index), a copy whose content + * differs is rejected like an unreadable plugin: reported, not thrown, and nothing replaced. + */ fun install( kind: BundledAddonKind, fileName: String, input: InputStream, - ): InstalledAddon = - when (kind) { + sha256: String? = null, + ): InstalledAddon { + val digest = sha256?.let { MessageDigest.getInstance("SHA-256") } + val source = digest?.let { DigestInputStream(input, it) } ?: input + val checkContent = { + if (digest != null && digest.digest().toHex() != sha256) { + throw RejectedAddonException("its content does not match the bundle index") + } + } + return when (kind) { BundledAddonKind.PLUGIN -> { - installPlugin(fileName, input) + installPlugin(fileName, source, checkContent) } BundledAddonKind.TEMPLATE -> { - val file = AtomicFiles.writeInto(templatesDir, { input.copyToFile(it) }, { fileName }) - InstalledAddon(kind, file, null) + try { + val file = + AtomicFiles.writeInto(templatesDir, { source.copyToFile(it) }, { + checkContent() + fileName + }) + InstalledAddon(kind, file, null) + } catch (e: RejectedAddonException) { + InstalledAddon(kind, null, null, failure = e.message, sourceName = fileName) + } } } + } private fun installPlugin( fileName: String, input: InputStream, + checkContent: () -> Unit, ): InstalledAddon { var pluginId: String? = null val file = @@ -61,23 +86,24 @@ class BundledAddonInstaller( pluginsDir, { input.copyToFile(it) }, { copy -> + checkContent() val id = try { readPluginId(copy) } catch (e: Exception) { null - } ?: throw RejectedPluginException("it has no readable manifest") - checkPluginId(id).onFailure { throw RejectedPluginException(it.message ?: "invalid plugin ID") } + } ?: throw RejectedAddonException("it has no readable manifest") + checkPluginId(id).onFailure { throw RejectedAddonException(it.message ?: "invalid plugin ID") } val name = "${PluginBuildFiles.fileStem(id, copy)}.$PLUGIN_ARCHIVE_EXTENSION" // 255 bytes is the longest file name the file system takes. if (name.toByteArray(Charsets.UTF_8).size > MAX_FILE_NAME_BYTES) { - throw RejectedPluginException("its plugin ID is too long") + throw RejectedAddonException("its plugin ID is too long") } pluginId = id name }, ) - } catch (e: RejectedPluginException) { + } catch (e: RejectedAddonException) { // writeInto has deleted the scratch copy. A write error (disk full) still propagates. return InstalledAddon(BundledAddonKind.PLUGIN, null, null, failure = e.message, sourceName = fileName) } @@ -88,10 +114,12 @@ class BundledAddonInstaller( const val MAX_FILE_NAME_BYTES = 255 } - private class RejectedPluginException( + private class RejectedAddonException( message: String, ) : IOException(message) + private fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it) } + private fun InputStream.copyToFile(dest: File) { dest.outputStream().use { out -> copyTo(out) } } diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt index c2071fccc6..60c0964b86 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt @@ -15,11 +15,15 @@ enum class BundledAddonKind( TEMPLATE("templates", TEMPLATE_ARCHIVE_EXTENSION), } -/** One bundled add-on file: [fileName] inside the [kind] folder, [size] bytes. */ +/** + * One bundled add-on file: [fileName] inside the [kind] folder, [size] bytes. [sha256] (hex) comes + * from the bundle index; it is null for a bundle without one, listed by name and size. + */ data class BundledEntry( val kind: BundledAddonKind, val fileName: String, val size: Long, + val sha256: String? = null, ) { /** The name the installers and the progress list know it by: `plugins/`. */ val entryName: String get() = "${kind.dir}/$fileName" @@ -39,9 +43,19 @@ interface BundleSource { dir: String, name: String, ): InputStream + + /** The text of the bundle index ([BundledAddons.INDEX_FILE]), or null when the bundle has none. */ + fun index(): String? = null } object BundledAddons { + /** + * The bundle index, written by the build beside `plugins/` and `templates/`: one line per add-on, + * `\t\t`. A thin build writes it empty. With it, listing the bundle + * opens no add-on, and the fingerprint notices a rebuilt add-on of the same size. + */ + const val INDEX_FILE = "bundled-addons.tsv" + /** True for an entry name that [BundledEntry.entryName] could have produced. */ fun isAddonEntry(entryName: String): Boolean = parse(entryName) != null @@ -54,9 +68,33 @@ object BundledAddons { /** * Every add-on file [source] holds, plugins first, each kind in name order. A thin build has - * none. Other files in the folders, and any path below them, are not add-ons. + * none. The bundle index is used when there is a valid one. Otherwise, as for a debug zip made + * before the index, the folders are listed and each file's size read: other files in the folders, + * and any path below them, are not add-ons. + */ + fun list(source: BundleSource): List = source.index()?.let(::parseIndex) ?: listFolders(source) + + /** + * The entries of an index, in [list]'s order, or null when any line is malformed, names no add-on + * file, or repeats an entry: such an index was not written by the build, so the folders decide. */ - fun list(source: BundleSource): List = + fun parseIndex(text: String): List? { + val entries = + text.lines().filter { it.isNotBlank() }.map { line -> + val fields = line.split('\t') + if (fields.size != 3) return null + val (kind, fileName) = parse(fields[0]) ?: return null + val size = fields[1].toLongOrNull()?.takeIf { it >= 0 } ?: return null + val sha256 = fields[2].takeIf { SHA256_HEX.matches(it) } ?: return null + BundledEntry(kind, fileName, size, sha256) + } + if (entries.distinctBy { it.entryName }.size != entries.size) return null + return entries.sortedWith(compareBy({ it.kind.ordinal }, { it.fileName })) + } + + private val SHA256_HEX = Regex("[0-9a-f]{64}") + + private fun listFolders(source: BundleSource): List = BundledAddonKind.values().flatMap { kind -> source .names(kind.dir) @@ -66,14 +104,15 @@ object BundledAddons { } /** - * Identifies a bundle by its entry names and sizes, in any order: sha-256, hex. Cheap enough to - * recompute at every start. A rebuilt add-on that keeps its name and size is not noticed. The - * empty bundle has a fingerprint too, so a thin build can be told from a missing record. + * Identifies a bundle by its entries, in any order: sha-256, hex. It reads no add-on, so it is + * cheap at every start. Entries from an index carry their content hash, so a rebuilt add-on of the + * same name and size is noticed; a bundle without an index is identified by names and sizes only. + * The empty bundle has a fingerprint too, so a thin build can be told from a missing record. */ fun fingerprint(entries: List): String { val digest = MessageDigest.getInstance("SHA-256") entries - .map { "${it.entryName}\t${it.size}\n" } + .map { entry -> listOfNotNull(entry.entryName, entry.size.toString(), entry.sha256).joinToString("\t", postfix = "\n") } .sorted() .forEach { digest.update(it.toByteArray(Charsets.UTF_8)) } return digest.digest().joinToString("") { "%02x".format(it) } diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt index 619f2ae14e..2426e6a711 100644 --- a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt @@ -11,6 +11,7 @@ import java.io.ByteArrayInputStream import java.io.File import java.io.IOException import java.io.InputStream +import java.security.MessageDigest class BundledAddonInstallerTest { @get:Rule @@ -33,6 +34,9 @@ class BundledAddonInstallerTest { private fun bytes(text: String): InputStream = ByteArrayInputStream(text.toByteArray()) + private fun sha256(text: String): String = + MessageDigest.getInstance("SHA-256").digest(text.toByteArray()).joinToString("") { "%02x".format(it) } + /** Delivers [first], then fails, like a copy cut short. */ private fun failingAfter(first: String): InputStream = object : InputStream() { @@ -86,6 +90,56 @@ class BundledAddonInstallerTest { assertThat(templatesDir.list()!!.toList()).containsExactly("starter.cgt") } + @Test + fun `a plugin whose content matches its index hash is installed`() { + val installed = installer().install(BundledAddonKind.PLUGIN, "a.cgp", bytes("plugin bytes"), sha256("plugin bytes")) + + assertThat(installed.failure).isNull() + assertThat(installed.file!!.readText()).isEqualTo("plugin bytes") + } + + @Test + fun `a plugin whose content differs from its index hash is reported, not thrown, and leaves no file`() { + var manifestRead = false + val installed = + installer(readPluginId = { + manifestRead = true + "com.example.plugin" + }).install(BundledAddonKind.PLUGIN, "a.cgp", bytes("tampered"), sha256("plugin bytes")) + + assertThat(installed.file).isNull() + assertThat(installed.pluginId).isNull() + assertThat(installed.sourceName).isEqualTo("a.cgp") + assertThat(installed.failure).contains("does not match the bundle index") + assertThat(manifestRead).isFalse() + assertThat(pluginsDir.list()!!.toList()).isEmpty() + } + + @Test + fun `a template whose content differs from its index hash is reported and keeps the old one`() { + templatesDir.mkdirs() + File(templatesDir, "starter.cgt").writeText("old") + + val installed = installer().install(BundledAddonKind.TEMPLATE, "starter.cgt", bytes("tampered"), sha256("new")) + + assertThat(installed.file).isNull() + assertThat(installed.sourceName).isEqualTo("starter.cgt") + assertThat(installed.failure).contains("does not match the bundle index") + assertThat(templatesDir.list()!!.toList()).containsExactly("starter.cgt") + assertThat(File(templatesDir, "starter.cgt").readText()).isEqualTo("old") + } + + @Test + fun `a template whose content matches its index hash replaces the old one`() { + templatesDir.mkdirs() + File(templatesDir, "starter.cgt").writeText("old") + + val installed = installer().install(BundledAddonKind.TEMPLATE, "starter.cgt", bytes("new"), sha256("new")) + + assertThat(installed.failure).isNull() + assertThat(File(templatesDir, "starter.cgt").readText()).isEqualTo("new") + } + @Test fun `a plugin copy that fails leaves no file behind`() { assertThrows(IOException::class.java) { diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsTest.kt index 1e76ed089d..d4528818f2 100644 --- a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsTest.kt +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsTest.kt @@ -1,6 +1,7 @@ package com.itsaky.androidide.assets.addons import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage import com.itsaky.androidide.assets.AssetsInstallationHelper import org.adfa.constants.ANDROID_SDK_ZIP import org.adfa.constants.DOCUMENTATION_DB @@ -23,7 +24,10 @@ class BundledAddonsTest { private class FakeSource( private val files: Map>, + private val indexText: String? = null, ) : BundleSource { + override fun index() = indexText + override fun names(dir: String) = files[dir]?.keys?.toList().orEmpty() override fun size( @@ -40,7 +44,37 @@ class BundledAddonsTest { private fun source( plugins: Map = emptyMap(), templates: Map = emptyMap(), - ) = FakeSource(mapOf("plugins" to plugins, "templates" to templates)) + index: String? = null, + ) = FakeSource(mapOf("plugins" to plugins, "templates" to templates), index) + + /** A source with only an index: asking it for a folder, a size or a file fails the test. */ + private class IndexOnlySource( + private val indexText: String, + ) : BundleSource { + override fun names(dir: String): List = throw AssertionError("listed $dir") + + override fun size( + dir: String, + name: String, + ): Long = throw AssertionError("sized $dir/$name") + + override fun open( + dir: String, + name: String, + ): InputStream = throw AssertionError("opened $dir/$name") + + override fun index() = indexText + } + + private val shaA = "a".repeat(64) + private val shaB = "b".repeat(64) + private val shaT = "c".repeat(64) + + private fun line( + entryName: String, + size: Long, + sha256: String, + ) = "$entryName\t$size\t$sha256\n" @Test fun `a thin bundle lists nothing`() { @@ -189,6 +223,91 @@ class BundledAddonsTest { } } + @Test + fun `an index lists the bundle without listing, sizing or opening an add-on`() { + val index = line("plugins/b.cgp", 20L, shaB) + line("templates/t.cgt", 30L, shaT) + line("plugins/a.cgp", 10L, shaA) + + assertThat(BundledAddons.list(IndexOnlySource(index))) + .containsExactly( + BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 10L, shaA), + BundledEntry(BundledAddonKind.PLUGIN, "b.cgp", 20L, shaB), + BundledEntry(BundledAddonKind.TEMPLATE, "t.cgt", 30L, shaT), + ).inOrder() + } + + @Test + fun `an empty index is a thin bundle`() { + assertThat(BundledAddons.list(IndexOnlySource(""))).isEmpty() + assertThat(BundledAddons.list(IndexOnlySource("\n"))).isEmpty() + } + + @Test + fun `the fingerprint notices new content at the same name and size`() { + val old = BundledAddons.list(IndexOnlySource(line("plugins/a.cgp", 10L, shaA))) + val rebuilt = BundledAddons.list(IndexOnlySource(line("plugins/a.cgp", 10L, shaB))) + + assertThat(BundledAddons.fingerprint(rebuilt)).isNotEqualTo(BundledAddons.fingerprint(old)) + assertThat(BundledAddons.fingerprint(old)).isNotEqualTo(BundledAddons.fingerprint(emptyList())) + } + + @Test + fun `a malformed index leaves the folders to decide`() { + val folders = listOf(BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 10L)) + val malformed = + listOf( + "plugins/a.cgp\t10\n", + "plugins/a.cgp\t10\t$shaA\textra\n", + "plugins/a.cgp\tten\t$shaA\n", + "plugins/a.cgp\t-1\t$shaA\n", + "plugins/a.cgp\t10\t${shaA.uppercase()}\n", + "plugins/a.cgp\t10\t${shaA.drop(1)}\n", + line("other/a.cgp", 10L, shaA), + line("plugins/nested/a.cgp", 10L, shaA), + line("plugins/.hidden.cgp", 10L, shaA), + line("templates/$TEMPLATE_CORE_ARCHIVE", 10L, shaA), + line("plugins/a.cgp", 10L, shaA) + line("plugins/a.cgp", 10L, shaB), + ) + + malformed.forEach { index -> + assertWithMessage(index).that(BundledAddons.list(source(plugins = mapOf("a.cgp" to 10L), index = index))).isEqualTo(folders) + } + } + + @Test + fun `a bundle without an index is listed from its folders, without hashes`() { + val entries = BundledAddons.list(source(plugins = mapOf("a.cgp" to 10L))) + + assertThat(entries).containsExactly(BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 10L)) + assertThat(entries.single().sha256).isNull() + } + + @Test + fun `a zip source reads its index, and has none without the entry`() { + val indexed = tempFolder.newFile("indexed.zip") + ZipOutputStream(indexed.outputStream()).use { zip -> + zip.putNextEntry(ZipEntry("plugins/a.cgp")) + zip.write(ByteArray(5)) + zip.closeEntry() + zip.putNextEntry(ZipEntry(BundledAddons.INDEX_FILE)) + zip.write(line("plugins/a.cgp", 5L, shaA).toByteArray()) + zip.closeEntry() + } + val plain = tempFolder.newFile("plain.zip") + ZipOutputStream(plain.outputStream()).use { zip -> + zip.putNextEntry(ZipEntry("plugins/a.cgp")) + zip.write(ByteArray(5)) + zip.closeEntry() + } + + ZipFile(indexed).use { zip -> + assertThat(BundledAddons.list(ZipBundleSource(zip))).containsExactly(BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 5L, shaA)) + } + ZipFile(plain).use { zip -> + assertThat(ZipBundleSource(zip).index()).isNull() + assertThat(BundledAddons.list(ZipBundleSource(zip))).containsExactly(BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 5L)) + } + } + @Test fun `a zip source without the folders lists nothing`() { val zipFile = tempFolder.newFile("thin.zip") diff --git a/resources/src/main/res/values/strings.xml b/resources/src/main/res/values/strings.xml index b29987ca32..ca581c25d6 100644 --- a/resources/src/main/res/values/strings.xml +++ b/resources/src/main/res/values/strings.xml @@ -110,7 +110,7 @@ Assets file \'%1$s\' not found. Copy it to %2$s, then restart %3$s. - Some plugins that came with the app did not start:\n%1$s + Some plugins or templates that came with the app could not be installed or started:\n%1$s The picked file is not a directory. Please wait for a moment. Not enough storage available for installation. An additional %1$.1fGB is required on the internal storage partition. You currently have %2$.1fGB available. From 9ee25ddd6be1dce7d2b72abe0bfb313ff3f2919a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 02:07:57 +0000 Subject: [PATCH 18/22] ADFA-7238: Warn when a present bundle index is rejected BundledAddons.list fell back to listing the folders without a word when the index was there but parseIndex rejected it. Every entry then has no SHA-256, so no copy is checked and the fingerprint loses its hashes. Log a warning in that case; behaviour is unchanged (CodeRabbit nitpick). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- .../itsaky/androidide/assets/addons/BundledAddons.kt | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt index 60c0964b86..a224d8d70a 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt @@ -3,6 +3,7 @@ package com.itsaky.androidide.assets.addons import org.adfa.constants.PLUGIN_ARCHIVE_EXTENSION import org.adfa.constants.TEMPLATE_ARCHIVE_EXTENSION import org.adfa.constants.TEMPLATE_CORE_ARCHIVE +import org.slf4j.LoggerFactory import java.io.InputStream import java.security.MessageDigest @@ -49,6 +50,8 @@ interface BundleSource { } object BundledAddons { + private val logger = LoggerFactory.getLogger(BundledAddons::class.java) + /** * The bundle index, written by the build beside `plugins/` and `templates/`: one line per add-on, * `\t\t`. A thin build writes it empty. With it, listing the bundle @@ -72,7 +75,13 @@ object BundledAddons { * before the index, the folders are listed and each file's size read: other files in the folders, * and any path below them, are not add-ons. */ - fun list(source: BundleSource): List = source.index()?.let(::parseIndex) ?: listFolders(source) + fun list(source: BundleSource): List { + val index = source.index() + index?.let(::parseIndex)?.let { return it } + // A present but rejected index loses every copy's SHA-256 check, so say so. + if (index != null) logger.warn("Bundle index {} is not valid; listing the folders without content checks", INDEX_FILE) + return listFolders(source) + } /** * The entries of an index, in [list]'s order, or null when any line is malformed, names no add-on From 020e45b0ee36efdcdb86ab00610fefec0ae0c18d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 02:07:58 +0000 Subject: [PATCH 19/22] ADFA-7238: One add-on rule and index format for both bundle builders The release staging task and the debug zip each spelled out the add-on file rule (not hidden, extension in any case, not core.cgt), the index line format and the index file name. If one copy changed alone, the two builds could write indexes the app rejects, and the app would fall back to unchecked folder listing without notice. Both now call the BundledAddonFiles object (CodeRabbit nitpick). The output is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- app/build.gradle.kts | 51 +++++++++++++++++++++++++++++++------------- 1 file changed, 36 insertions(+), 15 deletions(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 8a65c564e7..61aa3a1fa4 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -700,6 +700,34 @@ val quickBuildDaemonZip = // Beside them goes the bundle index, bundled-addons.tsv (BundledAddons.INDEX_FILE): one line per // add-on, "/\t\t", empty in a thin build. The app lists and fingerprints // the bundle from it, so it opens no add-on at start-up and notices a rebuild of the same size. +// The one copy of the add-on file rule and the index format, for the release staging task and the +// debug zip alike. The app's side is BundledAddons (INDEX_FILE, isAddonFile, parseIndex): an index +// it rejects silently loses every copy's SHA-256 check, so these must not drift. +object BundledAddonFiles { + const val INDEX_FILE = "bundled-addons.tsv" + + /** Each bundled folder with the extension of its add-ons, plugins first. */ + val DIRS = listOf("plugins" to "cgp", "templates" to "cgt") + + /** A file named [name] is a bundled add-on: not hidden, [extension] in any case, not core.cgt. */ + fun isAddonName( + name: String, + extension: String, + ): Boolean = + !name.startsWith(".") && + name.endsWith(".$extension", ignoreCase = true) && + // core.cgt has its own asset entry; same rule as BundledAddons.isAddonFile. + !name.equals("core.cgt", ignoreCase = true) + + /** The index line of the add-on [name] in [dir]: "/\t\t\n". */ + fun indexLine( + dir: String, + name: String, + size: Long, + sha256: ByteArray, + ): String = "$dir/$name\t$size\t${sha256.joinToString("") { "%02x".format(it) }}\n" +} + abstract class StageBundledAddons : DefaultTask() { @get:InputFiles @get:PathSensitive(PathSensitivity.NAME_ONLY) @@ -726,7 +754,7 @@ abstract class StageBundledAddons : DefaultTask() { .filter { !it.name.startsWith(".") } .sortedBy { it.name } .forEach { index.append(stage(it, "templates", out)) } - File(out, "bundled-addons.tsv").writeText(index.toString()) + File(out, BundledAddonFiles.INDEX_FILE).writeText(index.toString()) } /** Copies [file] into [dir] of [out], hashing it on the way, and returns its index line. */ @@ -741,7 +769,7 @@ abstract class StageBundledAddons : DefaultTask() { file.inputStream().use { input -> DigestOutputStream(dest.outputStream(), digest).use { output -> input.copyTo(output) } } - return "$dir/${file.name}\t${dest.length()}\t${digest.digest().joinToString("") { "%02x".format(it) }}\n" + return BundledAddonFiles.indexLine(dir, file.name, dest.length(), digest.digest()) } } @@ -752,10 +780,7 @@ fun isBundledAddon( ): Boolean = !element.isDirectory && element.relativePath.segments.size == 1 && - !element.name.startsWith(".") && - element.name.endsWith(".$extension", ignoreCase = true) && - // core.cgt has its own asset entry; same rule as BundledAddons.isAddonFile. - !element.name.equals("core.cgt", ignoreCase = true) + BundledAddonFiles.isAddonName(element.name, extension) androidComponents.onVariants { variant -> val variantName = variant.name.replaceFirstChar(Char::uppercaseChar) @@ -1122,15 +1147,11 @@ fun createAssetsZip(arch: String) { // Add-ons of a fat build, as plugins/ and templates/; none in a thin one. Then the // bundle index, as StageBundledAddons writes it for a release build. val index = StringBuilder() - arrayOf("plugins" to "cgp", "templates" to "cgt").forEach { (dirName, extension) -> + BundledAddonFiles.DIRS.forEach { (dirName, extension) -> sourceDir .resolve(dirName) - .listFiles { file -> - file.isFile && - !file.name.startsWith(".") && - file.extension.equals(extension, ignoreCase = true) && - !file.name.equals("core.cgt", ignoreCase = true) - }.orEmpty() + .listFiles { file -> file.isFile && BundledAddonFiles.isAddonName(file.name, extension) } + .orEmpty() .sortedBy { it.name } .forEach { file -> project.logger.lifecycle("Zipping bundled add-on $dirName/${file.name} from ${file.absolutePath}") @@ -1138,10 +1159,10 @@ fun createAssetsZip(arch: String) { zipOut.putNextEntry(ZipEntry("$dirName/${file.name}")) file.inputStream().use { input -> DigestInputStream(input, digest).copyTo(zipOut) } zipOut.closeEntry() - index.append("$dirName/${file.name}\t${file.length()}\t${digest.digest().joinToString("") { "%02x".format(it) }}\n") + index.append(BundledAddonFiles.indexLine(dirName, file.name, file.length(), digest.digest())) } } - zipOut.putNextEntry(ZipEntry("bundled-addons.tsv")) + zipOut.putNextEntry(ZipEntry(BundledAddonFiles.INDEX_FILE)) zipOut.write(index.toString().toByteArray(Charsets.UTF_8)) zipOut.closeEntry() } From a9b0a492ce08436f591a8d6034997fce766103b8 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 12:26:23 -0800 Subject: [PATCH 20/22] ADFA-7238: Mark bundled failures reported only when the user dismisses the bar On a Note 20, a font scale change with the failures bar up recreated MainActivity: the bar went away undismissed, and the failures, marked reported as soon as the bar appeared, never showed again. MainActivity handles rotation itself, but font scale, dark mode, locale and display size changes recreate it. - BundledAddonsRecord.reportFailures (new, BundledFailureReport.kt) shows the unreported failures and suspends until the user dismisses the bar, then marks them. If the screen goes away first, its lifecycleScope cancels the wait and the next MainActivity shows them again. The report lasts while the bar is up, so MainActivity's guard keeps a resume from showing a second bar; after a dismissal the record has nothing left. - Activity.flashErrorTracked returns a TrackedFlashbar to await the bar's appearance or dismissal; the AwaitShown helpers now go through it. Destroying the activity only detaches the bar's view: Flashbar fires onDismissed for the Dismiss button, a tap, a swipe, a timeout or a tap outside, never for a detach, so a dismissal is always the user's. - markReported takes the failures that were on the bar and marks only those, so one recorded while the bar is up (ADFA-7239's start-up sync after its 30 s wait) stays unreported now that the bar can stay up for minutes. The report no longer waits on the 3 s show timeout, so a slow bar is no longer shown twice. Tests: BundledFailureReportTest (fails with the old mark-once-shown rule), TrackedFlashbarTest (Robolectric: the Dismiss button dismisses; a font scale recreation, or finish and destroy, does not), and two BundledAddonsRecordTest cases for the targeted mark. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- .../androidide/activities/MainActivity.kt | 19 ++- .../assets/addons/BundledAddonsRecord.kt | 12 +- .../assets/addons/BundledFailureReport.kt | 29 +++++ .../assets/addons/BundledAddonsRecordTest.kt | 34 +++++- .../assets/addons/BundledFailureReportTest.kt | 114 ++++++++++++++++++ .../assets/addons/BundledPluginStartupTest.kt | 5 +- .../androidide/utils/FlashbarActivityUtils.kt | 73 +++++++++-- .../androidide/utils/TrackedFlashbarTest.kt | 88 ++++++++++++++ 8 files changed, 343 insertions(+), 31 deletions(-) create mode 100644 app/src/main/java/com/itsaky/androidide/assets/addons/BundledFailureReport.kt create mode 100644 app/src/test/java/com/itsaky/androidide/assets/addons/BundledFailureReportTest.kt create mode 100644 common/src/test/java/com/itsaky/androidide/utils/TrackedFlashbarTest.kt diff --git a/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt index 4a01e38e31..72ad9d62f4 100755 --- a/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt @@ -48,6 +48,7 @@ import com.itsaky.androidide.analytics.depth import com.itsaky.androidide.analytics.selector import com.itsaky.androidide.app.EdgeToEdgeIDEActivity import com.itsaky.androidide.assets.addons.BundledAddonsRecord +import com.itsaky.androidide.assets.addons.reportFailures import com.itsaky.androidide.databinding.ActivityMainBinding import com.itsaky.androidide.deeplink.ConsumedRequests import com.itsaky.androidide.fragments.MainFragment @@ -80,7 +81,7 @@ import com.itsaky.androidide.utils.UrlManager import com.itsaky.androidide.utils.applyBottomWindowInsetsPadding import com.itsaky.androidide.utils.findValidProjects import com.itsaky.androidide.utils.flashError -import com.itsaky.androidide.utils.flashErrorAwaitShown +import com.itsaky.androidide.utils.flashErrorTracked import com.itsaky.androidide.utils.flashInfo import com.itsaky.androidide.utils.hasVisibleDialog import com.itsaky.androidide.utils.recordProjectOpenedBookkeeping @@ -344,8 +345,9 @@ class MainActivity : EdgeToEdgeIDEActivity() { /** * Tells the user once which plugins bundled with the build did not start. The failures are - * marked reported only once the bar has finished appearing, so a screen that goes away first - * reports them next time; [reportingBundledFailures] keeps a resume during the report from + * marked reported only when the user dismisses the bar ([reportFailures]); a screen that goes + * away first, as a font scale change recreates it, shows them again next time. The report runs + * until the dismissal, and [reportingBundledFailures] keeps a resume during the report from * starting a second one. */ private fun reportBundledPluginFailures() { @@ -354,19 +356,14 @@ class MainActivity : EdgeToEdgeIDEActivity() { lifecycleScope.launch { try { val record = BundledAddonsRecord.inFilesDir(filesDir) - val failures = - withContext(Dispatchers.IO) { - runCatching { record.unreportedFailures() }.getOrDefault(emptyList()) - } - if (failures.isEmpty()) return@launch - val shown = - this@MainActivity.flashErrorAwaitShown( + record.reportFailures { failures -> + flashErrorTracked( getString( string.msg_bundled_plugins_failed, failures.joinToString("\n") { "${it.pluginId}: ${it.message}" }, ), ) - if (shown) withContext(Dispatchers.IO) { runCatching { record.markReported() } } + } } finally { reportingBundledFailures = false } diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonsRecord.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonsRecord.kt index 33f8590df6..877c2f7354 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonsRecord.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonsRecord.kt @@ -93,13 +93,17 @@ class BundledAddonsRecord( @Synchronized fun unreportedFailures(): List = read()?.failures.orEmpty().filterNot { it.reported } - /** Marks every recorded failure as told, and returns those that were not before. */ + /** + * Marks [told] as told, and returns those that were not before. A failure recorded since [told] + * was read, or recorded again with another message, stays unreported. + */ @Synchronized - fun markReported(): List { + fun markReported(told: Collection): List { val state = read() ?: return emptyList() - val pending = state.failures.filterNot { it.reported } + val keys = told.mapTo(HashSet()) { it.pluginId to it.message } + val pending = state.failures.filter { !it.reported && (it.pluginId to it.message) in keys } if (pending.isNotEmpty()) { - write(state.copy(failures = state.failures.map { it.copy(reported = true) })) + write(state.copy(failures = state.failures.map { if (it in pending) it.copy(reported = true) else it })) } return pending } diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledFailureReport.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledFailureReport.kt new file mode 100644 index 0000000000..6dbb6573a7 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledFailureReport.kt @@ -0,0 +1,29 @@ +package com.itsaky.androidide.assets.addons + +import com.itsaky.androidide.utils.TrackedFlashbar +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.withContext +import kotlin.coroutines.CoroutineContext + +/** + * Shows the failures the user has not been told about with [show], and marks them reported only once + * the user dismisses the bar. Until then this suspends, so a caller that runs one report at a time + * shows no second bar while one is up. + * + * If the caller's scope ends first - the screen went away, say recreated by a font scale change - the + * failures stay unreported and the next report shows them again. Destroying an activity fires no + * dismiss callback, so only the user ends the wait. A failure recorded while the bar is up is not + * marked: it was not on the bar. + */ +suspend fun BundledAddonsRecord.reportFailures( + io: CoroutineContext = Dispatchers.IO, + show: (List) -> TrackedFlashbar?, +) { + val failures = withContext(io) { runCatching { unreportedFailures() }.getOrDefault(emptyList()) } + if (failures.isEmpty()) return + val bar = show(failures) ?: return + bar.awaitDismissed() + // The user dismissed the bar: record that even if the screen goes away now. + withContext(NonCancellable + io) { runCatching { markReported(failures) } } +} diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsRecordTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsRecordTest.kt index ce5e77bf0f..6a8e396518 100644 --- a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsRecordTest.kt +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsRecordTest.kt @@ -31,7 +31,7 @@ class BundledAddonsRecordTest { fun `no file reads as no record`() { assertThat(record.read()).isNull() assertThat(record.unreportedFailures()).isEmpty() - assertThat(record.markReported()).isEmpty() + assertThat(record.markReported(listOf(BundledPluginFailure("com.example.one", "boom")))).isEmpty() } @Test @@ -107,8 +107,9 @@ class BundledAddonsRecordTest { record.write(state) record.recordFailures(mapOf("com.example.one" to "boom")) - val first = record.markReported() - val second = record.markReported() + val told = record.unreportedFailures() + val first = record.markReported(told) + val second = record.markReported(told) assertThat(first).containsExactly(BundledPluginFailure("com.example.one", "boom", reported = false)) assertThat(second).isEmpty() @@ -120,13 +121,38 @@ class BundledAddonsRecordTest { fun `a new failure after a report is unreported again`() { record.write(state) record.recordFailures(mapOf("com.example.one" to "boom")) - record.markReported() + record.markReported(record.unreportedFailures()) record.recordFailures(mapOf("com.example.two" to "bang")) assertThat(record.unreportedFailures()).containsExactly(BundledPluginFailure("com.example.two", "bang", reported = false)) } + @Test + fun `markReported leaves a failure recorded after the told ones were read`() { + record.write(state) + record.recordFailures(mapOf("com.example.one" to "boom")) + val told = record.unreportedFailures() + + record.recordFailures(mapOf("com.example.two" to "bang")) + val marked = record.markReported(told) + + assertThat(marked).containsExactly(BundledPluginFailure("com.example.one", "boom")) + assertThat(record.unreportedFailures()).containsExactly(BundledPluginFailure("com.example.two", "bang")) + } + + @Test + fun `markReported leaves a failure recorded again with another message`() { + record.write(state) + record.recordFailures(mapOf("com.example.one" to "boom")) + val told = record.unreportedFailures() + + record.recordFailures(mapOf("com.example.one" to "bang")) + record.markReported(told) + + assertThat(record.unreportedFailures()).containsExactly(BundledPluginFailure("com.example.one", "bang")) + } + @Test fun `recording load failures keeps failures recorded under other keys`() { record.write(state.copy(failures = listOf(BundledPluginFailure("broken.cgp", "it has no readable manifest")))) diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledFailureReportTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledFailureReportTest.kt new file mode 100644 index 0000000000..558074e7f8 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledFailureReportTest.kt @@ -0,0 +1,114 @@ +package com.itsaky.androidide.assets.addons + +import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage +import com.itsaky.androidide.utils.TrackedFlashbar +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File +import kotlin.coroutines.EmptyCoroutineContext + +/** + * The bundled plugin failures stay unreported until the user dismisses their bar (F30): a screen + * recreated by a font scale change took the bar away, and the failures, already marked when the bar + * appeared, never showed again. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class BundledFailureReportTest { + @get:Rule + val tempFolder = TemporaryFolder() + + private lateinit var record: BundledAddonsRecord + private val bars = ArrayList() + + private class FakeBar( + val failures: List, + ) : TrackedFlashbar { + val dismissed = CompletableDeferred() + + override suspend fun awaitShown() = true + + override suspend fun awaitDismissed() = dismissed.await() + } + + @Before + fun setUp() { + record = BundledAddonsRecord(File(tempFolder.root, "bundled_addons.properties")) + record.write(BundledAddonsState("fp", listOf("com.example.one", "com.example.two"))) + record.recordFailures(mapOf("com.example.one" to "boom")) + bars.clear() + } + + private fun TestScope.startReport(): Job { + val job = launch { record.reportFailures(EmptyCoroutineContext) { FakeBar(it).also(bars::add) } } + runCurrent() + return job + } + + @Test + fun `the failures stay unreported until the user dismisses the bar, so the next screen shows them again`() = + runTest { + val report = startReport() + assertThat(bars).hasSize(1) + assertWithMessage("failures marked reported while the bar is still up") + .that(record.unreportedFailures()) + .containsExactly(BundledPluginFailure("com.example.one", "boom")) + + // The screen goes away with the bar up: its scope ends, and no dismiss callback fires. + report.cancel() + runCurrent() + assertThat(record.unreportedFailures()).containsExactly(BundledPluginFailure("com.example.one", "boom")) + + val next = startReport() + assertThat(bars).hasSize(2) + assertThat(bars[1].failures).containsExactly(BundledPluginFailure("com.example.one", "boom")) + next.cancel() + } + + @Test + fun `the report lasts while the bar is up, and dismissing it marks the failures reported`() = + runTest { + val report = startReport() + assertWithMessage("report ended before the user dismissed the bar").that(report.isActive).isTrue() + + bars.single().dismissed.complete(Unit) + runCurrent() + + assertThat(report.isCompleted).isTrue() + assertThat(record.unreportedFailures()).isEmpty() + startReport() + assertWithMessage("a bar shown again after the user dismissed it").that(bars).hasSize(1) + } + + @Test + fun `a failure recorded while the bar is up stays unreported`() = + runTest { + startReport() + record.recordFailures(mapOf("com.example.two" to "bang")) + + bars.single().dismissed.complete(Unit) + runCurrent() + + assertThat(record.unreportedFailures()).containsExactly(BundledPluginFailure("com.example.two", "bang")) + } + + @Test + fun `no unreported failure shows no bar`() = + runTest { + record.markReported(record.unreportedFailures()) + + val report = startReport() + + assertThat(bars).isEmpty() + assertThat(report.isCompleted).isTrue() + } +} diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledPluginStartupTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledPluginStartupTest.kt index 0237d88eff..05b44b6580 100644 --- a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledPluginStartupTest.kt +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledPluginStartupTest.kt @@ -93,8 +93,9 @@ class BundledPluginStartupTest { writeBundle("a") startup(loadError = { "boom" }).start() - val first = record.markReported() - val second = record.markReported() + val told = record.unreportedFailures() + val first = record.markReported(told) + val second = record.markReported(told) assertThat(first.map { it.pluginId }).containsExactly("a") assertThat(second).isEmpty() diff --git a/common/src/main/java/com/itsaky/androidide/utils/FlashbarActivityUtils.kt b/common/src/main/java/com/itsaky/androidide/utils/FlashbarActivityUtils.kt index 672bef9f2e..f3b82d4e21 100644 --- a/common/src/main/java/com/itsaky/androidide/utils/FlashbarActivityUtils.kt +++ b/common/src/main/java/com/itsaky/androidide/utils/FlashbarActivityUtils.kt @@ -63,7 +63,7 @@ private fun Flashbar.Builder.applyIcon(iconType: IconType): Flashbar.Builder = /** * Builds and configures a Flashbar for [msg]/[iconType] (icon, and - for an indefinite error - the * dismiss button plus tap/swipe dismissal), without showing it yet. Shared by [showFlashBar] and - * [showFlashBarAwaitShown] + * [showTrackedFlashBar] * so their setup can't silently diverge. Returns `null` for a `null` [msg] (nothing to show). */ private fun Activity.configureFlashbar( @@ -161,22 +161,34 @@ fun Activity.flashInfo(msg: String?) = showFlashBar(msg, IconType.INFO) // is the difference between an explanation and a flicker. fun Activity.flashInfoLong(msg: String?) = showFlashBar(msg, IconType.INFO, duration = DURATION_LONG) +/** A bar shown by [flashErrorTracked], for a caller that waits for it to appear or to be dismissed. */ +interface TrackedFlashbar { + /** Suspends until the bar has finished appearing; false if it has not within [FLASH_SHOWN_TIMEOUT_MS]. */ + suspend fun awaitShown(): Boolean + + /** + * Suspends until the bar is dismissed; for an indefinite error bar, only the user does that. + * Destroying the activity fires no dismiss callback (the bar's view is only detached), so if the + * activity goes away first this never returns: wait in a scope that ends with the activity, such + * as its lifecycleScope. + */ + suspend fun awaitDismissed() +} + /** - * Like [showFlashBar], but suspends until the bar's entrance animation has actually finished (or - * [FLASH_SHOWN_TIMEOUT_MS] elapses) instead of firing-and-forgetting - for callers (e.g. a - * one-shot screen about to finish()) that need the message to be visible before proceeding, - * rather than guessing a fixed delay that may or may not outlast the real animation. - * Returns whether the bar finished appearing: false for a `null` [msg] or on timeout. + * Like [showFlashBar], but returns a [TrackedFlashbar] to wait on: for its entrance animation to + * finish, or for its dismissal. Returns `null` for a `null` [msg]. */ -private suspend fun Activity.showFlashBarAwaitShown( +private fun Activity.showTrackedFlashBar( msg: Any?, iconType: IconType, gravity: Flashbar.Gravity = TOP, duration: Long = Flashbar.DURATION_SHORT, -): Boolean { - val builder = configureFlashbar(msg, iconType, gravity, duration) ?: return false +): TrackedFlashbar? { + val builder = configureFlashbar(msg, iconType, gravity, duration) ?: return null val shown = CompletableDeferred() + val dismissed = CompletableDeferred() builder.barShowListener( object : Flashbar.OnBarShowListener { override fun onShowing(bar: Flashbar) = Unit @@ -191,15 +203,56 @@ private suspend fun Activity.showFlashBarAwaitShown( } }, ) + builder.barDismissListener( + object : Flashbar.OnBarDismissListener { + override fun onDismissing( + bar: Flashbar, + isSwiped: Boolean, + ) = Unit + + override fun onDismissProgress( + bar: Flashbar, + progress: Float, + ) = Unit + + override fun onDismissed( + bar: Flashbar, + event: Flashbar.DismissEvent, + ) { + dismissed.complete(Unit) + } + }, + ) runOnUiThread { builder.build().show() } - return withTimeoutOrNull(FLASH_SHOWN_TIMEOUT_MS) { shown.await() } != null + return object : TrackedFlashbar { + override suspend fun awaitShown() = withTimeoutOrNull(FLASH_SHOWN_TIMEOUT_MS) { shown.await() } != null + + override suspend fun awaitDismissed() = dismissed.await() + } } +/** + * Like [showFlashBar], but suspends until the bar's entrance animation has actually finished (or + * [FLASH_SHOWN_TIMEOUT_MS] elapses) instead of firing-and-forgetting - for callers (e.g. a + * one-shot screen about to finish()) that need the message to be visible before proceeding, + * rather than guessing a fixed delay that may or may not outlast the real animation. + * Returns whether the bar finished appearing: false for a `null` [msg] or on timeout. + */ +private suspend fun Activity.showFlashBarAwaitShown( + msg: Any?, + iconType: IconType, + gravity: Flashbar.Gravity = TOP, + duration: Long = Flashbar.DURATION_SHORT, +): Boolean = showTrackedFlashBar(msg, iconType, gravity, duration)?.awaitShown() ?: false + suspend fun Activity.flashSuccessAwaitShown(msg: String?) = showFlashBarAwaitShown(msg, IconType.SUCCESS) suspend fun Activity.flashErrorAwaitShown(msg: String?) = showFlashBarAwaitShown(msg, IconType.ERROR, duration = DURATION_INDEFINITE) +/** Shows an indefinite error bar, as [flashError] does, and returns it to wait on; `null` for a `null` [msg]. */ +fun Activity.flashErrorTracked(msg: String?): TrackedFlashbar? = showTrackedFlashBar(msg, IconType.ERROR, duration = DURATION_INDEFINITE) + fun Activity.flashSuccess( @StringRes msg: Int, ) = showFlashBar(msg, IconType.SUCCESS) diff --git a/common/src/test/java/com/itsaky/androidide/utils/TrackedFlashbarTest.kt b/common/src/test/java/com/itsaky/androidide/utils/TrackedFlashbarTest.kt new file mode 100644 index 0000000000..0f061e26a1 --- /dev/null +++ b/common/src/test/java/com/itsaky/androidide/utils/TrackedFlashbarTest.kt @@ -0,0 +1,88 @@ +package com.itsaky.androidide.utils + +import android.app.Activity +import android.content.res.Configuration +import android.os.Bundle +import android.os.Looper +import android.view.View +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.resources.R +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeoutOrNull +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import java.time.Duration +import com.itsaky.androidide.flashbar.R as FlashbarR + +/** + * Whether an indefinite error bar counts as dismissed: by the Dismiss button yes, by its activity + * going away no. Destroying the activity only detaches the bar's view, and Flashbar fires no dismiss + * callback for that, which is what lets a caller keep a report unread when a font scale change + * recreates the screen (F30). + */ +@RunWith(RobolectricTestRunner::class) +class TrackedFlashbarTest { + class ThemedActivity : Activity() { + override fun onCreate(savedInstanceState: Bundle?) { + setTheme(R.style.Theme_AndroidIDE) + super.onCreate(savedInstanceState) + } + } + + private fun idle() = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(5)) + + private fun TrackedFlashbar.isShown() = runBlocking { awaitShown() } + + private fun TrackedFlashbar.isDismissed() = runBlocking { withTimeoutOrNull(1) { awaitDismissed() } } != null + + @Test + fun `the Dismiss button dismisses the bar`() { + val controller = Robolectric.buildActivity(ThemedActivity::class.java).setup() + val bar = controller.get().flashErrorTracked("boom")!! + idle() + assertThat(bar.isShown()).isTrue() + assertThat(bar.isDismissed()).isFalse() + + controller + .get() + .window.decorView + .findViewById(FlashbarR.id.fbPositiveAction) + .performClick() + idle() + + assertThat(bar.isDismissed()).isTrue() + } + + @Test + fun `a font scale change that recreates the activity does not dismiss the bar`() { + val controller = Robolectric.buildActivity(ThemedActivity::class.java).setup() + val first = controller.get() + val bar = first.flashErrorTracked("boom")!! + idle() + assertThat(bar.isShown()).isTrue() + + controller.configurationChange(Configuration(first.resources.configuration).apply { fontScale = 2f }) + idle() + + assertThat(controller.get()).isNotSameInstanceAs(first) + assertThat(first.isDestroyed).isTrue() + assertThat(bar.isDismissed()).isFalse() + } + + @Test + fun `finishing and destroying the activity does not dismiss the bar`() { + val controller = Robolectric.buildActivity(ThemedActivity::class.java).setup() + val bar = controller.get().flashErrorTracked("boom")!! + idle() + assertThat(bar.isShown()).isTrue() + + controller.get().finish() + controller.pause().stop().destroy() + idle() + + assertThat(bar.isDismissed()).isFalse() + } +} From 6e6a0f0a84c083eec94d68530ab241b7929c22b9 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 13:36:23 -0800 Subject: [PATCH 21/22] ADFA-7238: Test that a load pass skips loaded files and keeps their failures PluginManagerLoadPassTest covers the loadPlugins() rules this branch added: - Skip: a second pass neither opens a loaded plugin's file again nor initializes or activates the plugin again. - Keep: a loaded plugin's activation failure survives a later pass; an uninstalled plugin's failure is dropped, while a failure the pass records itself is still reported. - Clear: enabling a plugin whose activation now succeeds clears its failure. Each test failed with its rule removed from PluginManager.kt. Removing only the path filter fails the file test alone: loadPlugin()'s already-loaded check still stops a second activation. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- .../manager/core/PluginManagerLoadPassTest.kt | 143 ++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadPassTest.kt diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadPassTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadPassTest.kt new file mode 100644 index 0000000000..454506bd9d --- /dev/null +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadPassTest.kt @@ -0,0 +1,143 @@ +package com.itsaky.androidide.plugins.manager.core + +import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage +import com.itsaky.androidide.plugins.IPlugin +import com.itsaky.androidide.plugins.PluginContext +import kotlinx.coroutines.runBlocking +import org.junit.After +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 +import java.util.concurrent.atomic.AtomicInteger + +/** + * loadPlugins() runs at startup, after every install and when bundled plugins start, so a pass + * meets plugins an earlier pass loaded. It leaves their files alone, so it keeps the activation + * failures they reported, which nothing would report again. It forgets the failures of plugins no + * longer loaded, and a plugin that activates clears its failure. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class PluginManagerLoadPassTest { + private val pluginsDir by lazy { File(RuntimeEnvironment.getApplication().filesDir, "plugins") } + + @Before + fun resetPlugin() = CountingPlugin.reset() + + @After + fun forgetManager() = forgetPluginManager() + + @Test + fun aSecondPassDoesNotLoadOrActivateALoadedPluginAgain() { + countingPlugin("a") + load() + val first = pluginManager().getPlugin("a") + assertWithMessage("plugin a did not load: ${pluginManager().getLoadError("a")}").that(first).isNotNull() + + load() + + assertWithMessage("the second pass replaced plugin a").that(pluginManager().getPlugin("a")).isSameInstanceAs(first) + assertWithMessage("the second pass initialized plugin a again").that(CountingPlugin.initializations.get()).isEqualTo(1) + assertWithMessage("the second pass activated plugin a again").that(CountingPlugin.activations.get()).isEqualTo(1) + } + + @Test + fun aSecondPassDoesNotOpenAFileAlreadyLoaded() { + val file = countingPlugin("a") + load() + assertThat(pluginManager().getLoadedPluginIds()).containsExactly("a") + // Robolectric reads a plugin's manifest from the package manager: the loaded file now reads + // as plugin "b", which only a pass that opened the file again would load. + fakePlugin(file, "b", NoopPlugin::class.java.name) + + load() + + assertWithMessage("the second pass opened the loaded file again").that(pluginManager().getLoadedPluginIds()).containsExactly("a") + } + + @Test + fun aLoadedPluginsActivationFailureSurvivesALaterPass() { + CountingPlugin.failActivation = true + countingPlugin("a") + load() + assertThat(pluginManager().getLoadedPluginIds()).containsExactly("a") + assertThat(pluginManager().getLoadError("a")).isEqualTo(CountingPlugin.ACTIVATION_ERROR) + + load() + + assertWithMessage("the later pass dropped the activation failure of loaded plugin a") + .that(pluginManager().getLoadError("a")) + .isEqualTo(CountingPlugin.ACTIVATION_ERROR) + } + + @Test + fun aPassDropsTheFailureOfAPluginNoLongerLoaded() { + CountingPlugin.failActivation = true + countingPlugin("a") + load() + assertThat(pluginManager().getLoadError("a")).isEqualTo(CountingPlugin.ACTIVATION_ERROR) + assertThat(pluginManager().uninstallPlugin("a")).isTrue() + // Its main class is missing, so the pass records a failure of its own, which it must report. + fakePlugin(File(pluginsDir, "b-0123456789012345.cgp"), "b") + + load() + + assertWithMessage("the failure of uninstalled plugin a outlived the pass").that(pluginManager().getLoadError("a")).isNull() + assertWithMessage("the pass dropped the failure it recorded itself").that(pluginManager().getLoadError("b")).isNotNull() + } + + @Test + fun aSuccessfulActivationClearsTheEarlierFailure() { + CountingPlugin.failActivation = true + countingPlugin("a") + load() + assertThat(pluginManager().getLoadError("a")).isEqualTo(CountingPlugin.ACTIVATION_ERROR) + + CountingPlugin.failActivation = false + assertWithMessage("enabling plugin a failed").that(pluginManager().enablePlugin("a")).isTrue() + + assertWithMessage("plugin a activated, but its earlier failure is still reported").that(pluginManager().getLoadError("a")).isNull() + } + + private fun load() = runBlocking { pluginManager().loadPlugins() } + + private fun countingPlugin(id: String) = fakePlugin(File(pluginsDir, "$id-0123456789012345.cgp"), id, CountingPlugin::class.java.name) + + /** Counts its initialize() and activate() calls. activate() throws while [failActivation] is set. */ + class CountingPlugin : IPlugin { + override fun initialize(context: PluginContext): Boolean { + initializations.incrementAndGet() + return true + } + + override fun activate(): Boolean { + activations.incrementAndGet() + check(!failActivation) { ACTIVATION_ERROR } + return true + } + + override fun deactivate() = true + + override fun dispose() = Unit + + companion object { + const val ACTIVATION_ERROR = "activate() failed on purpose" + val initializations = AtomicInteger() + val activations = AtomicInteger() + + @Volatile + var failActivation = false + + fun reset() { + initializations.set(0) + activations.set(0) + failActivation = false + } + } + } +} From 6e4c1aa114305f6ec065723a448250bbb73a5dfa Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 05:13:40 +0000 Subject: [PATCH 22/22] ADFA-7238: Say a bundled plugin may need a newer Android On a Galaxy J7 (Android 9), bundled AI-Core (minSdkVersion 33) was rejected as "it has no readable manifest". The platform parser most likely refuses a plugin that needs a newer Android, which from here looks the same as a damaged file, so the message hid the likelier cause from every Android 9-12 user of a fat build with such a plugin. It now reads "its manifest can't be read: it may need a newer version of Android, or be damaged" (BundledAddonInstaller.UNREADABLE_MANIFEST), and the installer test checks that text. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- .../androidide/assets/addons/BundledAddonInstaller.kt | 10 +++++++--- .../assets/addons/BundledAddonInstallerTest.kt | 2 +- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt index 77a69bc353..fe64cad837 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt @@ -92,7 +92,7 @@ class BundledAddonInstaller( readPluginId(copy) } catch (e: Exception) { null - } ?: throw RejectedAddonException("it has no readable manifest") + } ?: throw RejectedAddonException(UNREADABLE_MANIFEST) checkPluginId(id).onFailure { throw RejectedAddonException(it.message ?: "invalid plugin ID") } val name = "${PluginBuildFiles.fileStem(id, copy)}.$PLUGIN_ARCHIVE_EXTENSION" // 255 bytes is the longest file name the file system takes. @@ -110,8 +110,12 @@ class BundledAddonInstaller( return InstalledAddon(BundledAddonKind.PLUGIN, file, pluginId) } - private companion object { - const val MAX_FILE_NAME_BYTES = 255 + internal companion object { + private const val MAX_FILE_NAME_BYTES = 255 + + // The platform parser also refuses a plugin whose minSdkVersion is above the device's + // (AI-Core, 33, on Android 9), and the two cases look alike from here. + const val UNREADABLE_MANIFEST = "its manifest can't be read: it may need a newer version of Android, or be damaged" } private class RejectedAddonException( diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt index 2426e6a711..6eb02ae776 100644 --- a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt @@ -169,7 +169,7 @@ class BundledAddonInstallerTest { assertThat(result.file).isNull() assertThat(result.pluginId).isNull() assertThat(result.sourceName).isEqualTo("a.cgp") - assertThat(result.failure).isNotNull() + assertThat(result.failure).isEqualTo(BundledAddonInstaller.UNREADABLE_MANIFEST) assertThat(pluginsDir.list()!!.toList()).isEmpty() }