Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
0ea1a57
ADFA-7238: Serialize PluginManager.loadPlugins() and make checkPlugin…
claude Nov 21, 2026
94a0d1b
ADFA-7238: Bundle plugins and templates and install them at first ins…
claude Nov 21, 2026
56974f5
ADFA-7238: Report a bundled plugin with an unreadable manifest instea…
claude Nov 21, 2026
8625acc
ADFA-7238: Fix lint errors the formatter cannot fix
claude Nov 21, 2026
367c455
style: spotless reformat, no functional change
Nov 21, 2026
45f0eb0
Revert flox manifest changes swept in by the Spotless apply workflow
claude Nov 21, 2026
58082be
ADFA-7238: Fix review findings
claude Nov 21, 2026
ddec4d2
ADFA-7238: Address review findings
claude Nov 21, 2026
72d01e8
style: spotless reformat, no functional change
Nov 21, 2026
310ddfa
Revert flox manifest changes swept in by the Spotless apply workflow
claude Nov 21, 2026
ebb5329
ADFA-7238: Report bundled failures only once shown; clear recovered a…
claude Nov 21, 2026
86573c0
style: spotless reformat, no functional change
Nov 21, 2026
edcd3a9
Revert flox manifest changes swept in by the Spotless apply workflow
claude Nov 21, 2026
3267017
ADFA-7238: Fix load-failure pruning to check keys, not values
claude Nov 21, 2026
7671ff9
ADFA-7238: Load brotli for real before the bundle test mocks Brotli4j…
davidschachterADFA Nov 22, 2026
34d016e
ADFA-7238: Drop the staging task's output folder, which AGP replaces
davidschachterADFA Nov 22, 2026
eb8f522
ADFA-7238: Index the bundle, so listing it opens no add-on
davidschachterADFA Nov 22, 2026
fea9942
Merge remote-tracking branch 'origin/stage' into feature/ADFA-7238
claude Nov 23, 2026
5a1a0b4
Merge origin/stage into feature/ADFA-7238
claude Nov 24, 2026
9ee25dd
ADFA-7238: Warn when a present bundle index is rejected
claude Nov 24, 2026
020e45b
ADFA-7238: One add-on rule and index format for both bundle builders
claude Nov 24, 2026
a9b0a49
ADFA-7238: Mark bundled failures reported only when the user dismisse…
davidschachterADFA Nov 24, 2026
6e6a0f0
ADFA-7238: Test that a load pass skips loaded files and keeps their f…
davidschachterADFA Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,10 @@ 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
Expand Down
1 change: 1 addition & 0 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<name>` and `templates/<name>` (`StageBundledAddons` in `app/build.gradle.kts`), and `createAssetsZip()` adds the same entries to the debug `assets-<arch>.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 `<pluginId>-<hash>.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/<abi>/*.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).
Expand Down
127 changes: 127 additions & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -691,10 +693,113 @@ 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/<name> and templates/<name>. 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, "<dir>/<name>\t<size>\t<sha256>", 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]: "<dir>/<name>\t<size>\t<sha256 hex>\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)
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()
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, BundledAddonFiles.INDEX_FILE).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 BundledAddonFiles.indexLine(dir, file.name, dest.length(), digest.digest())
}
}

/** 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 &&
BundledAddonFiles.isAddonName(element.name, extension)

androidComponents.onVariants { variant ->
val variantName = variant.name.replaceFirstChar(Char::uppercaseChar)
val flavorName = variant.flavorName!!

if (hasBundledAssets(variant)) {
val stageBundledAddons =
tasks.register<StageBundledAddons>("stage${variantName}BundledAddons") {
// 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") } })
}
// AGP sets the task's outputDirectory: build/generated/assets/<task name>.
variant.sources.assets?.addGeneratedSourceDirectory(
stageBundledAddons,
StageBundledAddons::outputDirectory,
)
}

val copyRuntimeAar =
tasks.register<AddFileToAssetsTask>("copy${variantName}QuickBuildRuntimeAar") {
val runtimeProject = rootProject.project(":quickbuild:runtime")
Expand Down Expand Up @@ -1038,6 +1143,28 @@ fun createAssetsZip(arch: String) {
filePath.inputStream().use { input -> input.copyTo(zipOut) }
zipOut.closeEntry()
}

// Add-ons of a fat build, as plugins/<name> and templates/<name>; none in a thin one. Then the
// bundle index, as StageBundledAddons writes it for a release build.
val index = StringBuilder()
BundledAddonFiles.DIRS.forEach { (dirName, extension) ->
sourceDir
.resolve(dirName)
.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}")
val digest = MessageDigest.getInstance("SHA-256")
zipOut.putNextEntry(ZipEntry("$dirName/${file.name}"))
file.inputStream().use { input -> DigestInputStream(input, digest).copyTo(zipOut) }
zipOut.closeEntry()
index.append(BundledAddonFiles.indexLine(dirName, file.name, file.length(), digest.digest()))
}
}
zipOut.putNextEntry(ZipEntry(BundledAddonFiles.INDEX_FILE))
zipOut.write(index.toString().toByteArray(Charsets.UTF_8))
zipOut.closeEntry()
}
project.logger.lifecycle("Created ${zipFile.name} at ${zipFile.parentFile.absolutePath}")
}
Expand Down
32 changes: 32 additions & 0 deletions app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ 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.assets.addons.reportFailures
import com.itsaky.androidide.databinding.ActivityMainBinding
import com.itsaky.androidide.deeplink.ConsumedRequests
import com.itsaky.androidide.fragments.MainFragment
Expand Down Expand Up @@ -79,6 +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.flashErrorTracked
import com.itsaky.androidide.utils.flashInfo
import com.itsaky.androidide.utils.hasVisibleDialog
import com.itsaky.androidide.utils.recordProjectOpenedBookkeeping
Expand Down Expand Up @@ -109,6 +112,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.
Expand Down Expand Up @@ -336,6 +340,34 @@ class MainActivity : EdgeToEdgeIDEActivity() {
super.onResume()
MainScreenActions.register(this)
feedbackButtonManager?.loadFabPosition()
reportBundledPluginFailures()
}

/**
* Tells the user once which plugins bundled with the build did not start. The failures are
* 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() {
if (reportingBundledFailures) return
reportingBundledFailures = true
lifecycleScope.launch {
try {
val record = BundledAddonsRecord.inFilesDir(filesDir)
record.reportFailures { failures ->
flashErrorTracked(
getString(
string.msg_bundled_plugins_failed,
failures.joinToString("\n") { "${it.pluginId}: ${it.message}" },
),
)
}
} finally {
reportingBundledFailures = false
}
}
}

override fun onPause() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ 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.assets.addons.BundledPluginFailure
import com.itsaky.androidide.resources.R
import com.itsaky.androidide.utils.ContainedPathResolver
import com.itsaky.androidide.utils.ContainedPathResolver.Resolution
Expand All @@ -15,6 +21,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
Expand Down Expand Up @@ -69,6 +76,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<BundledEntry>): List<String> = expectedEntries + bundled.map { it.entryName }

suspend fun install(
context: Context,
onProgress: AssetsInstallerProgressConsumer = {},
Expand Down Expand Up @@ -124,18 +147,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)

Expand All @@ -160,17 +171,19 @@ object AssetsInstallationHelper {
logAndRethrow("I/O error during preInstall", e)
}

val bundledAddons = ASSETS_INSTALLER.listBundledAddons(context)
val entries = entriesToInstall(bundledAddons)

val entrySizes: Map<String, Long> =
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<String, String>()

val installerJobs =
expectedEntries.map { entry ->
entries.map { entry ->
Comment thread
davidschachterADFA marked this conversation as resolved.
Resolved
async {
entryStatusMap[entry] = STATUS_INSTALLING

Expand Down Expand Up @@ -233,6 +246,29 @@ object AssetsInstallationHelper {

// then cancel progress updater
progressUpdater.cancel()

// 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.
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 }
.mapNotNull { it.file?.name }
.sorted(),
// Add-ons 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 {
// 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
Expand Down
12 changes: 12 additions & 0 deletions app/src/main/java/com/itsaky/androidide/assets/AssetsInstaller.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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

/**
Expand Down Expand Up @@ -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<BundledEntry>

/** The add-ons [doInstall] has put in place since [listBundledAddons]. */
fun installedAddons(): List<InstalledAddon>
}
Loading
Loading