From 813c352d89d212e15a842710354196b2a7aa0ed7 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 21:33:44 -0800 Subject: [PATCH 01/21] ADFA-7137 Add debugger_endpoint_table and migration 5 to 6 The SQLite debugger in an app built by Code on the Go reports a token and a port; Code on the Go needs to keep them per app and per project. debugger_endpoint_table (RecentProjectRoomDatabase version 6) is keyed by application_id and holds project_location, token, port and updated_at. project_location is a foreign key to recent_project_table.location with ON DELETE CASCADE, so removing a project removes its endpoints, and ON UPDATE CASCADE, so renaming a project (which rewrites location) does not fail once an endpoint row exists. Room enables PRAGMA foreign_keys itself once the schema declares a foreign key, so no extra code is needed. The pairing upsert is INSERT OR IGNORE plus UPDATE in one transaction: minSdk 28 ships SQLite 3.22, which predates UPSERT (3.24). Tests: migration 5 to 6 on a v5 file opened through Room (projects kept, schema validated, cascade works on the migrated file); delete and rename cascades. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../recentproject/DebuggerEndpoint.kt | 36 +++ .../recentproject/DebuggerEndpointDao.kt | 63 ++++++ .../RecentProjectRoomDatabase.kt | 21 +- .../RecentProjectRoomDatabaseTest.kt | 213 ++++++++++++++++++ 4 files changed, 331 insertions(+), 2 deletions(-) create mode 100644 app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt create mode 100644 app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpointDao.kt diff --git a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt new file mode 100644 index 0000000000..f5e6d1c1cb --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt @@ -0,0 +1,36 @@ +package com.itsaky.androidide.roomData.recentproject + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.ForeignKey +import androidx.room.Index +import androidx.room.PrimaryKey + +/** + * The SQLite debugger endpoint of one app built from a project (ADFA-7131). [token], [port] and + * [updatedAt] stay null until the app reports them. + * + * ON UPDATE CASCADE as well as ON DELETE: renaming a project rewrites its recent_project_table + * location, which would otherwise be refused while foreign keys are on. + */ +@Entity( + tableName = "debugger_endpoint_table", + foreignKeys = [ + ForeignKey( + entity = RecentProject::class, + parentColumns = ["location"], + childColumns = ["project_location"], + onDelete = ForeignKey.CASCADE, + onUpdate = ForeignKey.CASCADE, + ), + ], + indices = [Index(value = ["project_location"])], +) +data class DebuggerEndpoint( + @PrimaryKey + @ColumnInfo(name = "application_id") val applicationId: String, + @ColumnInfo(name = "project_location") val projectLocation: String, + @ColumnInfo(name = "token") val token: String? = null, + @ColumnInfo(name = "port") val port: Int? = null, + @ColumnInfo(name = "updated_at") val updatedAt: Long? = null, +) diff --git a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpointDao.kt b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpointDao.kt new file mode 100644 index 0000000000..4108d69cfc --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpointDao.kt @@ -0,0 +1,63 @@ +package com.itsaky.androidide.roomData.recentproject + +import androidx.room.Dao +import androidx.room.Query +import androidx.room.Transaction + +@Dao +interface DebuggerEndpointDao { + @Query("INSERT OR IGNORE INTO debugger_endpoint_table (application_id, project_location) VALUES (:applicationId, :projectLocation)") + suspend fun insertPairingIfAbsent( + applicationId: String, + projectLocation: String, + ) + + @Query("UPDATE debugger_endpoint_table SET project_location = :projectLocation WHERE application_id = :applicationId") + suspend fun updatePairingLocation( + applicationId: String, + projectLocation: String, + ) + + /** Clears what the old project's build reported, when [applicationId] moves to another project. */ + @Query( + "UPDATE debugger_endpoint_table SET token = NULL, port = NULL, updated_at = NULL " + + "WHERE application_id = :applicationId AND project_location != :projectLocation", + ) + suspend fun clearEndpointIfProjectDiffers( + applicationId: String, + projectLocation: String, + ) + + /** + * Pairs [applicationId] with [projectLocation], keeping any token and port already stored + * unless the app was paired with a different project, whose build they belong to. + * Not REPLACE, which would delete the row and lose them. Two statements rather than + * ON CONFLICT DO UPDATE, which needs SQLite 3.24 and minSdk 28 ships 3.22. + * + * Throws SQLiteConstraintException when [projectLocation] has no recent_project_table row. + */ + @Transaction + suspend fun upsertPairing( + applicationId: String, + projectLocation: String, + ) { + insertPairingIfAbsent(applicationId, projectLocation) + clearEndpointIfProjectDiffers(applicationId, projectLocation) + updatePairingLocation(applicationId, projectLocation) + } + + /** Returns the number of rows changed: 0 when [applicationId] has no pairing. */ + @Query("UPDATE debugger_endpoint_table SET token = :token, port = :port, updated_at = :updatedAt WHERE application_id = :applicationId") + suspend fun updateEndpoint( + applicationId: String, + token: String, + port: Int, + updatedAt: Long, + ): Int + + @Query("SELECT * FROM debugger_endpoint_table WHERE project_location = :projectLocation") + suspend fun getByProjectLocation(projectLocation: String): List + + @Query("SELECT * FROM debugger_endpoint_table WHERE application_id = :applicationId") + suspend fun getByApplicationId(applicationId: String): DebuggerEndpoint? +} diff --git a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/RecentProjectRoomDatabase.kt b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/RecentProjectRoomDatabase.kt index 7aaaabfc64..870c435012 100644 --- a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/RecentProjectRoomDatabase.kt +++ b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/RecentProjectRoomDatabase.kt @@ -8,12 +8,14 @@ import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import kotlinx.coroutines.CoroutineScope -@Database(entities = [RecentProject::class, RecentProjectMaintenance::class], version = 5, exportSchema = false) +@Database(entities = [RecentProject::class, RecentProjectMaintenance::class, DebuggerEndpoint::class], version = 6, exportSchema = false) abstract class RecentProjectRoomDatabase : RoomDatabase() { abstract fun recentProjectDao(): RecentProjectDao abstract fun maintenanceDao(): RecentProjectMaintenanceDao + abstract fun debuggerEndpointDao(): DebuggerEndpointDao + fun vacuum() { val db = openHelper.writableDatabase db.execSQL("PRAGMA wal_checkpoint(FULL)") @@ -82,6 +84,21 @@ abstract class RecentProjectRoomDatabase : RoomDatabase() { } } + internal val migration5To6 = + object : Migration(5, 6) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL( + "CREATE TABLE IF NOT EXISTS `debugger_endpoint_table` (`application_id` TEXT NOT NULL, `project_location` TEXT NOT NULL, `token` TEXT, `port` INTEGER, `updated_at` INTEGER, PRIMARY KEY(`application_id`), FOREIGN KEY(`project_location`) REFERENCES `recent_project_table`(`location`) ON UPDATE CASCADE ON DELETE CASCADE )", + ) + db.execSQL( + "CREATE INDEX IF NOT EXISTS `index_debugger_endpoint_table_project_location` ON `debugger_endpoint_table` (`project_location`)", + ) + } + } + + internal val migrations: Array + get() = arrayOf(migration1To2, migration2To3, migration3To4, migration4To5, migration5To6) + fun getDatabase( context: Context, scope: CoroutineScope, @@ -93,7 +110,7 @@ abstract class RecentProjectRoomDatabase : RoomDatabase() { RecentProjectRoomDatabase::class.java, "RecentProject_database", ).addCallback(RecentProjectRoomDatabaseCallback(context, scope)) - .addMigrations(migration1To2, migration2To3, migration3To4, migration4To5) + .addMigrations(*migrations) .build() .also { instance = it } } diff --git a/app/src/test/java/com/itsaky/androidide/roomData/recentproject/RecentProjectRoomDatabaseTest.kt b/app/src/test/java/com/itsaky/androidide/roomData/recentproject/RecentProjectRoomDatabaseTest.kt index 542d5eaf04..10a0318521 100644 --- a/app/src/test/java/com/itsaky/androidide/roomData/recentproject/RecentProjectRoomDatabaseTest.kt +++ b/app/src/test/java/com/itsaky/androidide/roomData/recentproject/RecentProjectRoomDatabaseTest.kt @@ -1,14 +1,19 @@ package com.itsaky.androidide.roomData.recentproject import android.content.Context +import android.database.sqlite.SQLiteConstraintException +import android.database.sqlite.SQLiteDatabase +import androidx.room.Room import androidx.sqlite.db.SupportSQLiteDatabase import androidx.sqlite.db.SupportSQLiteOpenHelper import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.runBlocking import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner +import java.io.File @RunWith(RobolectricTestRunner::class) class RecentProjectRoomDatabaseTest { @@ -58,4 +63,212 @@ class RecentProjectRoomDatabaseTest { assertThat(tableFound).isTrue() } + + private fun createVersion5Database(name: String): File { + val context = ApplicationProvider.getApplicationContext() + val file = context.getDatabasePath(name) + file.parentFile?.mkdirs() + file.delete() + val db = SQLiteDatabase.openOrCreateDatabase(file, null) + db.execSQL( + "CREATE TABLE IF NOT EXISTS `recent_project_table` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `create_at` TEXT NOT NULL, `location` TEXT NOT NULL, `last_modified` TEXT NOT NULL DEFAULT '0', `template_name` TEXT NOT NULL DEFAULT 'unknown', `language` TEXT NOT NULL DEFAULT 'unknown')", + ) + db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS `index_recent_project_table_location` ON `recent_project_table` (`location`)") + db.execSQL( + "CREATE TABLE IF NOT EXISTS `recent_project_maintenance` (`key` TEXT NOT NULL, `completed` INTEGER NOT NULL, PRIMARY KEY(`key`))", + ) + db.execSQL( + "INSERT INTO recent_project_table (name, create_at, location, last_modified, template_name, language) VALUES ('A', '1', '/p/a', '10', 'Basic', 'Kotlin')", + ) + db.execSQL( + "INSERT INTO recent_project_table (name, create_at, location, last_modified, template_name, language) VALUES ('B', '2', '/p/b', '20', 'Empty', 'Java')", + ) + db.version = 5 + db.close() + return file + } + + @Test + fun `migration 5 to 6 keeps recent projects and creates the endpoint table with its foreign key and index`() { + val context = ApplicationProvider.getApplicationContext() + val name = "migration_5_6_test.db" + val file = createVersion5Database(name) + + // Room validates the migrated schema (columns, foreign keys, indices) against the entities + // when it opens the database, and throws if the migration SQL differs from what it expects. + val room = + Room + .databaseBuilder(context, RecentProjectRoomDatabase::class.java, name) + .addMigrations(RecentProjectRoomDatabase.migration5To6) + .allowMainThreadQueries() + .build() + try { + val projects = runBlocking { room.recentProjectDao().dumpAll() }.orEmpty() + assertThat(projects.map { it.location to it.name }).containsExactly("/p/b" to "B", "/p/a" to "A").inOrder() + assertThat(projects.map { it.language }).containsExactly("Java", "Kotlin").inOrder() + + val db = room.openHelper.writableDatabase + db.query("PRAGMA foreign_key_list(`debugger_endpoint_table`)").use { c -> + assertThat(c.count).isEqualTo(1) + c.moveToFirst() + assertThat(c.getString(c.getColumnIndexOrThrow("table"))).isEqualTo("recent_project_table") + assertThat(c.getString(c.getColumnIndexOrThrow("from"))).isEqualTo("project_location") + assertThat(c.getString(c.getColumnIndexOrThrow("to"))).isEqualTo("location") + assertThat(c.getString(c.getColumnIndexOrThrow("on_delete"))).isEqualTo("CASCADE") + } + db + .query( + "SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='debugger_endpoint_table' AND name='index_debugger_endpoint_table_project_location'", + ).use { c -> + assertThat(c.count).isEqualTo(1) + } + + runBlocking { + room.debuggerEndpointDao().upsertPairing("com.example.one", "/p/a") + room.debuggerEndpointDao().upsertPairing("com.example.two", "/p/b") + room.recentProjectDao().deleteByLocation("/p/a") + assertThat(room.debuggerEndpointDao().getByApplicationId("com.example.one")).isNull() + assertThat(room.debuggerEndpointDao().getByApplicationId("com.example.two")).isNotNull() + } + } finally { + room.close() + file.delete() + } + } + + @Test + fun `getDatabase registers the 5 to 6 migration`() { + assertThat(RecentProjectRoomDatabase.migrations.map { it.startVersion to it.endVersion }).contains(5 to 6) + assertThat(RecentProjectRoomDatabase.migrations).asList().contains(RecentProjectRoomDatabase.migration5To6) + } + + private fun newDatabase(): RecentProjectRoomDatabase = + Room + .inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext(), RecentProjectRoomDatabase::class.java) + .allowMainThreadQueries() + .build() + + private fun project(location: String) = RecentProject(name = location, createdAt = "1", location = location) + + @Test + fun `deleting a recent project deletes its endpoint rows`() = + runBlocking { + val room = newDatabase() + try { + room.recentProjectDao().insert(project("/p/a")) + room.recentProjectDao().insert(project("/p/b")) + val dao = room.debuggerEndpointDao() + dao.upsertPairing("com.example.one", "/p/a") + dao.upsertPairing("com.example.two", "/p/a") + dao.upsertPairing("com.example.three", "/p/b") + + room.recentProjectDao().deleteByLocation("/p/a") + + assertThat(dao.getByProjectLocation("/p/a")).isEmpty() + assertThat(dao.getByProjectLocation("/p/b").map { it.applicationId }).containsExactly("com.example.three") + } finally { + room.close() + } + } + + @Test + fun `renaming a recent project moves its endpoint rows`() = + runBlocking { + val room = newDatabase() + try { + room.recentProjectDao().insert(project("/p/a")) + val dao = room.debuggerEndpointDao() + dao.upsertPairing("com.example.one", "/p/a") + + room.recentProjectDao().updateNameAndLocation("/p/a", "renamed", "/p/renamed") + + assertThat(dao.getByProjectLocation("/p/renamed").map { it.applicationId }).containsExactly("com.example.one") + } finally { + room.close() + } + } + + @Test + fun `upsertPairing for a different project moves it and clears token, port and time`() = + runBlocking { + val room = newDatabase() + try { + room.recentProjectDao().insert(project("/p/a")) + room.recentProjectDao().insert(project("/p/b")) + val dao = room.debuggerEndpointDao() + dao.upsertPairing("com.example.one", "/p/a") + assertThat(dao.updateEndpoint("com.example.one", "tok", 4242, 99L)).isEqualTo(1) + + dao.upsertPairing("com.example.one", "/p/b") + + val row = dao.getByApplicationId("com.example.one") + assertThat(row).isEqualTo(DebuggerEndpoint("com.example.one", "/p/b", null, null, null)) + } finally { + room.close() + } + } + + @Test + fun `upsertPairing for the same project keeps token, port and time`() = + runBlocking { + val room = newDatabase() + try { + room.recentProjectDao().insert(project("/p/a")) + val dao = room.debuggerEndpointDao() + dao.upsertPairing("com.example.one", "/p/a") + dao.updateEndpoint("com.example.one", "tok", 4242, 99L) + + dao.upsertPairing("com.example.one", "/p/a") + + assertThat(dao.getByApplicationId("com.example.one")) + .isEqualTo(DebuggerEndpoint("com.example.one", "/p/a", "tok", 4242, 99L)) + } finally { + room.close() + } + } + + @Test + fun `updateEndpoint matches no row for an unknown application`() = + runBlocking { + val room = newDatabase() + try { + assertThat(room.debuggerEndpointDao().updateEndpoint("com.unknown", "tok", 1, 1L)).isEqualTo(0) + assertThat(room.debuggerEndpointDao().getByApplicationId("com.unknown")).isNull() + } finally { + room.close() + } + } + + @Test + fun `upsertPairing for a project that is not in recents is refused`() = + runBlocking { + val room = newDatabase() + try { + val result = runCatching { room.debuggerEndpointDao().upsertPairing("com.example.one", "/p/missing") } + assertThat(result.exceptionOrNull()).isInstanceOf(SQLiteConstraintException::class.java) + assertThat(room.debuggerEndpointDao().getByApplicationId("com.example.one")).isNull() + } finally { + room.close() + } + } + + @Test + fun `insertPairingIfAbsent leaves an existing pairing and its endpoint alone`() = + runBlocking { + val room = newDatabase() + try { + room.recentProjectDao().insert(project("/p/a")) + room.recentProjectDao().insert(project("/p/b")) + val dao = room.debuggerEndpointDao() + dao.upsertPairing("com.example.one", "/p/a") + dao.updateEndpoint("com.example.one", "tok", 4242, 99L) + + dao.insertPairingIfAbsent("com.example.one", "/p/b") + + assertThat(dao.getByApplicationId("com.example.one")) + .isEqualTo(DebuggerEndpoint("com.example.one", "/p/a", "tok", 4242, 99L)) + } finally { + room.close() + } + } } From 6adec66425ee61fddb1ddedaa95cb0c91f3d9f97 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 21:33:44 -0800 Subject: [PATCH 02/21] style: spotless reformat, no functional change LaunchAppAction.kt was indented with spaces; the next commit edits it, which pulls the whole file under the Spotless ratchet. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../androidide/actions/etc/LaunchAppAction.kt | 125 +++++++++--------- 1 file changed, 64 insertions(+), 61 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/actions/etc/LaunchAppAction.kt b/app/src/main/java/com/itsaky/androidide/actions/etc/LaunchAppAction.kt index a84e904b60..ed2286c056 100644 --- a/app/src/main/java/com/itsaky/androidide/actions/etc/LaunchAppAction.kt +++ b/app/src/main/java/com/itsaky/androidide/actions/etc/LaunchAppAction.kt @@ -37,67 +37,70 @@ import org.slf4j.LoggerFactory * * @author Akash Yadav */ -class LaunchAppAction(context: Context, override val order: Int) : EditorActivityAction() { - - override val id: String = "ide.editor.launchInstalledApp" - override var requiresUIThread: Boolean = true - override fun retrieveTooltipTag(isReadOnlyContext: Boolean) = EDITOR_TOOLBAR_LAUNCH_APP - - init { - label = context.getString(R.string.title_launch_app) - icon = ContextCompat.getDrawable(context, R.drawable.ic_open_external) - } - - companion object { - private val log = LoggerFactory.getLogger(LaunchAppAction::class.java) - } - - override fun prepare(data: ActionData) { - super.prepare(data) - data.getActivity() ?: run { - markInvisible() - return - } - - visible = true - - val projectManager = IProjectManager.getInstance() - enabled = projectManager.getAndroidAppModules().isNotEmpty() - } - - override suspend fun execAction(data: ActionData) { - openApplicationModuleChooser(data) { app -> - val variant = app.getSelectedVariant() - - log.debug("Selected variant: {}", variant?.name) - - if (variant == null) { - flashError(R.string.err_selected_variant_not_found) - return@openApplicationModuleChooser - } - - val applicationId = variant.mainArtifact.applicationId - if (applicationId == null) { - log.error("Unable to launch application. variant.mainArtifact.applicationId is null") - flashError(R.string.err_cannot_determine_package) - return@openApplicationModuleChooser - } - - log.info("Launching application: {}", applicationId) - - val activity = data.requireActivity() - activity.activityScope.launch { - IntentUtils.launchApp( +class LaunchAppAction( + context: Context, + override val order: Int, +) : EditorActivityAction() { + override val id: String = "ide.editor.launchInstalledApp" + override var requiresUIThread: Boolean = true + + override fun retrieveTooltipTag(isReadOnlyContext: Boolean) = EDITOR_TOOLBAR_LAUNCH_APP + + init { + label = context.getString(R.string.title_launch_app) + icon = ContextCompat.getDrawable(context, R.drawable.ic_open_external) + } + + companion object { + private val log = LoggerFactory.getLogger(LaunchAppAction::class.java) + } + + override fun prepare(data: ActionData) { + super.prepare(data) + data.getActivity() ?: run { + markInvisible() + return + } + + visible = true + + val projectManager = IProjectManager.getInstance() + enabled = projectManager.getAndroidAppModules().isNotEmpty() + } + + override suspend fun execAction(data: ActionData) { + openApplicationModuleChooser(data) { app -> + val variant = app.getSelectedVariant() + + log.debug("Selected variant: {}", variant?.name) + + if (variant == null) { + flashError(R.string.err_selected_variant_not_found) + return@openApplicationModuleChooser + } + + val applicationId = variant.mainArtifact.applicationId + if (applicationId == null) { + log.error("Unable to launch application. variant.mainArtifact.applicationId is null") + flashError(R.string.err_cannot_determine_package) + return@openApplicationModuleChooser + } + + log.info("Launching application: {}", applicationId) + + val activity = data.requireActivity() + activity.activityScope.launch { + IntentUtils.launchApp( context = activity, packageName = applicationId, - logError = false + logError = false, ) - } - } - } - - override fun getShowAsActionFlags(data: ActionData): Int { - // prefer showing this in the overflow menu - return MenuItem.SHOW_AS_ACTION_IF_ROOM - } -} \ No newline at end of file + } + } + } + + override fun getShowAsActionFlags(data: ActionData): Int { + // prefer showing this in the overflow menu + return MenuItem.SHOW_AS_ACTION_IF_ROOM + } +} From 4a97c773925df35b856ed9a6f06fecb0f6e859c0 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 21:33:44 -0800 Subject: [PATCH 03/21] ADFA-7137 Pair apps with projects and receive their debugger endpoint Code on the Go must know which project an app belongs to before it accepts that app's debugger token and port, otherwise any app could register an endpoint. - A project-started install records (application ID, project) once the install succeeds. An existing pairing moves to the new project and its stale token and port are cleared. LaunchAppAction only adds a pairing when the app has none, and waits for it before launching. The Activity is not captured in the pairing lambda. - DebuggerEndpointReceiver (exported, action com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT) stores the endpoint off the main thread. The token must be 1-128 URL-safe base64 characters and the port 1-65535. A broadcast from an unpaired app stores nothing. A database failure is logged, never thrown. - Sender identity: the app attaches an immutable PendingIntent, and the receiver trusts only its creatorPackage, which the framework sets and another app cannot forge, on every API level. A forged broadcast could otherwise point the AI Agent at another app's debugger server. Tests: DAO and repository (pairing rules, failures reported as false, move and clear on re-pairing); the receiver delivered through the framework under Robolectric (stored, unpaired app ignored, no PendingIntent ignored, malformed extras ignored); validation of token and port. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- app/src/main/AndroidManifest.xml | 12 + .../androidide/actions/etc/LaunchAppAction.kt | 12 + .../activities/editor/BaseEditorActivity.kt | 15 + .../editor/ProjectHandlerActivity.kt | 23 +- .../com/itsaky/androidide/di/AppModule.kt | 9 + .../DebuggerEndpointRepository.kt | 122 +++++++++ .../DebuggerEndpointReceiver.kt | 80 ++++++ .../DebuggerEndpointValidation.kt | 35 +++ .../DebuggerEndpointRepositoryTest.kt | 258 ++++++++++++++++++ .../DebuggerEndpointReceiverTest.kt | 156 +++++++++++ .../DebuggerEndpointValidationTest.kt | 61 +++++ 11 files changed, 782 insertions(+), 1 deletion(-) create mode 100644 app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt create mode 100644 app/src/main/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointReceiver.kt create mode 100644 app/src/main/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointValidation.kt create mode 100644 app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt create mode 100644 app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointReceiverTest.kt create mode 100644 app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointValidationTest.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 134ac9e1f1..f42ebf7b95 100755 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -360,6 +360,18 @@ + + + + + + + McpHttp -> McpProtocol -> DatabaseTools -> Debug - `engine/`: `DebugEngine` is what the server needs from the extension, `NativeDebugEngine` implements it over JNI, and `EventDecoder` turns the event buffer's bytes into `Event`s. - `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `get_events`. - `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. +- `EndpointBroadcast` runs once the server listens, on every process start (the port changes). It sends an explicit broadcast, action `com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT`, to `com.itsaky.androidide` with `FLAG_INCLUDE_STOPPED_PACKAGES`, carrying the token, the port and a `PendingIntent` that identifies the app. The `PendingIntent` is immutable (on API 23 and later; the flag does not exist before) and wraps an intent that is never sent: Code on the Go reads its `creatorPackage`, which the framework sets and another app cannot forge, as the app's package name. The library manifest declares `` for Code on the Go. A failure to send is logged and never thrown. +- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. The row is deleted with its project (foreign key, ON DELETE CASCADE). ### The event record @@ -48,7 +50,6 @@ No workflow in `.github/workflows` runs either yet. ## Not done yet -- Broadcasting the port and token to Code on the Go (ADFA-7137). `DebuggerStartup` only keeps them in `DebuggerStartup.port` and `endpointToken` and logs the port, never the token. - Gradle plugin wiring and the build-time rewrite that adds the library to debug builds (ADFA-7138). - The AI-Agent-MCP side that connects to the server (ADFA-7139). - Verification on a device. The C tests run on the host and the Kotlin tests on the JVM; nothing has run in an app on a device or emulator. From 2b759e60eb844d6774ff7cc0a9db4b517e96ba7a Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 23:08:56 -0800 Subject: [PATCH 06/21] ADFA-7137 Clear pending installs on failure and pin the endpoint broadcast contract A failed or cancelled install left its pendingInstalls entry behind, so a later install of the same applicationId from an APK file was paired with the wrong project. The editor now tells the repository when an install ends without a launch, and entries older than five minutes are ignored as a backstop. Tests: a discarded note is not used, an expired note is not used, a recent note still pairs (the first two fail with the discard and the expiry removed). The broadcast extra names are consts in the library, and EndpointBroadcastTest (Robolectric) checks the sent action, package, extras and creatorPackage. The library is not on :app's classpath, so DebuggerEndpointContractTest in :app pins the same literals; each test names the other. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../activities/editor/BaseEditorActivity.kt | 14 +++- .../editor/ProjectHandlerActivity.kt | 4 + .../DebuggerEndpointRepository.kt | 25 +++++- .../DebuggerEndpointRepositoryTest.kt | 82 +++++++++++++++++++ .../DebuggerEndpointContractTest.kt | 19 +++++ subprojects/sqlite-debugger/build.gradle.kts | 6 ++ .../sqlitedebugger/EndpointBroadcast.kt | 10 ++- .../sqlitedebugger/EndpointBroadcastTest.kt | 43 ++++++++++ 8 files changed, 196 insertions(+), 7 deletions(-) create mode 100644 app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointContractTest.kt create mode 100644 subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/EndpointBroadcastTest.kt diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/BaseEditorActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/BaseEditorActivity.kt index c0ab3ee687..5fd7e0accd 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/BaseEditorActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/BaseEditorActivity.kt @@ -20,6 +20,7 @@ package com.itsaky.androidide.activities.editor import android.content.ComponentName import android.content.Intent import android.content.ServiceConnection +import android.content.pm.PackageInstaller import android.content.res.Configuration import android.graphics.Color import android.graphics.Rect @@ -755,7 +756,15 @@ abstract class BaseEditorActivity : return } - val packageName = onResult(this, intent) ?: return + val packageName = onResult(this, intent) + if (packageName == null) { + val extras = intent.extras + val installed = extras?.getString(PackageInstaller.EXTRA_PACKAGE_NAME) + if (installed != null && extras.getInt(PackageInstaller.EXTRA_STATUS) != PackageInstaller.STATUS_PENDING_USER_ACTION) { + onInstallEndedWithoutLaunch(installed) + } + return + } // Runs before the launch so the app's first report finds its pairing row. activityScope.launch(Dispatchers.Main.immediate) { beforePostInstallLaunch(packageName) @@ -763,6 +772,9 @@ abstract class BaseEditorActivity : } } + /** Called on the main thread when an install of [packageName] ended and no post-install launch follows (failed, cancelled, or suppressed). */ + protected open fun onInstallEndedWithoutLaunch(packageName: String) {} + /** Called on the main thread after an install succeeded, before the app is launched. Must not throw. */ protected open suspend fun beforePostInstallLaunch(packageName: String) {} diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt index 4568401fde..2c728c3504 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt @@ -737,6 +737,10 @@ abstract class ProjectHandlerActivity : debuggerEndpointRepository.confirmInstall(packageName) } + override fun onInstallEndedWithoutLaunch(packageName: String) { + debuggerEndpointRepository.discardPendingInstall(packageName) + } + private fun doInstallApk(state: BuildState.AwaitingInstall) { val projectDirPath = IProjectManager.getInstance().projectDirPath if (projectDirPath.isNotBlank()) { diff --git a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt index 642f5d5804..ea7ff37729 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt @@ -23,8 +23,13 @@ class DebuggerEndpointRepository( private val scope: CoroutineScope, private val clock: () -> Long = System::currentTimeMillis, ) { + private class PendingInstall( + val location: String, + val noteTimeMillis: Long, + ) + /** Installs expected to finish, by applicationId, with the project location that built them. */ - private val pendingInstalls = ConcurrentHashMap() + private val pendingInstalls = ConcurrentHashMap() /** * Notes, off the main thread, that [projectDir] is installing the app [applicationId] returns @@ -37,7 +42,7 @@ class DebuggerEndpointRepository( scope.launch { try { val id = runCatching(applicationId).getOrNull()?.takeIf { it.isNotBlank() } ?: return@launch - pendingInstalls[id] = projectDir.canonicalProjectLocation() + pendingInstalls[id] = PendingInstall(projectDir.canonicalProjectLocation(), clock()) } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -52,8 +57,19 @@ class DebuggerEndpointRepository( * some other way, such as opening an APK file, is not paired. */ suspend fun confirmInstall(applicationId: String): Boolean { - val location = pendingInstalls.remove(applicationId) ?: return false - return recordInstalled(applicationId, location) + val pending = pendingInstalls.remove(applicationId) ?: return false + // A note this old belongs to an install that never reported a result. + if (clock() - pending.noteTimeMillis > PENDING_INSTALL_MAX_AGE_MILLIS) return false + return recordInstalled(applicationId, pending.location) + } + + /** + * Call when the install of [applicationId] ended without success (failed, cancelled, blocked), so + * a later install of the same app from elsewhere, such as an APK file, is not paired with the + * project that started this one. + */ + fun discardPendingInstall(applicationId: String) { + pendingInstalls.remove(applicationId) } /** @@ -117,6 +133,7 @@ class DebuggerEndpointRepository( } private companion object { + private const val PENDING_INSTALL_MAX_AGE_MILLIS = 5 * 60 * 1000L private val log = LoggerFactory.getLogger(DebuggerEndpointRepository::class.java) } } diff --git a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt index 6e1d4fea38..b0e6d0c6fb 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt @@ -17,6 +17,7 @@ import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import java.io.File +import java.util.concurrent.atomic.AtomicLong /** The database path DebuggerEndpointReceiver and the install/launch hooks call. */ @RunWith(RobolectricTestRunner::class) @@ -161,6 +162,87 @@ class DebuggerEndpointRepositoryTest { } } + private suspend fun awaitNoted( + repo: DebuggerEndpointRepository, + id: String, + dir: File, + discard: Boolean, + advanceMillis: Long, + now: AtomicLong, + ): Boolean { + repo.expectInstallAsync(dir) { id } + Thread.sleep(300) + if (discard) repo.discardPendingInstall(id) + now.addAndGet(advanceMillis) + return repo.confirmInstall(id) + } + + private fun clockedRepository(now: AtomicLong) = + DebuggerEndpointRepository(room.debuggerEndpointDao(), CoroutineScope(Dispatchers.IO), clock = { now.get() }) + + @Test + fun `a failed install does not pair a later install of the same app`() = + runBlocking { + val dir = + File.createTempFile("proj", "").apply { + delete() + mkdirs() + } + try { + addProject(dir.canonicalPath) + val now = AtomicLong(1_000L) + + val paired = awaitNoted(clockedRepository(now), "com.example", dir, discard = true, advanceMillis = 0, now = now) + + assertThat(paired).isFalse() + assertThat(room.debuggerEndpointDao().getByApplicationId("com.example")).isNull() + } finally { + dir.delete() + } + } + + @Test + fun `a note older than the expiry is not used`() = + runBlocking { + val dir = + File.createTempFile("proj", "").apply { + delete() + mkdirs() + } + try { + addProject(dir.canonicalPath) + val now = AtomicLong(1_000L) + + val sixMinutes = 6 * 60 * 1000L + val paired = awaitNoted(clockedRepository(now), "com.example", dir, discard = false, advanceMillis = sixMinutes, now = now) + + assertThat(paired).isFalse() + assertThat(room.debuggerEndpointDao().getByApplicationId("com.example")).isNull() + } finally { + dir.delete() + } + } + + @Test + fun `a recent note still pairs on success`() = + runBlocking { + val dir = + File.createTempFile("proj", "").apply { + delete() + mkdirs() + } + try { + addProject(dir.canonicalPath) + val now = AtomicLong(1_000L) + + val paired = awaitNoted(clockedRepository(now), "com.example", dir, discard = false, advanceMillis = 60_000L, now = now) + + assertThat(paired).isTrue() + } finally { + dir.delete() + } + } + @Test fun `launching pairs an unpaired app`() = runBlocking { diff --git a/app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointContractTest.kt b/app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointContractTest.kt new file mode 100644 index 0000000000..01eb97d605 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointContractTest.kt @@ -0,0 +1,19 @@ +package com.itsaky.androidide.sqlitedebugger + +import com.google.common.truth.Truth.assertThat +import org.junit.Test + +/** + * The library (:subprojects:sqlite-debugger) cannot share these constants and is not on this module's + * classpath, so each side pins the same literals: EndpointBroadcastTest in the library checks the sender + * against them. Change both together. + */ +class DebuggerEndpointContractTest { + @Test + fun `the broadcast names match what the library sends`() { + assertThat(DebuggerEndpointValidation.ACTION).isEqualTo("com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT") + assertThat(DebuggerEndpointValidation.EXTRA_TOKEN).isEqualTo("token") + assertThat(DebuggerEndpointValidation.EXTRA_PORT).isEqualTo("port") + assertThat(DebuggerEndpointValidation.EXTRA_SENDER).isEqualTo("sender") + } +} diff --git a/subprojects/sqlite-debugger/build.gradle.kts b/subprojects/sqlite-debugger/build.gradle.kts index 2acf1dd65c..941d63d06f 100644 --- a/subprojects/sqlite-debugger/build.gradle.kts +++ b/subprojects/sqlite-debugger/build.gradle.kts @@ -32,6 +32,10 @@ android { targetCompatibility = JavaVersion.VERSION_1_8 } + testOptions { + unitTests.isIncludeAndroidResources = true + } + buildFeatures { viewBinding = false buildConfig = false @@ -65,4 +69,6 @@ dependencies { testImplementation(libs.org.json) testImplementation(libs.tests.junit) testImplementation(libs.tests.google.truth) + testImplementation(libs.tests.robolectric) + testImplementation(libs.tests.androidx.test.core) } diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/EndpointBroadcast.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/EndpointBroadcast.kt index 846b128f57..2476e05b76 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/EndpointBroadcast.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/EndpointBroadcast.kt @@ -9,8 +9,14 @@ import android.util.Log /** Tells Code on the Go which port and token this process's server uses (ADFA-7137). */ internal object EndpointBroadcast { private const val TAG = "SqliteDebugger" + + // ACTION, EXTRA_TOKEN, EXTRA_PORT and EXTRA_SENDER repeat the constants of the same names in Code on the + // Go's DebuggerEndpointValidation (:app), which this library cannot depend on. EndpointBroadcastTest here + // and DebuggerEndpointContractTest there pin the same values. const val ACTION = "com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT" const val COGO_PACKAGE = "com.itsaky.androidide" + const val EXTRA_TOKEN = "token" + const val EXTRA_PORT = "port" const val EXTRA_SENDER = "sender" private const val IDENTITY_ACTION = "org.appdevforall.sqlitedebugger.IDENTITY" @@ -35,8 +41,8 @@ internal object EndpointBroadcast { Intent(ACTION) .setPackage(COGO_PACKAGE) .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES or Intent.FLAG_RECEIVER_FOREGROUND) - .putExtra("token", token) - .putExtra("port", port) + .putExtra(EXTRA_TOKEN, token) + .putExtra(EXTRA_PORT, port) .putExtra(EXTRA_SENDER, sender) context.sendBroadcast(intent) } catch (e: Exception) { diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/EndpointBroadcastTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/EndpointBroadcastTest.kt new file mode 100644 index 0000000000..b710370816 --- /dev/null +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/EndpointBroadcastTest.kt @@ -0,0 +1,43 @@ +package org.appdevforall.sqlitedebugger + +import android.app.Application +import android.app.PendingIntent +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf + +/** + * The literals below are Code on the Go's contract: the same values are pinned by + * DebuggerEndpointContractTest in :app (DebuggerEndpointValidation). Change both together. + */ +@RunWith(RobolectricTestRunner::class) +class EndpointBroadcastTest { + @Test + fun `the constants match the receiver in Code on the Go`() { + assertThat(EndpointBroadcast.ACTION).isEqualTo("com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT") + assertThat(EndpointBroadcast.COGO_PACKAGE).isEqualTo("com.itsaky.androidide") + assertThat(EndpointBroadcast.EXTRA_TOKEN).isEqualTo("token") + assertThat(EndpointBroadcast.EXTRA_PORT).isEqualTo("port") + assertThat(EndpointBroadcast.EXTRA_SENDER).isEqualTo("sender") + } + + @Test + fun `send broadcasts the endpoint to Code on the Go with the sender identity`() { + val app = ApplicationProvider.getApplicationContext() + + EndpointBroadcast.send(app, "tok-en_1", 5555) + + val intent = shadowOf(app).broadcastIntents.single() + assertThat(intent.action).isEqualTo("com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT") + assertThat(intent.`package`).isEqualTo("com.itsaky.androidide") + assertThat(intent.getStringExtra("token")).isEqualTo("tok-en_1") + assertThat(intent.getIntExtra("port", 0)).isEqualTo(5555) + @Suppress("DEPRECATION") + val sender = intent.getParcelableExtra("sender") + assertThat(sender).isNotNull() + assertThat(sender!!.creatorPackage).isEqualTo(app.packageName) + } +} From 1d12027d357461ddbec9f478009382958a2b52b1 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 18:42:59 -0800 Subject: [PATCH 07/21] ADFA-7137 Re-send the endpoint when Code on the Go asks An app's SQLite debugger reported its endpoint only once, when its server started, and Code on the Go drops a report from an app it has not paired. An app already running when Code on the Go paired it (installed from an APK file, installed before this feature, or started before its project was opened) stayed unknown until its process restarted. The library now registers a receiver at run time for org.appdevforall.sqlitedebugger.ANNOUNCE before its first send, and sends the same token and port again on each request. It is registered only once the server listens, after the debuggable check, and is not in the manifest, so a request never starts an app that is not running. Exported (RECEIVER_EXPORTED on API 33+) and unauthenticated, per ADFA-7131 D8: the reply goes only to Code on the Go. DebuggerEndpointRepository asks the app (DebuggerEndpointAnnounce, an explicit broadcast to the app's package) after every pairing that was written, by recordLaunched or recordInstalled. The announce callback is a required constructor argument, so a forgotten wiring is a compile error. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../com/itsaky/androidide/di/AppModule.kt | 8 ++- .../DebuggerEndpointRepository.kt | 18 +++++-- .../DebuggerEndpointAnnounce.kt | 31 +++++++++++ .../DebuggerEndpointRepositoryTest.kt | 53 +++++++++++++++++-- .../DebuggerEndpointAnnounceTest.kt | 25 +++++++++ .../DebuggerEndpointContractTest.kt | 3 +- .../DebuggerEndpointReceiverTest.kt | 2 +- subprojects/sqlite-debugger/README.md | 6 +-- .../sqlitedebugger/DebuggerStartup.kt | 2 +- .../sqlitedebugger/EndpointBroadcast.kt | 51 ++++++++++++++++++ .../sqlitedebugger/EndpointBroadcastTest.kt | 26 +++++++++ 11 files changed, 210 insertions(+), 15 deletions(-) create mode 100644 app/src/main/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointAnnounce.kt create mode 100644 app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointAnnounceTest.kt diff --git a/app/src/main/java/com/itsaky/androidide/di/AppModule.kt b/app/src/main/java/com/itsaky/androidide/di/AppModule.kt index eb3bc46704..194847f4eb 100644 --- a/app/src/main/java/com/itsaky/androidide/di/AppModule.kt +++ b/app/src/main/java/com/itsaky/androidide/di/AppModule.kt @@ -11,6 +11,7 @@ import com.itsaky.androidide.repositories.DebuggerEndpointRepository import com.itsaky.androidide.repositories.RecentProjectRepository import com.itsaky.androidide.repositories.RecentProjectRepositoryImpl import com.itsaky.androidide.roomData.recentproject.RecentProjectRoomDatabase +import com.itsaky.androidide.sqlitedebugger.DebuggerEndpointAnnounce import com.itsaky.androidide.viewmodel.CloneRepositoryViewModel import com.itsaky.androidide.viewmodel.GitBottomSheetViewModel import com.itsaky.androidide.viewmodel.MainViewModel @@ -63,7 +64,12 @@ val coreModule = } single { - DebuggerEndpointRepository(get(), get(named(APPLICATION_SCOPE))) + val context = androidContext() + DebuggerEndpointRepository( + get(), + get(named(APPLICATION_SCOPE)), + announce = { DebuggerEndpointAnnounce.send(context, it) }, + ) } single { diff --git a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt index ea7ff37729..98033c815b 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt @@ -22,6 +22,11 @@ class DebuggerEndpointRepository( private val dao: DebuggerEndpointDao, private val scope: CoroutineScope, private val clock: () -> Long = System::currentTimeMillis, + /** + * Asks the app to report its endpoint again, after each pairing; see DebuggerEndpointAnnounce. Required, with no + * default: one that did nothing would leave an app that was already running unknown until its process restarts. + */ + private val announce: (applicationId: String) -> Unit, ) { private class PendingInstall( val location: String, @@ -73,17 +78,20 @@ class DebuggerEndpointRepository( } /** - * Moves [applicationId] to [projectLocation], clearing its token and port if the project changed. - * Returns false when the project has no recent_project_table row yet, or the write failed. + * Moves [applicationId] to [projectLocation], clearing its token and port if the project changed, then asks the + * app to report again. Returns false when the project has no recent_project_table row yet, or the write failed. */ suspend fun recordInstalled( applicationId: String, projectLocation: String, - ): Boolean = guarded("pair $applicationId with project $projectLocation") { dao.upsertPairing(applicationId, projectLocation) } + ): Boolean = + guarded("pair $applicationId with project $projectLocation") { dao.upsertPairing(applicationId, projectLocation) } + .also { if (it) announce(applicationId) } /** * Pairs [applicationId] with the project at [projectDir] only if it has no pairing; an existing - * one, with its token and port, is left alone because launching restarts nothing. + * one, with its token and port, is left alone because launching restarts nothing. Either way the + * app is then asked to report again, which an app that was already running needs. */ suspend fun recordLaunched( applicationId: String, @@ -99,7 +107,7 @@ class DebuggerEndpointRepository( ): Boolean = guarded("pair launched $applicationId with project $projectLocation") { dao.insertPairingIfAbsent(applicationId, projectLocation) - } + }.also { if (it) announce(applicationId) } /** Returns true when [applicationId] has a pairing and its token and port were stored. */ suspend fun storeEndpoint( diff --git a/app/src/main/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointAnnounce.kt b/app/src/main/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointAnnounce.kt new file mode 100644 index 0000000000..f284178e6d --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointAnnounce.kt @@ -0,0 +1,31 @@ +package com.itsaky.androidide.sqlitedebugger + +import android.content.Context +import android.content.Intent +import org.slf4j.LoggerFactory + +/** + * Asks a paired app's SQLite debugger to report its endpoint again (ADFA-7137). The app reports once, when its + * server starts, and [DebuggerEndpointReceiver] drops a report from an app with no pairing row, so an app that was + * already running when Code on the Go paired it would otherwise stay unknown until its process restarts. An app + * that is not running gets nothing and starts nothing: the library listens only while its server runs, and reports + * when it starts. + */ +object DebuggerEndpointAnnounce { + /** Repeats the library's EndpointBroadcast.ANNOUNCE_ACTION; DebuggerEndpointContractTest pins it. */ + const val ACTION = "org.appdevforall.sqlitedebugger.ANNOUNCE" + + private val log = LoggerFactory.getLogger(DebuggerEndpointAnnounce::class.java) + + /** Never throws: pairing goes ahead whether or not the app is there to hear this. */ + fun send( + context: Context, + applicationId: String, + ) { + try { + context.sendBroadcast(Intent(ACTION).setPackage(applicationId)) + } catch (e: Exception) { + log.warn("Could not ask {} to report its SQLite debugger endpoint", applicationId, e) + } + } +} diff --git a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt index b0e6d0c6fb..ee4565837b 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt @@ -17,6 +17,7 @@ import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import java.io.File +import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.atomic.AtomicLong /** The database path DebuggerEndpointReceiver and the install/launch hooks call. */ @@ -25,6 +26,9 @@ class DebuggerEndpointRepositoryTest { private lateinit var room: RecentProjectRoomDatabase private lateinit var repository: DebuggerEndpointRepository + /** The application IDs the repository asked to report again, in order. */ + private val announced = CopyOnWriteArrayList() + @Before fun setUp() { room = @@ -32,7 +36,13 @@ class DebuggerEndpointRepositoryTest { .inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext(), RecentProjectRoomDatabase::class.java) .allowMainThreadQueries() .build() - repository = DebuggerEndpointRepository(room.debuggerEndpointDao(), CoroutineScope(Dispatchers.IO), clock = { 1234L }) + repository = + DebuggerEndpointRepository( + room.debuggerEndpointDao(), + CoroutineScope(Dispatchers.IO), + clock = { 1234L }, + announce = { announced += it }, + ) } @After @@ -178,7 +188,12 @@ class DebuggerEndpointRepositoryTest { } private fun clockedRepository(now: AtomicLong) = - DebuggerEndpointRepository(room.debuggerEndpointDao(), CoroutineScope(Dispatchers.IO), clock = { now.get() }) + DebuggerEndpointRepository( + room.debuggerEndpointDao(), + CoroutineScope(Dispatchers.IO), + clock = { now.get() }, + announce = { announced += it }, + ) @Test fun `a failed install does not pair a later install of the same app`() = @@ -269,6 +284,35 @@ class DebuggerEndpointRepositoryTest { assertThat(row.port).isEqualTo(5555) } + @Test + fun `pairing on launch asks the app to report its endpoint again`() = + runBlocking { + addProject("/p/a") + + repository.recordLaunched("com.example", "/p/a") + + assertThat(announced).containsExactly("com.example") + } + + @Test + fun `pairing on install asks the app to report its endpoint again`() = + runBlocking { + addProject("/p/a") + + repository.recordInstalled("com.example", "/p/a") + + assertThat(announced).containsExactly("com.example") + } + + @Test + fun `a pairing that was not written asks nothing`() = + runBlocking { + repository.recordLaunched("com.example", "/p/missing") + repository.recordInstalled("com.example", "/p/missing") + + assertThat(announced).isEmpty() + } + @Test fun `launching a project that is not in recents is skipped without throwing`() = runBlocking { @@ -317,12 +361,14 @@ class DebuggerEndpointRepositoryTest { { IllegalStateException("closed") }, { android.database.SQLException("generic") }, )) { - val failing = DebuggerEndpointRepository(ThrowingDao(error), CoroutineScope(Dispatchers.IO)) + val failing = + DebuggerEndpointRepository(ThrowingDao(error), CoroutineScope(Dispatchers.IO), announce = { announced += it }) assertThat(failing.recordInstalled("com.example", "/p/a")).isFalse() assertThat(failing.recordLaunched("com.example", "/p/a")).isFalse() assertThat(failing.storeEndpoint("com.example", endpoint)).isFalse() } + assertThat(announced).isEmpty() } @Test @@ -331,6 +377,7 @@ class DebuggerEndpointRepositoryTest { DebuggerEndpointRepository( ThrowingDao { kotlinx.coroutines.CancellationException("cancelled") }, CoroutineScope(Dispatchers.IO), + announce = {}, ) val result = runCatching { runBlocking { failing.storeEndpoint("com.example", endpoint) } } diff --git a/app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointAnnounceTest.kt b/app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointAnnounceTest.kt new file mode 100644 index 0000000000..1cf9ce9fbd --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointAnnounceTest.kt @@ -0,0 +1,25 @@ +package com.itsaky.androidide.sqlitedebugger + +import android.app.Application +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], application = Application::class) +class DebuggerEndpointAnnounceTest { + @Test + fun `the request goes only to the paired app`() { + val app = ApplicationProvider.getApplicationContext() + + DebuggerEndpointAnnounce.send(app, "com.example") + + val intent = shadowOf(app).broadcastIntents.single() + assertThat(intent.action).isEqualTo("org.appdevforall.sqlitedebugger.ANNOUNCE") + assertThat(intent.`package`).isEqualTo("com.example") + } +} diff --git a/app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointContractTest.kt b/app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointContractTest.kt index 01eb97d605..038dc3197e 100644 --- a/app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointContractTest.kt +++ b/app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointContractTest.kt @@ -10,10 +10,11 @@ import org.junit.Test */ class DebuggerEndpointContractTest { @Test - fun `the broadcast names match what the library sends`() { + fun `the broadcast names match what the library sends and listens for`() { assertThat(DebuggerEndpointValidation.ACTION).isEqualTo("com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT") assertThat(DebuggerEndpointValidation.EXTRA_TOKEN).isEqualTo("token") assertThat(DebuggerEndpointValidation.EXTRA_PORT).isEqualTo("port") assertThat(DebuggerEndpointValidation.EXTRA_SENDER).isEqualTo("sender") + assertThat(DebuggerEndpointAnnounce.ACTION).isEqualTo("org.appdevforall.sqlitedebugger.ANNOUNCE") } } diff --git a/app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointReceiverTest.kt b/app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointReceiverTest.kt index 8a251767e9..32a5abd3fd 100644 --- a/app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointReceiverTest.kt +++ b/app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointReceiverTest.kt @@ -42,7 +42,7 @@ class DebuggerEndpointReceiverTest { .allowMainThreadQueries() .build() val scope = CoroutineScope(Dispatchers.IO) - val repository = DebuggerEndpointRepository(room.debuggerEndpointDao(), scope, clock = { 99L }) + val repository = DebuggerEndpointRepository(room.debuggerEndpointDao(), scope, clock = { 99L }, announce = {}) if (GlobalContext.getOrNull() != null) stopKoin() startKoin { modules( diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index d7a978e476..c0ab2e3864 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -22,8 +22,8 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `engine/`: `DebugEngine` is what the server needs from the extension, `NativeDebugEngine` implements it over JNI, and `EventDecoder` turns the event buffer's bytes into `Event`s. - `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `get_events`. - `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. -- `EndpointBroadcast` runs once the server listens, on every process start (the port changes). It sends an explicit broadcast, action `com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT`, to `com.itsaky.androidide` with `FLAG_INCLUDE_STOPPED_PACKAGES`, carrying the token, the port and a `PendingIntent` that identifies the app. The `PendingIntent` is immutable (on API 23 and later; the flag does not exist before) and wraps an intent that is never sent: Code on the Go reads its `creatorPackage`, which the framework sets and another app cannot forge, as the app's package name. The library manifest declares `` for Code on the Go. A failure to send is logged and never thrown. -- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. The row is deleted with its project (foreign key, ON DELETE CASCADE). +- `EndpointBroadcast` runs once the server listens, on every process start (the port changes). It sends an explicit broadcast, action `com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT`, to `com.itsaky.androidide` with `FLAG_INCLUDE_STOPPED_PACKAGES`, carrying the token, the port and a `PendingIntent` that identifies the app. The `PendingIntent` is immutable (on API 23 and later; the flag does not exist before) and wraps an intent that is never sent: Code on the Go reads its `creatorPackage`, which the framework sets and another app cannot forge, as the app's package name. The library manifest declares `` for Code on the Go. A failure to send is logged and never thrown. Before the first send it registers a receiver at run time for `org.appdevforall.sqlitedebugger.ANNOUNCE` (exported, as Code on the Go is another app; `RECEIVER_EXPORTED` on API 33 and later), and sends the same token and port again each time it receives one. Code on the Go sends that request when it pairs the app, because it drops a report from an app it has not paired: an app that was already running then, installed some other way or started before its project was opened, would otherwise stay unknown until its process restarted. The receiver is not in the manifest, so a request never starts an app that is not running, and is not authenticated (ADFA-7131 D8): the reply goes only to Code on the Go. +- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). ### The event record @@ -45,7 +45,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Host C tests of the extension:** `subprojects/sqlite-debugger/test.sh [--update-fixture] [AMALGAMATION_TARBALL]`. It builds SQLite 3.49.1 from the amalgamation as requery builds it (`SQLITE_THREADSAFE=2`), checks its headers against `sqlite-js/upstream/libs`, and runs `src/test/c/sqlitedbg_test.c` under AddressSanitizer with UBSan, then under ThreadSanitizer. It needs gcc, curl, tar and sha256sum, and downloads the tarball unless you pass one. - **The fixture:** `src/test/resources/.../engine/events.bin` and `events.tsv` are written by the C test and read by `EventDecoderTest`. Without `--update-fixture`, `test.sh` checks the committed pair against the current record layout, so a layout change fails until you regenerate it and update `EventDecoder.kt`. - **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. -- **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp` and `DatabaseTools` (with `FakeDebugEngine`). +- **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp`, `DatabaseTools` (with `FakeDebugEngine`) and `EndpointBroadcast`, its announce receiver included. `.github/workflows/test-sqlite-debugger.yml` runs `test.sh` (the C and JNI tests) on pull requests that touch the module or the SQLite headers. No workflow runs the JVM tests. diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt index f04fb26fe7..8779b35a39 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt @@ -60,7 +60,7 @@ class DebuggerStartup : ContentProvider() { port = http.boundPort endpointToken = token Log.i(TAG, "listening on 127.0.0.1:${http.boundPort}") - EndpointBroadcast.send(context, token, http.boundPort) + EndpointBroadcast.sendAndListen(context, token, http.boundPort) } override fun query( diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/EndpointBroadcast.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/EndpointBroadcast.kt index 2476e05b76..2dc8dff2e0 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/EndpointBroadcast.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/EndpointBroadcast.kt @@ -1,8 +1,10 @@ package org.appdevforall.sqlitedebugger import android.app.PendingIntent +import android.content.BroadcastReceiver import android.content.Context import android.content.Intent +import android.content.IntentFilter import android.os.Build import android.util.Log @@ -18,8 +20,57 @@ internal object EndpointBroadcast { const val EXTRA_TOKEN = "token" const val EXTRA_PORT = "port" const val EXTRA_SENDER = "sender" + + // Code on the Go sends this when it pairs the app; its DebuggerEndpointAnnounce (:app) repeats the value, and + // the same two tests pin it. + const val ANNOUNCE_ACTION = "org.appdevforall.sqlitedebugger.ANNOUNCE" private const val IDENTITY_ACTION = "org.appdevforall.sqlitedebugger.IDENTITY" + /** + * Sends the endpoint now, and again each time Code on the Go asks with [ANNOUNCE_ACTION]. Code on the Go drops + * a report from an app it has not paired, so an app already running when it pairs would otherwise stay unknown + * to it until the process restarts. Listens first, so a request that arrives before the first send is not lost. + */ + fun sendAndListen( + context: Context, + token: String, + port: Int, + ) { + listen(context, token, port) + send(context, token, port) + } + + /** + * Registered at run time, not in the manifest, so it lives as long as this process's server and a request never + * starts the app. Exported, because Code on the Go is another app, and not authenticated (ADFA-7131 D8): the + * reply goes only to Code on the Go, so a request from any other app learns nothing. Never throws. + */ + private fun listen( + context: Context, + token: String, + port: Int, + ) { + try { + val receiver = + object : BroadcastReceiver() { + override fun onReceive( + context: Context, + intent: Intent, + ) { + if (intent.action == ANNOUNCE_ACTION) send(context, token, port) + } + } + val filter = IntentFilter(ANNOUNCE_ACTION) + if (Build.VERSION.SDK_INT >= 33) { + context.registerReceiver(receiver, filter, Context.RECEIVER_EXPORTED) + } else { + context.registerReceiver(receiver, filter) + } + } catch (e: Exception) { + Log.w(TAG, "could not listen for Code on the Go's requests to send the endpoint again", e) + } + } + /** Never throws: the app must run whether or not Code on the Go is there to hear this. */ fun send( context: Context, diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/EndpointBroadcastTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/EndpointBroadcastTest.kt index b710370816..e62f973594 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/EndpointBroadcastTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/EndpointBroadcastTest.kt @@ -2,12 +2,15 @@ package org.appdevforall.sqlitedebugger import android.app.Application import android.app.PendingIntent +import android.content.Intent +import android.os.Looper import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config /** * The literals below are Code on the Go's contract: the same values are pinned by @@ -22,6 +25,7 @@ class EndpointBroadcastTest { assertThat(EndpointBroadcast.EXTRA_TOKEN).isEqualTo("token") assertThat(EndpointBroadcast.EXTRA_PORT).isEqualTo("port") assertThat(EndpointBroadcast.EXTRA_SENDER).isEqualTo("sender") + assertThat(EndpointBroadcast.ANNOUNCE_ACTION).isEqualTo("org.appdevforall.sqlitedebugger.ANNOUNCE") } @Test @@ -40,4 +44,26 @@ class EndpointBroadcastTest { assertThat(sender).isNotNull() assertThat(sender!!.creatorPackage).isEqualTo(app.packageName) } + + // 28 and 33 run both registerReceiver calls: RECEIVER_EXPORTED exists from 33. + @Test + @Config(sdk = [28, 33]) + fun `an announce request sends the endpoint again with the same token and port`() { + val app = ApplicationProvider.getApplicationContext() + EndpointBroadcast.sendAndListen(app, "tok-en_1", 5555) + assertThat(endpointBroadcasts(app)).hasSize(1) + + app.sendBroadcast(Intent("org.appdevforall.sqlitedebugger.ANNOUNCE").setPackage(app.packageName)) + shadowOf(Looper.getMainLooper()).idle() + + val sent = endpointBroadcasts(app) + assertThat(sent).hasSize(2) + val again = sent.last() + assertThat(again.`package`).isEqualTo("com.itsaky.androidide") + assertThat(again.getStringExtra("token")).isEqualTo("tok-en_1") + assertThat(again.getIntExtra("port", 0)).isEqualTo(5555) + } + + private fun endpointBroadcasts(app: Application) = + shadowOf(app).broadcastIntents.filter { it.action == "com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT" } } From 6d8c81c58eec7f5e0a5c2e232bc897dc4c983c32 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 18:27:18 -0800 Subject: [PATCH 08/21] ADFA-7137 Pair a slow install with the open project at launch confirmInstall dropped the pending-install note after 5 minutes, and the post-install launch never called recordLaunched. A user who left the system install prompt (or the unknown-sources detour) open longer got an unpaired app, and Code on the Go dropped its endpoint broadcast. When the note is missing or expired, confirmInstall now pairs the app as recordLaunched does, with the open project, before the launch. ProjectHandlerActivity passes the open project only when one of its app modules' selected variant builds the installed application ID, as LaunchAppAction pairs a launch, so an unrelated APK installed from a file is still not paired. The expiry stays: an old note, possibly from a project that is no longer open, never moves a pairing, and recordLaunched never moves one either. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../editor/ProjectHandlerActivity.kt | 20 ++++++- .../DebuggerEndpointRepository.kt | 24 +++++--- .../DebuggerEndpointRepositoryTest.kt | 59 +++++++++++++++++-- subprojects/sqlite-debugger/README.md | 2 +- 4 files changed, 91 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt index 2c728c3504..a244ff0432 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt @@ -734,9 +734,27 @@ abstract class ProjectHandlerActivity : ?.takeIf { it.isNotBlank() } override suspend fun beforePostInstallLaunch(packageName: String) { - debuggerEndpointRepository.confirmInstall(packageName) + debuggerEndpointRepository.confirmInstall(packageName, openProjectDirBuilding(packageName)) } + /** + * The open project's directory when one of its app modules builds [applicationId], as LaunchAppAction pairs a + * launch, else null. Never throws: [beforePostInstallLaunch] must not. + */ + private fun openProjectDirBuilding(applicationId: String): File? = + try { + val projectManager = IProjectManager.getInstance() + val projectDirPath = projectManager.projectDirPath + val builds = + projectManager.getAndroidAppModules().any { module -> + module.getSelectedVariant()?.mainArtifact?.applicationId == applicationId + } + if (projectDirPath.isNotBlank() && builds) File(projectDirPath) else null + } catch (e: Exception) { + logger.warn("Could not tell whether the open project builds {}", applicationId, e) + null + } + override fun onInstallEndedWithoutLaunch(packageName: String) { debuggerEndpointRepository.discardPendingInstall(packageName) } diff --git a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt index 98033c815b..fad2ee1dd0 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt @@ -57,15 +57,23 @@ class DebuggerEndpointRepository( } /** - * Call when the install of [applicationId] succeeded. Pairs it with the project that built it, - * if [expectInstallAsync] noted one, and returns whether it did. An install the user started - * some other way, such as opening an APK file, is not paired. + * Call when the install of [applicationId] succeeded, before the app is launched, and returns whether it paired + * the app. With a note from [expectInstallAsync] at most 5 minutes old, the app moves to the project that built + * it. Without one, as when the install prompt stayed open longer, the launch that follows pairs it as + * [recordLaunched] does, with [launchingProjectDir]: the caller passes the open project's directory when that + * project builds [applicationId], and null otherwise, so an unrelated APK installed from a file is not paired. */ - suspend fun confirmInstall(applicationId: String): Boolean { - val pending = pendingInstalls.remove(applicationId) ?: return false - // A note this old belongs to an install that never reported a result. - if (clock() - pending.noteTimeMillis > PENDING_INSTALL_MAX_AGE_MILLIS) return false - return recordInstalled(applicationId, pending.location) + suspend fun confirmInstall( + applicationId: String, + launchingProjectDir: File?, + ): Boolean { + val pending = pendingInstalls.remove(applicationId) + // An older note may belong to an install that never reported a result, from a project that is no longer + // open, so it must not move the pairing; recordLaunched never moves one. + if (pending != null && clock() - pending.noteTimeMillis <= PENDING_INSTALL_MAX_AGE_MILLIS) { + return recordInstalled(applicationId, pending.location) + } + return launchingProjectDir != null && recordLaunched(applicationId, launchingProjectDir) } /** diff --git a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt index ee4565837b..b747639158 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt @@ -131,7 +131,7 @@ class DebuggerEndpointRepositoryTest { var confirmed = false repeat(100) { if (!confirmed) { - confirmed = repository.confirmInstall("com.example") + confirmed = repository.confirmInstall("com.example", launchingProjectDir = null) if (!confirmed) Thread.sleep(50) } } @@ -144,11 +144,11 @@ class DebuggerEndpointRepositoryTest { } @Test - fun `an install nobody expected is not paired`() = + fun `an install nobody expected is not paired when the open project does not build it`() = runBlocking { addProject("/p/a") - assertThat(repository.confirmInstall("com.example")).isFalse() + assertThat(repository.confirmInstall("com.example", launchingProjectDir = null)).isFalse() assertThat(room.debuggerEndpointDao().getByApplicationId("com.example")).isNull() } @@ -179,12 +179,13 @@ class DebuggerEndpointRepositoryTest { discard: Boolean, advanceMillis: Long, now: AtomicLong, + launchingProjectDir: File? = null, ): Boolean { repo.expectInstallAsync(dir) { id } Thread.sleep(300) if (discard) repo.discardPendingInstall(id) now.addAndGet(advanceMillis) - return repo.confirmInstall(id) + return repo.confirmInstall(id, launchingProjectDir) } private fun clockedRepository(now: AtomicLong) = @@ -238,6 +239,56 @@ class DebuggerEndpointRepositoryTest { } } + @Test + fun `after a note expires, the launch still pairs the app with the open project`() = + runBlocking { + val dir = + File.createTempFile("proj", "").apply { + delete() + mkdirs() + } + try { + addProject(dir.canonicalPath) + val now = AtomicLong(1_000L) + + val sixMinutes = 6 * 60 * 1000L + val paired = + awaitNoted( + clockedRepository(now), + "com.example", + dir, + discard = false, + advanceMillis = sixMinutes, + now = now, + launchingProjectDir = File(dir, "../" + dir.name), + ) + + assertThat(paired).isTrue() + assertThat(room.debuggerEndpointDao().getByApplicationId("com.example")?.projectLocation).isEqualTo(dir.canonicalPath) + } finally { + dir.delete() + } + } + + @Test + fun `an install with no note pairs with the open project that builds the app`() = + runBlocking { + val dir = + File.createTempFile("proj", "").apply { + delete() + mkdirs() + } + try { + addProject(dir.canonicalPath) + + assertThat(repository.confirmInstall("com.example", launchingProjectDir = dir)).isTrue() + + assertThat(room.debuggerEndpointDao().getByApplicationId("com.example")?.projectLocation).isEqualTo(dir.canonicalPath) + } finally { + dir.delete() + } + } + @Test fun `a recent note still pairs on success`() = runBlocking { diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index c0ab2e3864..ed8d279724 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -23,7 +23,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `get_events`. - `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. - `EndpointBroadcast` runs once the server listens, on every process start (the port changes). It sends an explicit broadcast, action `com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT`, to `com.itsaky.androidide` with `FLAG_INCLUDE_STOPPED_PACKAGES`, carrying the token, the port and a `PendingIntent` that identifies the app. The `PendingIntent` is immutable (on API 23 and later; the flag does not exist before) and wraps an intent that is never sent: Code on the Go reads its `creatorPackage`, which the framework sets and another app cannot forge, as the app's package name. The library manifest declares `` for Code on the Go. A failure to send is logged and never thrown. Before the first send it registers a receiver at run time for `org.appdevforall.sqlitedebugger.ANNOUNCE` (exported, as Code on the Go is another app; `RECEIVER_EXPORTED` on API 33 and later), and sends the same token and port again each time it receives one. Code on the Go sends that request when it pairs the app, because it drops a report from an app it has not paired: an app that was already running then, installed some other way or started before its project was opened, would otherwise stay unknown until its process restarted. The receiver is not in the manifest, so a request never starts an app that is not running, and is not authenticated (ADFA-7131 D8): the reply goes only to Code on the Go. -- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). +- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. A successful install moves the app to the project that started it, from a note kept for 5 minutes; when the note is older (an install prompt left open) or missing, the launch after the install pairs the app as `LaunchAppAction` does, if the open project builds it, and never moves an existing pairing. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). ### The event record From 7bd6675a1c978158618671a1898b0bc71f720106 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 22:36:39 -0800 Subject: [PATCH 09/21] ADFA-7137 Pair each install by its PackageInstaller session, in the app-wide receiver Review 5950634318 of 6d8c81c58 found four faults in the install pairing: 1. It ran in the editor's EventBus subscriber, which gets the non-sticky result only between onStart and onStop, so a result that came while the install prompt had stopped the editor was lost. 2. A success with the launch suppressed (Quick Build) dropped the note as if the install had failed. 3. The post-install launch waited for the Room write in activityScope; an Activity destroyed meanwhile lost the launch, silently. 4. The note, keyed by application ID, was written fire-and-forget, so it could land after the result, and a stale one was taken by the next install of the same ID (an APK opened from the file tree, another project), moving the pairing. And once the 5-minute expiry passed, the open project was paired, which can be another project with the same ID, as two made from one template have. Now ProjectHandlerActivity notes each install by session ID, with the project and the APK's application ID, through ApkInstaller's new beforeCommit hook: on the install's IO thread, just before the session is committed, so the result always finds it (4). InstallationResultReceiver, in the manifest, handles the result app-wide: on success, launch or not, it pairs the noted app with its session's project on the application scope; a failure drops that session's note only; the install prompt keeps it (1, 2). The event that launches the app is posted without waiting for the write, and BaseEditorActivity's handler is stage's again, launching at once; the announce after each pairing brings the app's report once the row exists (3). Only the same session's result uses a note, and nothing expires, so a slow install pairs with its own project, two projects sharing an application ID pair their own installs, and an install Code on the Go did not start is paired by its next launch from a project (recordLaunched) (4, and the template case). The 5-minute expiry guessed which install a result belonged to, which the session ID now says, so it is gone, and with it the open-project fallback (openProjectDirBuilding), which existed for expired notes. A result naming another package than the noted one pairs nothing: the receiver is exported. Limits: notes live in memory, in the repository singleton. A recreated editor keeps them; a process death mid-install loses them, and the next launch pairs the app. A note whose session never reports, as after a failed commit, stays unused until the process ends. The intent-based fallback installer has no session and reports no result, so its installs pair at launch, as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../activities/editor/BaseEditorActivity.kt | 29 +-- .../editor/ProjectHandlerActivity.kt | 62 ++---- .../DebuggerEndpointRepository.kt | 78 ++++--- .../services/InstallationResultReceiver.kt | 50 ++++- .../itsaky/androidide/utils/ApkInstaller.kt | 15 +- .../viewmodel/ApkInstallationViewModel.kt | 3 + .../DebuggerEndpointRepositoryTest.kt | 200 +++++++----------- .../InstallationResultReceiverTest.kt | 191 +++++++++++++++++ subprojects/sqlite-debugger/README.md | 2 +- 9 files changed, 399 insertions(+), 231 deletions(-) create mode 100644 app/src/test/java/com/itsaky/androidide/services/InstallationResultReceiverTest.kt diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/BaseEditorActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/BaseEditorActivity.kt index 5fd7e0accd..812c443225 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/BaseEditorActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/BaseEditorActivity.kt @@ -20,7 +20,6 @@ package com.itsaky.androidide.activities.editor import android.content.ComponentName import android.content.Intent import android.content.ServiceConnection -import android.content.pm.PackageInstaller import android.content.res.Configuration import android.graphics.Color import android.graphics.Rect @@ -756,33 +755,7 @@ abstract class BaseEditorActivity : return } - val packageName = onResult(this, intent) - if (packageName == null) { - val extras = intent.extras - val installed = extras?.getString(PackageInstaller.EXTRA_PACKAGE_NAME) - if (installed != null && extras.getInt(PackageInstaller.EXTRA_STATUS) != PackageInstaller.STATUS_PENDING_USER_ACTION) { - onInstallEndedWithoutLaunch(installed) - } - return - } - // Runs before the launch so the app's first report finds its pairing row. - activityScope.launch(Dispatchers.Main.immediate) { - beforePostInstallLaunch(packageName) - launchAfterInstall(event, packageName) - } - } - - /** Called on the main thread when an install of [packageName] ended and no post-install launch follows (failed, cancelled, or suppressed). */ - protected open fun onInstallEndedWithoutLaunch(packageName: String) {} - - /** Called on the main thread after an install succeeded, before the app is launched. Must not throw. */ - protected open suspend fun beforePostInstallLaunch(packageName: String) {} - - private fun launchAfterInstall( - event: InstallationEvent.InstallationResultEvent, - packageName: String, - ) { - if (isDestroying) return + val packageName = onResult(this, intent) ?: return val isDebugging = event.intent.getBooleanExtra(DebugAction.ID, false) if (!isDebugging) { doLaunchApp(packageName) diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt index a244ff0432..94280a5708 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt @@ -285,6 +285,15 @@ abstract class ProjectHandlerActivity : const val STATE_KEY_SHOULD_INITIALIZE = "ide.editor.isInitializing" private const val PLUGIN_SEARCH_TIMEOUT_SECONDS = 10L + + private fun apkApplicationId( + packageManager: PackageManager, + apk: File, + ): String? = + runCatching { packageManager.getPackageArchiveInfo(apk.absolutePath, 0)?.packageName } + .onFailure { logger.warn("Could not read the applicationId of {}", apk, it) } + .getOrNull() + ?.takeIf { it.isNotBlank() } } abstract fun doCloseAll() @@ -724,55 +733,30 @@ abstract class ProjectHandlerActivity : */ private fun apkApplicationId(apk: File): String? = apkApplicationId(packageManager, apk) - private fun apkApplicationId( - packageManager: PackageManager, - apk: File, - ): String? = - runCatching { packageManager.getPackageArchiveInfo(apk.absolutePath, 0)?.packageName } - .onFailure { logger.warn("Could not read the applicationId of {}", apk, it) } - .getOrNull() - ?.takeIf { it.isNotBlank() } - - override suspend fun beforePostInstallLaunch(packageName: String) { - debuggerEndpointRepository.confirmInstall(packageName, openProjectDirBuilding(packageName)) - } - /** - * The open project's directory when one of its app modules builds [applicationId], as LaunchAppAction pairs a - * launch, else null. Never throws: [beforePostInstallLaunch] must not. + * Notes the install of [apk] as the open project's for the SQLite debugger pairing (ADFA-7137), or null when no + * project is open. It runs on the install's IO thread before the session is committed, and + * InstallationResultReceiver pairs the app when that session succeeds. When the APK's application ID cannot be + * read, nothing is noted, and the app's next launch from the project pairs it. Captures no Activity: the install + * outlives a recreated one. */ - private fun openProjectDirBuilding(applicationId: String): File? = - try { - val projectManager = IProjectManager.getInstance() - val projectDirPath = projectManager.projectDirPath - val builds = - projectManager.getAndroidAppModules().any { module -> - module.getSelectedVariant()?.mainArtifact?.applicationId == applicationId - } - if (projectDirPath.isNotBlank() && builds) File(projectDirPath) else null - } catch (e: Exception) { - logger.warn("Could not tell whether the open project builds {}", applicationId, e) - null + private fun pendingInstallNote(apk: File): ((sessionId: Int) -> Unit)? { + val projectDirPath = IProjectManager.getInstance().projectDirPath + if (projectDirPath.isBlank()) return null + val projectDir = File(projectDirPath) + val repository = debuggerEndpointRepository + val packageManager = applicationContext.packageManager + return { sessionId -> + apkApplicationId(packageManager, apk)?.let { repository.notePendingInstall(sessionId, projectDir, it) } } - - override fun onInstallEndedWithoutLaunch(packageName: String) { - debuggerEndpointRepository.discardPendingInstall(packageName) } private fun doInstallApk(state: BuildState.AwaitingInstall) { - val projectDirPath = IProjectManager.getInstance().projectDirPath - if (projectDirPath.isNotBlank()) { - val apk = state.apkFile - // The lambda outlives this Activity in the application scope. The pairing itself is written - // by beforePostInstallLaunch, once the install has succeeded. - val packageManager = applicationContext.packageManager - debuggerEndpointRepository.expectInstallAsync(File(projectDirPath)) { apkApplicationId(packageManager, apk) } - } - apkInstallationViewModel.installApk( context = this, apk = state.apkFile, launchInDebugMode = state.launchInDebugMode, + beforeCommit = pendingInstallNote(state.apkFile), ) if (state.launchProfilerAfterInstall) { diff --git a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt index fad2ee1dd0..a9b9b6af13 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt @@ -6,6 +6,7 @@ import com.itsaky.androidide.utils.canonicalProjectLocation import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.slf4j.LoggerFactory @@ -29,60 +30,58 @@ class DebuggerEndpointRepository( private val announce: (applicationId: String) -> Unit, ) { private class PendingInstall( + val applicationId: String, val location: String, - val noteTimeMillis: Long, ) - /** Installs expected to finish, by applicationId, with the project location that built them. */ - private val pendingInstalls = ConcurrentHashMap() + /** + * Installs Code on the Go started from a project, by PackageInstaller session ID, until the session reports a + * result. Held by this application-wide singleton, so recreating the editor Activity loses none; a process death + * loses them all, and each app is then paired by its next launch from its project (LaunchAppAction). Nothing + * expires, so a slow install still finds its note. A note whose session never reports, as when the commit + * failed, stays unused until the process ends: session IDs are not reused. + */ + private val pendingInstalls = ConcurrentHashMap() /** - * Notes, off the main thread, that [projectDir] is installing the app [applicationId] returns - * (it may read an APK). Nothing is written until [confirmInstall] reports the install succeeded. + * Notes that the PackageInstaller session [sessionId] installs [applicationId], built by [projectDir]. Call it + * before the session is committed, so its result always finds the note. It reads the file system: not on the + * main thread. */ - fun expectInstallAsync( + fun notePendingInstall( + sessionId: Int, projectDir: File, - applicationId: () -> String?, + applicationId: String, ) { - scope.launch { - try { - val id = runCatching(applicationId).getOrNull()?.takeIf { it.isNotBlank() } ?: return@launch - pendingInstalls[id] = PendingInstall(projectDir.canonicalProjectLocation(), clock()) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - log.warn("Could not note the install of project {}", projectDir, e) - } - } + pendingInstalls[sessionId] = PendingInstall(applicationId, projectDir.canonicalProjectLocation()) } /** - * Call when the install of [applicationId] succeeded, before the app is launched, and returns whether it paired - * the app. With a note from [expectInstallAsync] at most 5 minutes old, the app moves to the project that built - * it. Without one, as when the install prompt stayed open longer, the launch that follows pairs it as - * [recordLaunched] does, with [launchingProjectDir]: the caller passes the open project's directory when that - * project builds [applicationId], and null otherwise, so an unrelated APK installed from a file is not paired. + * Call when the session [sessionId] succeeded, whether or not a launch follows. If [notePendingInstall] noted it, + * pairs the app with the project that started it on the application scope, moving it from any other project, + * and returns that write; the caller need not wait for it before launching the app, which is asked to report + * again once paired. Only this session's result uses its note, however long the install took: another install + * of the same application ID, from this project or another, has its own session. + * + * Returns null, and writes nothing, for an install that was not noted, such as an APK opened from the file + * tree; its next launch from a project pairs it. Also when [installedApplicationId], the package the result + * names, is not the noted one: the result comes through an exported receiver, so it can be forged. */ - suspend fun confirmInstall( - applicationId: String, - launchingProjectDir: File?, - ): Boolean { - val pending = pendingInstalls.remove(applicationId) - // An older note may belong to an install that never reported a result, from a project that is no longer - // open, so it must not move the pairing; recordLaunched never moves one. - if (pending != null && clock() - pending.noteTimeMillis <= PENDING_INSTALL_MAX_AGE_MILLIS) { - return recordInstalled(applicationId, pending.location) + fun confirmInstall( + sessionId: Int, + installedApplicationId: String?, + ): Job? { + val note = pendingInstalls.remove(sessionId) ?: return null + if (installedApplicationId != null && installedApplicationId != note.applicationId) { + log.warn("Session {} installed {}, not {}; not paired", sessionId, installedApplicationId, note.applicationId) + return null } - return launchingProjectDir != null && recordLaunched(applicationId, launchingProjectDir) + return scope.launch { recordInstalled(note.applicationId, note.location) } } - /** - * Call when the install of [applicationId] ended without success (failed, cancelled, blocked), so - * a later install of the same app from elsewhere, such as an APK file, is not paired with the - * project that started this one. - */ - fun discardPendingInstall(applicationId: String) { - pendingInstalls.remove(applicationId) + /** Call when the session [sessionId] failed, was aborted or was blocked, to drop its note; other sessions' stay. */ + fun discardPendingInstall(sessionId: Int) { + pendingInstalls.remove(sessionId) } /** @@ -149,7 +148,6 @@ class DebuggerEndpointRepository( } private companion object { - private const val PENDING_INSTALL_MAX_AGE_MILLIS = 5 * 60 * 1000L private val log = LoggerFactory.getLogger(DebuggerEndpointRepository::class.java) } } diff --git a/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt b/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt index 81b0a25a13..af823bf152 100644 --- a/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt +++ b/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt @@ -20,26 +20,74 @@ package com.itsaky.androidide.services import android.content.BroadcastReceiver import android.content.Context import android.content.Intent +import android.content.pm.PackageInstaller import com.itsaky.androidide.buildinfo.BuildInfo import com.itsaky.androidide.events.InstallationEvent.InstallationResultEvent +import com.itsaky.androidide.repositories.DebuggerEndpointRepository import com.itsaky.androidide.utils.ApkInstaller import org.greenrobot.eventbus.EventBus +import org.koin.core.component.KoinComponent +import org.koin.core.component.inject +import org.slf4j.LoggerFactory /** * Receives status events for APK installation process. * * @author Akash Yadav */ -class InstallationResultReceiver : BroadcastReceiver() { +class InstallationResultReceiver : + BroadcastReceiver(), + KoinComponent { companion object { const val ACTION_INSTALL_STATUS = "${BuildInfo.PACKAGE_NAME}.installer.INSTALL_STATUS" + + private val log = LoggerFactory.getLogger(InstallationResultReceiver::class.java) } + private val debuggerEndpointRepository: DebuggerEndpointRepository by inject() + override fun onReceive( context: Context, intent: Intent, ) { ApkInstaller.onInstallStatusBroadcast(intent, context) + pairSqliteDebugger(intent) EventBus.getDefault().post(InstallationResultEvent(intent)) } + + /** + * Pairs the installed app with the project whose install it was, for the SQLite debugger (ADFA-7137), or drops + * the install's note when it failed. Done here rather than in the editor, which receives the event only while it + * is started: the event is not sticky, and the install prompt can stop the editor. On success it pairs whether + * or not a launch follows (Quick Build suppresses it), and the event, which launches the app, is posted without + * waiting for the write. + */ + private fun pairSqliteDebugger(intent: Intent) { + try { + val extras = intent.extras ?: return + if (!extras.containsKey(PackageInstaller.EXTRA_SESSION_ID) || !extras.containsKey(PackageInstaller.EXTRA_STATUS)) return + val sessionId = extras.getInt(PackageInstaller.EXTRA_SESSION_ID) + when (extras.getInt(PackageInstaller.EXTRA_STATUS)) { + PackageInstaller.STATUS_PENDING_USER_ACTION -> { + // Not a result yet: the note waits for the one that follows the prompt. + } + + PackageInstaller.STATUS_SUCCESS -> { + val write = + debuggerEndpointRepository.confirmInstall(sessionId, extras.getString(PackageInstaller.EXTRA_PACKAGE_NAME)) + ?: return + // Null when the broadcast was not delivered by the framework, as in a direct call. + val pending: PendingResult? = goAsync() + write.invokeOnCompletion { pending?.finish() } + } + + else -> { + debuggerEndpointRepository.discardPendingInstall(sessionId) + } + } + } catch (e: Exception) { + // The receiver is exported, so the extras can be malformed; the launch must go on regardless. + log.warn("Could not pair the SQLite debugger of an install", e) + } + } } diff --git a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt index ce7d347bc8..7ce0c86b30 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt @@ -103,6 +103,10 @@ object ApkInstaller { * @param apk The APK file to install. * @param suppressPostInstallLaunch tag the install so its success result skips the * launch-after-install behavior; see [EXTRA_SUPPRESS_POST_INSTALL_LAUNCH]. + * @param beforeCommit called with the session ID on an IO thread once the APK is staged, just before the session + * is committed, so whatever it records is in place when the result arrives. Not called by the intent-based + * fallback installer, which has no session and reports no result. What it throws is logged, and the install + * goes on. */ @JvmStatic suspend fun installApk( @@ -111,6 +115,7 @@ object ApkInstaller { launchInDebugMode: Boolean = false, debugFallbackInstaller: Boolean = DEBUG_FALLBACK_INSTALLER, suppressPostInstallLaunch: Boolean = false, + beforeCommit: ((sessionId: Int) -> Unit)? = null, ): Boolean = installApkSession( context = context, @@ -118,12 +123,13 @@ object ApkInstaller { launchInDebugMode = launchInDebugMode, debugFallbackInstaller = debugFallbackInstaller, suppressPostInstallLaunch = suppressPostInstallLaunch, + beforeCommit = beforeCommit, ) is SessionLaunchResult.Started /** * Starts a session-based package installation workflow and returns a [SessionLaunchResult] * with the committed `sessionId` (or a distinct [SessionLaunchResult.TooManySessions] - * when the UID's active session quota is exhausted). + * when the UID's active session quota is exhausted). [beforeCommit] is as for [installApk]. */ @JvmStatic suspend fun installApkSession( @@ -132,6 +138,7 @@ object ApkInstaller { launchInDebugMode: Boolean = false, debugFallbackInstaller: Boolean = DEBUG_FALLBACK_INSTALLER, suppressPostInstallLaunch: Boolean = false, + beforeCommit: ((sessionId: Int) -> Unit)? = null, ): SessionLaunchResult { val isValidApk = withContext(Dispatchers.IO) { @@ -167,7 +174,7 @@ object ApkInstaller { } } - return installUsingSession(context, apk, baseIntent) + return installUsingSession(context, apk, baseIntent, beforeCommit) } /** @@ -463,6 +470,7 @@ object ApkInstaller { context: Context, apk: File, intent: Intent, + beforeCommit: ((sessionId: Int) -> Unit)? = null, ): SessionLaunchResult { val installer = context.packageManager.packageInstaller val params = createSessionParams() @@ -489,6 +497,9 @@ object ApkInstaller { "PackageInstaller callback intent is null" } addToSession(session, apk) + beforeCommit?.let { record -> + runCatching { record(sessionId) }.onFailure { log.warn("beforeCommit failed for session {}", sessionId, it) } + } session.commit(callback.intentSender) sessionId } catch (t: Throwable) { diff --git a/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt index e883f71f68..117a8a35b5 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt @@ -120,11 +120,13 @@ class ApkInstallationViewModel : ViewModel() { * * @param context The context. * @param apk The APK file to install. + * @param beforeCommit see [ApkInstaller.installApk]. */ fun installApk( context: Context, apk: File, launchInDebugMode: Boolean, + beforeCommit: ((sessionId: Int) -> Unit)? = null, ) { packageInstaller = context.applicationContext.packageManager.packageInstaller packageInstaller.unregisterSessionCallback(callback) @@ -135,6 +137,7 @@ class ApkInstallationViewModel : ViewModel() { context, apk, launchInDebugMode, + beforeCommit = beforeCommit, ) } } diff --git a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt index b747639158..fe28b8dcf1 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt @@ -117,193 +117,153 @@ class DebuggerEndpointRepositoryTest { assertThat(row.updatedAt).isNull() } + /** A project directory that exists and is in recents. */ + private suspend fun newProject(): File = + java.nio.file.Files + .createTempDirectory("proj") + .toFile() + .also { addProject(it.canonicalPath) } + + private suspend fun pairedLocation(applicationId: String = "com.example"): String? = + room.debuggerEndpointDao().getByApplicationId(applicationId)?.projectLocation + + private fun clockedRepository(now: AtomicLong) = + DebuggerEndpointRepository( + room.debuggerEndpointDao(), + CoroutineScope(Dispatchers.IO), + clock = { now.get() }, + announce = { announced += it }, + ) + @Test - fun `an expected install is paired with its canonical project location once it succeeds`() = + fun `a noted install is paired with its canonical project location once its session succeeds`() = runBlocking { - val dir = - java.nio.file.Files - .createTempDirectory("proj") - .toFile() + val dir = newProject() try { - addProject(dir.canonicalPath) - - repository.expectInstallAsync(File(dir, "../" + dir.name)) { "com.example" } - var confirmed = false - repeat(100) { - if (!confirmed) { - confirmed = repository.confirmInstall("com.example", launchingProjectDir = null) - if (!confirmed) Thread.sleep(50) - } - } - - assertThat(confirmed).isTrue() - assertThat(room.debuggerEndpointDao().getByApplicationId("com.example")?.projectLocation).isEqualTo(dir.canonicalPath) + repository.notePendingInstall(1, File(dir, "../" + dir.name), "com.example") + + repository.confirmInstall(1, "com.example")?.join() + + assertThat(pairedLocation()).isEqualTo(dir.canonicalPath) + assertThat(announced).containsExactly("com.example") } finally { dir.delete() } } @Test - fun `an install nobody expected is not paired when the open project does not build it`() = + fun `a noted install writes nothing until its session succeeds`() = runBlocking { - addProject("/p/a") - - assertThat(repository.confirmInstall("com.example", launchingProjectDir = null)).isFalse() + val dir = newProject() + try { + repository.notePendingInstall(1, dir, "com.example") - assertThat(room.debuggerEndpointDao().getByApplicationId("com.example")).isNull() + assertThat(pairedLocation()).isNull() + } finally { + dir.delete() + } } @Test - fun `an expected install writes nothing until it is confirmed`() = + fun `a stale note is not used by another session's result or an install Code on the Go did not start`() = runBlocking { - val dir = - java.nio.file.Files - .createTempDirectory("proj") - .toFile() + val dir = newProject() try { - addProject(dir.canonicalPath) + repository.notePendingInstall(1, dir, "com.example") - repository.expectInstallAsync(dir) { "com.example" } - Thread.sleep(500) + // Session 2 has no note: an APK opened from the file tree, say, of the same application ID. + assertThat(repository.confirmInstall(2, "com.example")).isNull() + assertThat(pairedLocation()).isNull() - assertThat(room.debuggerEndpointDao().getByApplicationId("com.example")).isNull() + repository.confirmInstall(1, "com.example")?.join() + assertThat(pairedLocation()).isEqualTo(dir.canonicalPath) } finally { dir.delete() } } - private suspend fun awaitNoted( - repo: DebuggerEndpointRepository, - id: String, - dir: File, - discard: Boolean, - advanceMillis: Long, - now: AtomicLong, - launchingProjectDir: File? = null, - ): Boolean { - repo.expectInstallAsync(dir) { id } - Thread.sleep(300) - if (discard) repo.discardPendingInstall(id) - now.addAndGet(advanceMillis) - return repo.confirmInstall(id, launchingProjectDir) - } - - private fun clockedRepository(now: AtomicLong) = - DebuggerEndpointRepository( - room.debuggerEndpointDao(), - CoroutineScope(Dispatchers.IO), - clock = { now.get() }, - announce = { announced += it }, - ) - @Test - fun `a failed install does not pair a later install of the same app`() = + fun `two projects with the same application ID each pair with their own session`() = runBlocking { - val dir = - File.createTempFile("proj", "").apply { - delete() - mkdirs() - } + val projectA = newProject() + val projectB = newProject() try { - addProject(dir.canonicalPath) - val now = AtomicLong(1_000L) + repository.notePendingInstall(1, projectA, "com.example") + repository.notePendingInstall(2, projectB, "com.example") - val paired = awaitNoted(clockedRepository(now), "com.example", dir, discard = true, advanceMillis = 0, now = now) + repository.confirmInstall(1, "com.example")?.join() + assertThat(pairedLocation()).isEqualTo(projectA.canonicalPath) - assertThat(paired).isFalse() - assertThat(room.debuggerEndpointDao().getByApplicationId("com.example")).isNull() + repository.confirmInstall(2, "com.example")?.join() + assertThat(pairedLocation()).isEqualTo(projectB.canonicalPath) } finally { - dir.delete() + projectA.delete() + projectB.delete() } } @Test - fun `a note older than the expiry is not used`() = + fun `an install whose prompt stayed open more than 5 minutes still pairs with its own project`() = runBlocking { - val dir = - File.createTempFile("proj", "").apply { - delete() - mkdirs() - } + val dir = newProject() try { - addProject(dir.canonicalPath) val now = AtomicLong(1_000L) + val repo = clockedRepository(now) + repo.notePendingInstall(1, dir, "com.example") - val sixMinutes = 6 * 60 * 1000L - val paired = awaitNoted(clockedRepository(now), "com.example", dir, discard = false, advanceMillis = sixMinutes, now = now) + now.addAndGet(6 * 60 * 1000L) + repo.confirmInstall(1, "com.example")?.join() - assertThat(paired).isFalse() - assertThat(room.debuggerEndpointDao().getByApplicationId("com.example")).isNull() + assertThat(pairedLocation()).isEqualTo(dir.canonicalPath) } finally { dir.delete() } } @Test - fun `after a note expires, the launch still pairs the app with the open project`() = + fun `a failed install drops only its own session's note`() = runBlocking { - val dir = - File.createTempFile("proj", "").apply { - delete() - mkdirs() - } + val dir = newProject() try { - addProject(dir.canonicalPath) - val now = AtomicLong(1_000L) + repository.notePendingInstall(1, dir, "com.example") + repository.notePendingInstall(2, dir, "com.example") - val sixMinutes = 6 * 60 * 1000L - val paired = - awaitNoted( - clockedRepository(now), - "com.example", - dir, - discard = false, - advanceMillis = sixMinutes, - now = now, - launchingProjectDir = File(dir, "../" + dir.name), - ) - - assertThat(paired).isTrue() - assertThat(room.debuggerEndpointDao().getByApplicationId("com.example")?.projectLocation).isEqualTo(dir.canonicalPath) + repository.discardPendingInstall(1) + + assertThat(repository.confirmInstall(1, "com.example")).isNull() + repository.confirmInstall(2, "com.example")?.join() + assertThat(pairedLocation()).isEqualTo(dir.canonicalPath) } finally { dir.delete() } } @Test - fun `an install with no note pairs with the open project that builds the app`() = + fun `a result naming another package than the noted one pairs nothing`() = runBlocking { - val dir = - File.createTempFile("proj", "").apply { - delete() - mkdirs() - } + val dir = newProject() try { - addProject(dir.canonicalPath) + repository.notePendingInstall(1, dir, "com.example") - assertThat(repository.confirmInstall("com.example", launchingProjectDir = dir)).isTrue() + assertThat(repository.confirmInstall(1, "com.other")).isNull() - assertThat(room.debuggerEndpointDao().getByApplicationId("com.example")?.projectLocation).isEqualTo(dir.canonicalPath) + assertThat(pairedLocation("com.example")).isNull() + assertThat(pairedLocation("com.other")).isNull() } finally { dir.delete() } } @Test - fun `a recent note still pairs on success`() = + fun `a result without a package name pairs the noted application ID`() = runBlocking { - val dir = - File.createTempFile("proj", "").apply { - delete() - mkdirs() - } + val dir = newProject() try { - addProject(dir.canonicalPath) - val now = AtomicLong(1_000L) + repository.notePendingInstall(1, dir, "com.example") - val paired = awaitNoted(clockedRepository(now), "com.example", dir, discard = false, advanceMillis = 60_000L, now = now) + repository.confirmInstall(1, installedApplicationId = null)?.join() - assertThat(paired).isTrue() + assertThat(pairedLocation()).isEqualTo(dir.canonicalPath) } finally { dir.delete() } diff --git a/app/src/test/java/com/itsaky/androidide/services/InstallationResultReceiverTest.kt b/app/src/test/java/com/itsaky/androidide/services/InstallationResultReceiverTest.kt new file mode 100644 index 0000000000..33314e061e --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/services/InstallationResultReceiverTest.kt @@ -0,0 +1,191 @@ +package com.itsaky.androidide.services + +import android.content.Context +import android.content.Intent +import android.content.pm.PackageInstaller +import androidx.room.Room +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.events.InstallationEvent.InstallationResultEvent +import com.itsaky.androidide.repositories.DebuggerEndpointRepository +import com.itsaky.androidide.roomData.recentproject.DebuggerEndpointDao +import com.itsaky.androidide.roomData.recentproject.RecentProject +import com.itsaky.androidide.roomData.recentproject.RecentProjectRoomDatabase +import com.itsaky.androidide.utils.ApkInstaller +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withContext +import org.greenrobot.eventbus.EventBus +import org.greenrobot.eventbus.Subscribe +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.koin.core.context.GlobalContext +import org.koin.core.context.startKoin +import org.koin.core.context.stopKoin +import org.koin.dsl.module +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean + +/** + * The SQLite debugger pairing of an install (ADFA-7137) is written by the app-wide receiver, not by the editor, + * which sees the result event only while it is started, and the event that launches the app does not wait for it. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], application = android.app.Application::class) +class InstallationResultReceiverTest { + private lateinit var room: RecentProjectRoomDatabase + private lateinit var project: File + private val context: Context get() = ApplicationProvider.getApplicationContext() + private var recorder: Recorder? = null + + /** Stands in for the editor's subscriber, which launches the app. */ + class Recorder( + private val onEvent: (InstallationResultEvent) -> Unit, + ) { + @Subscribe + fun on(event: InstallationResultEvent) = onEvent(event) + } + + @Before + fun setUp() { + room = + Room + .inMemoryDatabaseBuilder(context, RecentProjectRoomDatabase::class.java) + .allowMainThreadQueries() + .build() + project = + java.nio.file.Files + .createTempDirectory("proj") + .toFile() + runBlocking { room.recentProjectDao().insert(RecentProject(name = "a", createdAt = "1", location = project.canonicalPath)) } + } + + @After + fun tearDown() { + recorder?.let { EventBus.getDefault().unregister(it) } + if (GlobalContext.getOrNull() != null) stopKoin() + room.close() + project.delete() + } + + private fun repository( + dao: DebuggerEndpointDao = room.debuggerEndpointDao(), + scope: CoroutineScope = CoroutineScope(Dispatchers.IO), + ): DebuggerEndpointRepository { + val repository = DebuggerEndpointRepository(dao, scope, announce = {}) + if (GlobalContext.getOrNull() != null) stopKoin() + startKoin { modules(module { single { repository } }) } + return repository + } + + private fun record(onEvent: (InstallationResultEvent) -> Unit) { + recorder = Recorder(onEvent).also { EventBus.getDefault().register(it) } + } + + private fun deliver( + sessionId: Int, + status: Int, + suppressLaunch: Boolean = false, + ) { + val intent = + Intent(InstallationResultReceiver.ACTION_INSTALL_STATUS) + .putExtra(PackageInstaller.EXTRA_SESSION_ID, sessionId) + .putExtra(PackageInstaller.EXTRA_STATUS, status) + .putExtra(PackageInstaller.EXTRA_PACKAGE_NAME, "com.example") + if (suppressLaunch) intent.putExtra(ApkInstaller.EXTRA_SUPPRESS_POST_INSTALL_LAUNCH, true) + InstallationResultReceiver().onReceive(context, intent) + } + + /** The project the app is paired with, once the write on the application scope lands; null after 2 s. */ + private fun awaitPairedLocation(): String? { + repeat(100) { + runBlocking { room.debuggerEndpointDao().getByApplicationId("com.example") }?.let { return it.projectLocation } + Thread.sleep(20) + } + return null + } + + @Test + fun `a success that arrives while the editor is stopped still pairs`() { + val repository = repository() + repository.notePendingInstall(1, project, "com.example") + + // No subscriber: the stopped editor has unregistered from EventBus. + deliver(1, PackageInstaller.STATUS_SUCCESS) + + assertThat(awaitPairedLocation()).isEqualTo(project.canonicalPath) + } + + @Test + fun `a success with the launch suppressed pairs and uses up the note`() { + val repository = repository() + repository.notePendingInstall(1, project, "com.example") + + deliver(1, PackageInstaller.STATUS_SUCCESS, suppressLaunch = true) + + assertThat(awaitPairedLocation()).isEqualTo(project.canonicalPath) + assertThat(repository.confirmInstall(1, "com.example")).isNull() + } + + @Test + fun `a failure drops that session's note, and the install prompt keeps it`() { + val repository = repository() + repository.notePendingInstall(1, project, "com.example") + repository.notePendingInstall(2, project, "com.example") + + deliver(1, PackageInstaller.STATUS_FAILURE_ABORTED) + deliver(2, PackageInstaller.STATUS_PENDING_USER_ACTION) + + assertThat(repository.confirmInstall(1, "com.example")).isNull() + assertThat(repository.confirmInstall(2, "com.example")).isNotNull() + } + + @Test + fun `the event that launches the app is posted before a slow pairing write finishes`() { + val release = CountDownLatch(1) + val written = AtomicBoolean(false) + val roomDao = room.debuggerEndpointDao() + val slowDao = + object : DebuggerEndpointDao by roomDao { + override suspend fun upsertPairing( + applicationId: String, + projectLocation: String, + ) { + // Gives up after 2 s, so a receiver that waited for the write would post late, not hang the test. + withContext(Dispatchers.IO) { release.await(2, TimeUnit.SECONDS) } + roomDao.upsertPairing(applicationId, projectLocation) + written.set(true) + } + } + val repository = repository(dao = slowDao) + repository.notePendingInstall(1, project, "com.example") + var writtenWhenPosted: Boolean? = null + record { writtenWhenPosted = written.get() } + + deliver(1, PackageInstaller.STATUS_SUCCESS) + + assertThat(writtenWhenPosted).isFalse() + release.countDown() + assertThat(awaitPairedLocation()).isEqualTo(project.canonicalPath) + } + + @Test + fun `the event that launches the app is posted when the pairing scope is cancelled`() { + val repository = repository(scope = CoroutineScope(Job().apply { cancel() })) + repository.notePendingInstall(1, project, "com.example") + var posted = false + record { posted = true } + + deliver(1, PackageInstaller.STATUS_SUCCESS) + + assertThat(posted).isTrue() + } +} diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index ed8d279724..ee7ea4ade3 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -23,7 +23,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `get_events`. - `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. - `EndpointBroadcast` runs once the server listens, on every process start (the port changes). It sends an explicit broadcast, action `com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT`, to `com.itsaky.androidide` with `FLAG_INCLUDE_STOPPED_PACKAGES`, carrying the token, the port and a `PendingIntent` that identifies the app. The `PendingIntent` is immutable (on API 23 and later; the flag does not exist before) and wraps an intent that is never sent: Code on the Go reads its `creatorPackage`, which the framework sets and another app cannot forge, as the app's package name. The library manifest declares `` for Code on the Go. A failure to send is logged and never thrown. Before the first send it registers a receiver at run time for `org.appdevforall.sqlitedebugger.ANNOUNCE` (exported, as Code on the Go is another app; `RECEIVER_EXPORTED` on API 33 and later), and sends the same token and port again each time it receives one. Code on the Go sends that request when it pairs the app, because it drops a report from an app it has not paired: an app that was already running then, installed some other way or started before its project was opened, would otherwise stay unknown until its process restarted. The receiver is not in the manifest, so a request never starts an app that is not running, and is not authenticated (ADFA-7131 D8): the reply goes only to Code on the Go. -- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. A successful install moves the app to the project that started it, from a note kept for 5 minutes; when the note is older (an install prompt left open) or missing, the launch after the install pairs the app as `LaunchAppAction` does, if the open project builds it, and never moves an existing pairing. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). +- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. When `ProjectHandlerActivity` installs a build, it notes the PackageInstaller session ID with the project and the APK's application ID before the session is committed. `InstallationResultReceiver` takes the result app-wide, so a result that arrives while the editor is stopped still counts: on success, with or without a launch to follow (Quick Build suppresses it), it moves the app to that session's project; on failure it drops that session's note. Only the same session's result uses a note, however long the install prompt stayed open, so two projects with the same application ID, such as two made from one template, each pair their own installs. The post-install launch does not wait for the write; the announce request above brings the app's report once the row exists. An install Code on the Go did not start from a project (an APK opened from the file tree), or one whose result arrives after Code on the Go's process restarted (notes are kept in memory), is not paired at install; `LaunchAppAction` pairs it at the next launch. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). ### The event record From c45aae36096b3c082e648b79becc4857d36f7104 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 10:23:03 -0800 Subject: [PATCH 10/21] ADFA-7137 Drop the install note when the session cannot be committed ProjectHandlerActivity notes each install for the SQLite debugger pairing through ApkInstaller's beforeCommit hook, just before the commit. When staging or the commit itself threw, ApkInstaller abandoned the session, but the note stayed in DebuggerEndpointRepository: an abandoned uncommitted session reports no result, so nothing ever dropped it. ApkInstaller now takes onCommitFailed beside beforeCommit (installApk, installApkSession, installUsingSession, ApkInstallationViewModel.installApk) and calls it with the session ID on that path, before abandoning the session; what it throws is logged. ProjectHandlerActivity passes DebuggerEndpointRepository.discardPendingInstall. Test: ApkInstallerSessionTest "a commit that throws leaves no note, as its session reports no result". The ProjectHandlerActivity wiring is one line and not unit-tested (an Activity). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../editor/ProjectHandlerActivity.kt | 1 + .../DebuggerEndpointRepository.kt | 10 +++-- .../itsaky/androidide/utils/ApkInstaller.kt | 14 ++++++- .../viewmodel/ApkInstallationViewModel.kt | 3 ++ .../utils/ApkInstallerSessionTest.kt | 39 +++++++++++++++++++ subprojects/sqlite-debugger/README.md | 2 +- 6 files changed, 63 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt index 94280a5708..eecc8e19c3 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt @@ -757,6 +757,7 @@ abstract class ProjectHandlerActivity : apk = state.apkFile, launchInDebugMode = state.launchInDebugMode, beforeCommit = pendingInstallNote(state.apkFile), + onCommitFailed = debuggerEndpointRepository::discardPendingInstall, ) if (state.launchProfilerAfterInstall) { diff --git a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt index a9b9b6af13..3bfcffd2a5 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt @@ -38,8 +38,9 @@ class DebuggerEndpointRepository( * Installs Code on the Go started from a project, by PackageInstaller session ID, until the session reports a * result. Held by this application-wide singleton, so recreating the editor Activity loses none; a process death * loses them all, and each app is then paired by its next launch from its project (LaunchAppAction). Nothing - * expires, so a slow install still finds its note. A note whose session never reports, as when the commit - * failed, stays unused until the process ends: session IDs are not reused. + * expires, so a slow install still finds its note. A session whose staging or commit throws reports no result, + * so ApkInstaller's onCommitFailed drops its note through [discardPendingInstall]; a note whose session never + * reports for another reason stays unused until the process ends: session IDs are not reused. */ private val pendingInstalls = ConcurrentHashMap() @@ -79,7 +80,10 @@ class DebuggerEndpointRepository( return scope.launch { recordInstalled(note.applicationId, note.location) } } - /** Call when the session [sessionId] failed, was aborted or was blocked, to drop its note; other sessions' stay. */ + /** + * Call when the session [sessionId] failed, was aborted or was blocked, or could not be committed, to drop its + * note; other sessions' stay. + */ fun discardPendingInstall(sessionId: Int) { pendingInstalls.remove(sessionId) } diff --git a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt index 7ce0c86b30..6ba715f740 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt @@ -107,6 +107,9 @@ object ApkInstaller { * is committed, so whatever it records is in place when the result arrives. Not called by the intent-based * fallback installer, which has no session and reports no result. What it throws is logged, and the install * goes on. + * @param onCommitFailed called with the session ID on the same IO thread when staging or committing the session + * threw. The session is abandoned and reports no result, so this is where to drop what [beforeCommit] recorded. + * What it throws is logged. */ @JvmStatic suspend fun installApk( @@ -116,6 +119,7 @@ object ApkInstaller { debugFallbackInstaller: Boolean = DEBUG_FALLBACK_INSTALLER, suppressPostInstallLaunch: Boolean = false, beforeCommit: ((sessionId: Int) -> Unit)? = null, + onCommitFailed: ((sessionId: Int) -> Unit)? = null, ): Boolean = installApkSession( context = context, @@ -124,12 +128,13 @@ object ApkInstaller { debugFallbackInstaller = debugFallbackInstaller, suppressPostInstallLaunch = suppressPostInstallLaunch, beforeCommit = beforeCommit, + onCommitFailed = onCommitFailed, ) is SessionLaunchResult.Started /** * Starts a session-based package installation workflow and returns a [SessionLaunchResult] * with the committed `sessionId` (or a distinct [SessionLaunchResult.TooManySessions] - * when the UID's active session quota is exhausted). [beforeCommit] is as for [installApk]. + * when the UID's active session quota is exhausted). [beforeCommit] and [onCommitFailed] are as for [installApk]. */ @JvmStatic suspend fun installApkSession( @@ -139,6 +144,7 @@ object ApkInstaller { debugFallbackInstaller: Boolean = DEBUG_FALLBACK_INSTALLER, suppressPostInstallLaunch: Boolean = false, beforeCommit: ((sessionId: Int) -> Unit)? = null, + onCommitFailed: ((sessionId: Int) -> Unit)? = null, ): SessionLaunchResult { val isValidApk = withContext(Dispatchers.IO) { @@ -174,7 +180,7 @@ object ApkInstaller { } } - return installUsingSession(context, apk, baseIntent, beforeCommit) + return installUsingSession(context, apk, baseIntent, beforeCommit, onCommitFailed) } /** @@ -471,6 +477,7 @@ object ApkInstaller { apk: File, intent: Intent, beforeCommit: ((sessionId: Int) -> Unit)? = null, + onCommitFailed: ((sessionId: Int) -> Unit)? = null, ): SessionLaunchResult { val installer = context.packageManager.packageInstaller val params = createSessionParams() @@ -503,6 +510,9 @@ object ApkInstaller { session.commit(callback.intentSender) sessionId } catch (t: Throwable) { + onCommitFailed?.let { forget -> + runCatching { forget(sessionId) }.onFailure { log.warn("onCommitFailed failed for session {}", sessionId, it) } + } abandonSession(context, sessionId) throw t } finally { diff --git a/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt index 117a8a35b5..3ac04ceb60 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt @@ -121,12 +121,14 @@ class ApkInstallationViewModel : ViewModel() { * @param context The context. * @param apk The APK file to install. * @param beforeCommit see [ApkInstaller.installApk]. + * @param onCommitFailed see [ApkInstaller.installApk]. */ fun installApk( context: Context, apk: File, launchInDebugMode: Boolean, beforeCommit: ((sessionId: Int) -> Unit)? = null, + onCommitFailed: ((sessionId: Int) -> Unit)? = null, ) { packageInstaller = context.applicationContext.packageManager.packageInstaller packageInstaller.unregisterSessionCallback(callback) @@ -138,6 +140,7 @@ class ApkInstallationViewModel : ViewModel() { apk, launchInDebugMode, beforeCommit = beforeCommit, + onCommitFailed = onCommitFailed, ) } } diff --git a/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt b/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt index b3123637af..1783818582 100644 --- a/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt +++ b/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt @@ -283,6 +283,45 @@ class ApkInstallerSessionTest { assertThat(activeSessions).containsExactly(50) } + @Test + fun `a commit that throws leaves no note, as its session reports no result`() = + runTest { + val apk = tempFolder.newFile("app-debug.apk").apply { writeBytes(byteArrayOf(1, 2, 3, 4)) } + val session = mockk(relaxed = true) + every { session.openWrite(any(), any(), any()) } returns ByteArrayOutputStream() + every { session.commit(any()) } throws SecurityException("commit refused") + + val installer = mockk() + every { installer.createSession(any()) } returns 300 + every { installer.openSession(300) } returns session + justRun { installer.abandonSession(300) } + + val baseContext = ApplicationProvider.getApplicationContext() + val pm = spyk(baseContext.packageManager) + every { pm.packageInstaller } returns installer + val context = spyk(baseContext) + every { context.packageManager } returns pm + + // What ProjectHandlerActivity passes: a note before the commit, dropped when the commit fails. + val notes = mutableSetOf() + var noted = false + val result = + ApkInstaller.installUsingSession( + context, + apk, + Intent(), + beforeCommit = { + notes += it + noted = true + }, + onCommitFailed = { notes -= it }, + ) + + assertThat(result).isEqualTo(ApkInstaller.SessionLaunchResult.Failed) + assertThat(noted).isTrue() + assertThat(notes).isEmpty() + } + @Test fun `abandonSession retains tracking when abandonment throws and session is not finalized`() = runTest { diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index ee7ea4ade3..1675140cbd 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -23,7 +23,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `get_events`. - `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. - `EndpointBroadcast` runs once the server listens, on every process start (the port changes). It sends an explicit broadcast, action `com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT`, to `com.itsaky.androidide` with `FLAG_INCLUDE_STOPPED_PACKAGES`, carrying the token, the port and a `PendingIntent` that identifies the app. The `PendingIntent` is immutable (on API 23 and later; the flag does not exist before) and wraps an intent that is never sent: Code on the Go reads its `creatorPackage`, which the framework sets and another app cannot forge, as the app's package name. The library manifest declares `` for Code on the Go. A failure to send is logged and never thrown. Before the first send it registers a receiver at run time for `org.appdevforall.sqlitedebugger.ANNOUNCE` (exported, as Code on the Go is another app; `RECEIVER_EXPORTED` on API 33 and later), and sends the same token and port again each time it receives one. Code on the Go sends that request when it pairs the app, because it drops a report from an app it has not paired: an app that was already running then, installed some other way or started before its project was opened, would otherwise stay unknown until its process restarted. The receiver is not in the manifest, so a request never starts an app that is not running, and is not authenticated (ADFA-7131 D8): the reply goes only to Code on the Go. -- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. When `ProjectHandlerActivity` installs a build, it notes the PackageInstaller session ID with the project and the APK's application ID before the session is committed. `InstallationResultReceiver` takes the result app-wide, so a result that arrives while the editor is stopped still counts: on success, with or without a launch to follow (Quick Build suppresses it), it moves the app to that session's project; on failure it drops that session's note. Only the same session's result uses a note, however long the install prompt stayed open, so two projects with the same application ID, such as two made from one template, each pair their own installs. The post-install launch does not wait for the write; the announce request above brings the app's report once the row exists. An install Code on the Go did not start from a project (an APK opened from the file tree), or one whose result arrives after Code on the Go's process restarted (notes are kept in memory), is not paired at install; `LaunchAppAction` pairs it at the next launch. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). +- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. When `ProjectHandlerActivity` installs a build, it notes the PackageInstaller session ID with the project and the APK's application ID before the session is committed. `InstallationResultReceiver` takes the result app-wide, so a result that arrives while the editor is stopped still counts: on success, with or without a launch to follow (Quick Build suppresses it), it moves the app to that session's project; on failure it drops that session's note, as `ApkInstaller`'s `onCommitFailed` does when staging or committing the session throws, since no result follows. Only the same session's result uses a note, however long the install prompt stayed open, so two projects with the same application ID, such as two made from one template, each pair their own installs. The post-install launch does not wait for the write; the announce request above brings the app's report once the row exists. An install Code on the Go did not start from a project (an APK opened from the file tree), or one whose result arrives after Code on the Go's process restarted (notes are kept in memory), is not paired at install; `LaunchAppAction` pairs it at the next launch. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). ### The event record From 95660de30ec01f4f4d894188c078859ae1819f67 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 10:23:29 -0800 Subject: [PATCH 11/21] ADFA-7137 Pair nothing on a success result that names no package InstallationResultReceiver is exported, so DebuggerEndpointRepository .confirmInstall checks the package a success result names against the noted one. A result with no EXTRA_PACKAGE_NAME passed that check and paired the noted app. The framework puts EXTRA_PACKAGE_NAME in every result it sends (PackageInstallerService.PackageInstallObserverAdapter on Android 9, PackageInstallerSession.sendOnPackageInstalled on Android 14), so such a result was not sent by it: now a missing package name pairs nothing, like a wrong one, and the note is used up. Test: DebuggerEndpointRepositoryTest "a result without a package name pairs nothing", which replaces "a result without a package name pairs the noted application ID". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../androidide/repositories/DebuggerEndpointRepository.kt | 5 +++-- .../repositories/DebuggerEndpointRepositoryTest.kt | 7 ++++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt index 3bfcffd2a5..2b01028382 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt @@ -66,14 +66,15 @@ class DebuggerEndpointRepository( * * Returns null, and writes nothing, for an install that was not noted, such as an APK opened from the file * tree; its next launch from a project pairs it. Also when [installedApplicationId], the package the result - * names, is not the noted one: the result comes through an exported receiver, so it can be forged. + * names, is missing or is not the noted one: the result comes through an exported receiver, so it can be forged, + * and the framework names the package in every result it sends. */ fun confirmInstall( sessionId: Int, installedApplicationId: String?, ): Job? { val note = pendingInstalls.remove(sessionId) ?: return null - if (installedApplicationId != null && installedApplicationId != note.applicationId) { + if (installedApplicationId != note.applicationId) { log.warn("Session {} installed {}, not {}; not paired", sessionId, installedApplicationId, note.applicationId) return null } diff --git a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt index fe28b8dcf1..d9a6c74849 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt @@ -255,15 +255,16 @@ class DebuggerEndpointRepositoryTest { } @Test - fun `a result without a package name pairs the noted application ID`() = + fun `a result without a package name pairs nothing`() = runBlocking { val dir = newProject() try { repository.notePendingInstall(1, dir, "com.example") - repository.confirmInstall(1, installedApplicationId = null)?.join() + // The framework names the package in every result it sends, so this one was forged. + assertThat(repository.confirmInstall(1, installedApplicationId = null)).isNull() - assertThat(pairedLocation()).isEqualTo(dir.canonicalPath) + assertThat(pairedLocation()).isNull() } finally { dir.delete() } From 10e4c47b3c9422bc9b0bb5684447499266b94020 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 10:23:54 -0800 Subject: [PATCH 12/21] ADFA-7137 Docs: Quick Build's installs are never paired InstallationResultReceiver's pairSqliteDebugger KDoc and the sqlite-debugger README cited Quick Build as an install whose suppressed launch still pairs. Quick Build's installs (QuickBuildModule, installApkSession with suppressPostInstallLaunch) pass no beforeCommit, so they are never noted and never pair, which is correct. Say so instead. The InstallationResultReceiverTest case "a success with the launch suppressed pairs and uses up the note" only shows that the receiver ignores the suppress-launch flag; renamed to say that. Text only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../androidide/services/InstallationResultReceiver.kt | 7 ++++--- .../androidide/services/InstallationResultReceiverTest.kt | 3 ++- subprojects/sqlite-debugger/README.md | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt b/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt index af823bf152..534c7be462 100644 --- a/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt +++ b/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt @@ -58,9 +58,10 @@ class InstallationResultReceiver : /** * Pairs the installed app with the project whose install it was, for the SQLite debugger (ADFA-7137), or drops * the install's note when it failed. Done here rather than in the editor, which receives the event only while it - * is started: the event is not sticky, and the install prompt can stop the editor. On success it pairs whether - * or not a launch follows (Quick Build suppresses it), and the event, which launches the app, is posted without - * waiting for the write. + * is started: the event is not sticky, and the install prompt can stop the editor. On success it pairs only an + * install that ProjectHandlerActivity noted, and does not read EXTRA_SUPPRESS_POST_INSTALL_LAUNCH; Quick Build's + * installs, the ones that set it, are never noted, so never paired. The event, which launches the app, is posted + * without waiting for the write. */ private fun pairSqliteDebugger(intent: Intent) { try { diff --git a/app/src/test/java/com/itsaky/androidide/services/InstallationResultReceiverTest.kt b/app/src/test/java/com/itsaky/androidide/services/InstallationResultReceiverTest.kt index 33314e061e..1513a5e606 100644 --- a/app/src/test/java/com/itsaky/androidide/services/InstallationResultReceiverTest.kt +++ b/app/src/test/java/com/itsaky/androidide/services/InstallationResultReceiverTest.kt @@ -125,7 +125,8 @@ class InstallationResultReceiverTest { } @Test - fun `a success with the launch suppressed pairs and uses up the note`() { + fun `the suppress-launch flag does not stop a noted success from pairing and using up the note`() { + // No install sets the flag and has a note today: Quick Build, the one that sets it, notes nothing. val repository = repository() repository.notePendingInstall(1, project, "com.example") diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 1675140cbd..516f79f558 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -23,7 +23,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `get_events`. - `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. - `EndpointBroadcast` runs once the server listens, on every process start (the port changes). It sends an explicit broadcast, action `com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT`, to `com.itsaky.androidide` with `FLAG_INCLUDE_STOPPED_PACKAGES`, carrying the token, the port and a `PendingIntent` that identifies the app. The `PendingIntent` is immutable (on API 23 and later; the flag does not exist before) and wraps an intent that is never sent: Code on the Go reads its `creatorPackage`, which the framework sets and another app cannot forge, as the app's package name. The library manifest declares `` for Code on the Go. A failure to send is logged and never thrown. Before the first send it registers a receiver at run time for `org.appdevforall.sqlitedebugger.ANNOUNCE` (exported, as Code on the Go is another app; `RECEIVER_EXPORTED` on API 33 and later), and sends the same token and port again each time it receives one. Code on the Go sends that request when it pairs the app, because it drops a report from an app it has not paired: an app that was already running then, installed some other way or started before its project was opened, would otherwise stay unknown until its process restarted. The receiver is not in the manifest, so a request never starts an app that is not running, and is not authenticated (ADFA-7131 D8): the reply goes only to Code on the Go. -- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. When `ProjectHandlerActivity` installs a build, it notes the PackageInstaller session ID with the project and the APK's application ID before the session is committed. `InstallationResultReceiver` takes the result app-wide, so a result that arrives while the editor is stopped still counts: on success, with or without a launch to follow (Quick Build suppresses it), it moves the app to that session's project; on failure it drops that session's note, as `ApkInstaller`'s `onCommitFailed` does when staging or committing the session throws, since no result follows. Only the same session's result uses a note, however long the install prompt stayed open, so two projects with the same application ID, such as two made from one template, each pair their own installs. The post-install launch does not wait for the write; the announce request above brings the app's report once the row exists. An install Code on the Go did not start from a project (an APK opened from the file tree), or one whose result arrives after Code on the Go's process restarted (notes are kept in memory), is not paired at install; `LaunchAppAction` pairs it at the next launch. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). +- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. When `ProjectHandlerActivity` installs a build, it notes the PackageInstaller session ID with the project and the APK's application ID before the session is committed. `InstallationResultReceiver` takes the result app-wide, so a result that arrives while the editor is stopped still counts: on success it moves the app to that session's project (Quick Build's installs are never noted, so they never pair); on failure it drops that session's note, as `ApkInstaller`'s `onCommitFailed` does when staging or committing the session throws, since no result follows. Only the same session's result uses a note, however long the install prompt stayed open, so two projects with the same application ID, such as two made from one template, each pair their own installs. The post-install launch does not wait for the write; the announce request above brings the app's report once the row exists. An install Code on the Go did not start from a project (an APK opened from the file tree), or one whose result arrives after Code on the Go's process restarted (notes are kept in memory), is not paired at install; `LaunchAppAction` pairs it at the next launch. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). ### The event record From 906f7d26669c2167d16387e5a41f9a87f07433bf Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 10:34:29 -0800 Subject: [PATCH 13/21] ADFA-7137 Clear an app's stored endpoint when an install from its project succeeds A paired app had reported its SQLite debugger endpoint. The user turned the SQLite debugger off for the project and ran it again: the new APK has no SQLite debugger, so it never reports, and the row kept the old process's port and token. upsertPairing cleared them only when the app moved to another project, so a reinstall from the same project left them in place, and a reader of the table (AI-Agent-MCP, through #2261) showed a red entry: "Could not reach SQLite debugger (...): Failed to connect". Found on a Galaxy Note 20. An install replaces the process, so its endpoint is dead whatever the new build contains. upsertPairing, which only a successful install noted by ProjectHandlerActivity reaches, now clears token, port and updated_at unconditionally, in the same transaction as the pairing (clearEndpoint replaces clearEndpointIfProjectDiffers). A build with the SQLite debugger reports again when it starts and in reply to the announce request. Ordering: the post-install launch does not wait for the write, so the new process can report first. The clear is in the pairing's transaction, and the announce request is sent after it commits, so an early report is cleared and then sent again in the reply, never lost. A failed install still only drops its note. LaunchAppAction's pairing (a launch replaces no APK), Quick Build (never noted) and APKs opened from the file tree (never noted) are unchanged. No schema change: token and port were already nullable. Tests, each run against this commit with upsertPairing put back to clearing only on a project change, as at 10e4c47b3 (that condition written with getByApplicationId and clearEndpoint, so the tests' ThrowingDao still compiles; no test file touched): - DebuggerEndpointRepositoryTest "an install from the same project clears the token, port and time the replaced process reported" fails: the row still holds tok-en_1, 5555, 1234. - DebuggerEndpointRepositoryTest "a report the new process sends before the install's write is cleared, then stored from its reply to the request" fails: the row still held the early report, (new-tok_2, 6666), when the request was sent. A clear moved after the request fails its other assertion: the reply is wiped and the row ends with (null, null). - InstallationResultReceiverTest "a success clears the endpoint the replaced process reported" fails: tok-en_1, 5555 remain. - RecentProjectRoomDatabaseTest "upsertPairing for the same project also clears token, port and time" (was "... keeps ...") fails the same way. - InstallationResultReceiverTest "a failure leaves the stored endpoint as it was" passes with and without this change, as it should; it fails against a mutation that clears on a failure result. "relaunching keeps the stored token and port" now relaunches (recordLaunched) instead of reinstalling. KDoc of upsertPairing, confirmInstall, recordInstalled, the entity and InstallationResultReceiver, and the sqlite-debugger README's pairing paragraph, describe the clear. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../DebuggerEndpointRepository.kt | 18 +++-- .../recentproject/DebuggerEndpoint.kt | 3 +- .../recentproject/DebuggerEndpointDao.kt | 22 +++---- .../services/InstallationResultReceiver.kt | 5 +- .../DebuggerEndpointRepositoryTest.kt | 65 +++++++++++++++++-- .../RecentProjectRoomDatabaseTest.kt | 4 +- .../InstallationResultReceiverTest.kt | 54 +++++++++++++++ subprojects/sqlite-debugger/README.md | 2 +- 8 files changed, 142 insertions(+), 31 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt index 2b01028382..b5ea855647 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt @@ -59,10 +59,11 @@ class DebuggerEndpointRepository( /** * Call when the session [sessionId] succeeded, whether or not a launch follows. If [notePendingInstall] noted it, - * pairs the app with the project that started it on the application scope, moving it from any other project, - * and returns that write; the caller need not wait for it before launching the app, which is asked to report - * again once paired. Only this session's result uses its note, however long the install took: another install - * of the same application ID, from this project or another, has its own session. + * pairs the app with the project that started it on the application scope, moving it from any other project and + * clearing the endpoint it reported before (see [recordInstalled]), and returns that write; the caller need not + * wait for it before launching the app, which is asked to report again once paired. Only this session's result + * uses its note, however long the install took: another install of the same application ID, from this project + * or another, has its own session. * * Returns null, and writes nothing, for an install that was not noted, such as an APK opened from the file * tree; its next launch from a project pairs it. Also when [installedApplicationId], the package the result @@ -90,8 +91,13 @@ class DebuggerEndpointRepository( } /** - * Moves [applicationId] to [projectLocation], clearing its token and port if the project changed, then asks the - * app to report again. Returns false when the project has no recent_project_table row yet, or the write failed. + * Moves the just-installed [applicationId] to [projectLocation] and clears its token and port, then asks the app + * to report again. Returns false when the project has no recent_project_table row yet, or the write failed. + * + * The install replaced the process that reported them, so they are dead whether or not the new build has the + * SQLite debugger: a build without it never reports again, and its row would otherwise keep a dead port. The + * clear is in the pairing's transaction, before the request: a report the new process sent before this write + * (the launch does not wait for it) is cleared, then sent again in reply to the request. */ suspend fun recordInstalled( applicationId: String, diff --git a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt index f5e6d1c1cb..fb50d6cb8d 100644 --- a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt +++ b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt @@ -8,7 +8,8 @@ import androidx.room.PrimaryKey /** * The SQLite debugger endpoint of one app built from a project (ADFA-7131). [token], [port] and - * [updatedAt] stay null until the app reports them. + * [updatedAt] stay null until the app reports them, and go back to null when Code on the Go + * installs the app from a project, until the new process reports. * * ON UPDATE CASCADE as well as ON DELETE: renaming a project rewrites its recent_project_table * location, which would otherwise be refused while foreign keys are on. diff --git a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpointDao.kt b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpointDao.kt index 4108d69cfc..9fccfb5578 100644 --- a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpointDao.kt +++ b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpointDao.kt @@ -18,21 +18,15 @@ interface DebuggerEndpointDao { projectLocation: String, ) - /** Clears what the old project's build reported, when [applicationId] moves to another project. */ - @Query( - "UPDATE debugger_endpoint_table SET token = NULL, port = NULL, updated_at = NULL " + - "WHERE application_id = :applicationId AND project_location != :projectLocation", - ) - suspend fun clearEndpointIfProjectDiffers( - applicationId: String, - projectLocation: String, - ) + /** Clears what [applicationId] reported, once an install has replaced the process that reported it. */ + @Query("UPDATE debugger_endpoint_table SET token = NULL, port = NULL, updated_at = NULL WHERE application_id = :applicationId") + suspend fun clearEndpoint(applicationId: String) /** - * Pairs [applicationId] with [projectLocation], keeping any token and port already stored - * unless the app was paired with a different project, whose build they belong to. - * Not REPLACE, which would delete the row and lose them. Two statements rather than - * ON CONFLICT DO UPDATE, which needs SQLite 3.24 and minSdk 28 ships 3.22. + * Pairs the just-installed [applicationId] with [projectLocation] and clears its token and port, + * in one transaction: the install replaced the process they came from, whichever project built + * it. Not REPLACE, which would delete the row. Statements rather than ON CONFLICT DO UPDATE, + * which needs SQLite 3.24 and minSdk 28 ships 3.22. * * Throws SQLiteConstraintException when [projectLocation] has no recent_project_table row. */ @@ -42,7 +36,7 @@ interface DebuggerEndpointDao { projectLocation: String, ) { insertPairingIfAbsent(applicationId, projectLocation) - clearEndpointIfProjectDiffers(applicationId, projectLocation) + clearEndpoint(applicationId) updatePairingLocation(applicationId, projectLocation) } diff --git a/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt b/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt index 534c7be462..da8e4534e9 100644 --- a/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt +++ b/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt @@ -56,8 +56,9 @@ class InstallationResultReceiver : } /** - * Pairs the installed app with the project whose install it was, for the SQLite debugger (ADFA-7137), or drops - * the install's note when it failed. Done here rather than in the editor, which receives the event only while it + * Pairs the installed app with the project whose install it was, for the SQLite debugger (ADFA-7137), clearing + * the endpoint the replaced process reported, or drops the install's note when it failed, which leaves the stored + * endpoint as it was. Done here rather than in the editor, which receives the event only while it * is started: the event is not sticky, and the install prompt can stop the editor. On success it pairs only an * install that ProjectHandlerActivity noted, and does not read EXTRA_SUPPRESS_POST_INSTALL_LAUNCH; Quick Build's * installs, the ones that set it, are never noted, so never paired. The event, which launches the app, is posted diff --git a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt index d9a6c74849..54ef0d5a73 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt @@ -92,7 +92,7 @@ class DebuggerEndpointRepositoryTest { repository.recordInstalled("com.example", "/p/a") repository.storeEndpoint("com.example", endpoint) - repository.recordInstalled("com.example", "/p/a") + repository.recordLaunched("com.example", "/p/a") val row = room.debuggerEndpointDao().getByApplicationId("com.example")!! assertThat(row.port).isEqualTo(5555) @@ -270,6 +270,64 @@ class DebuggerEndpointRepositoryTest { } } + @Test + fun `an install from the same project clears the token, port and time the replaced process reported`() = + runBlocking { + val dir = newProject() + try { + repository.recordInstalled("com.example", dir.canonicalPath) + repository.storeEndpoint("com.example", endpoint) + repository.notePendingInstall(1, dir, "com.example") + + // A build without the SQLite debugger never reports again, so nothing would replace the dead port. + repository.confirmInstall(1, "com.example")?.join() + + assertThat(room.debuggerEndpointDao().getByApplicationId("com.example")) + .isEqualTo(DebuggerEndpoint("com.example", dir.canonicalPath, null, null, null)) + } finally { + dir.delete() + } + } + + @Test + fun `a report the new process sends before the install's write is cleared, then stored from its reply to the request`() = + runBlocking { + val dir = newProject() + try { + repository.recordInstalled("com.example", dir.canonicalPath) + repository.storeEndpoint("com.example", endpoint) + val fresh = DebuggerEndpointValidation.Endpoint("new-tok_2", 6666) + val seenWhenAsked = CopyOnWriteArrayList>() + lateinit var replying: DebuggerEndpointRepository + replying = + DebuggerEndpointRepository( + room.debuggerEndpointDao(), + CoroutineScope(Dispatchers.IO), + clock = { 1234L }, + announce = { id -> + // The running app replies at once, the tightest case: before anything after the request runs. + runBlocking { + val row = room.debuggerEndpointDao().getByApplicationId(id) + seenWhenAsked += row?.token to row?.port + replying.storeEndpoint(id, fresh) + } + }, + ) + replying.notePendingInstall(1, dir, "com.example") + // The post-install launch does not wait for the write, so the new process can report first. + assertThat(replying.storeEndpoint("com.example", fresh)).isTrue() + + replying.confirmInstall(1, "com.example")!!.join() + + val row = room.debuggerEndpointDao().getByApplicationId("com.example")!! + assertThat(row.token to row.port).isEqualTo("new-tok_2" to 6666) + // Cleared before the request, in the pairing's write: a clear after it could wipe the reply for good. + assertThat(seenWhenAsked).containsExactly(null to null) + } finally { + dir.delete() + } + } + @Test fun `launching pairs an unpaired app`() = runBlocking { @@ -344,10 +402,7 @@ class DebuggerEndpointRepositoryTest { projectLocation: String, ): Unit = throw error() - override suspend fun clearEndpointIfProjectDiffers( - applicationId: String, - projectLocation: String, - ): Unit = throw error() + override suspend fun clearEndpoint(applicationId: String): Unit = throw error() override suspend fun upsertPairing( applicationId: String, diff --git a/app/src/test/java/com/itsaky/androidide/roomData/recentproject/RecentProjectRoomDatabaseTest.kt b/app/src/test/java/com/itsaky/androidide/roomData/recentproject/RecentProjectRoomDatabaseTest.kt index 10a0318521..41a30f1d2f 100644 --- a/app/src/test/java/com/itsaky/androidide/roomData/recentproject/RecentProjectRoomDatabaseTest.kt +++ b/app/src/test/java/com/itsaky/androidide/roomData/recentproject/RecentProjectRoomDatabaseTest.kt @@ -209,7 +209,7 @@ class RecentProjectRoomDatabaseTest { } @Test - fun `upsertPairing for the same project keeps token, port and time`() = + fun `upsertPairing for the same project also clears token, port and time`() = runBlocking { val room = newDatabase() try { @@ -221,7 +221,7 @@ class RecentProjectRoomDatabaseTest { dao.upsertPairing("com.example.one", "/p/a") assertThat(dao.getByApplicationId("com.example.one")) - .isEqualTo(DebuggerEndpoint("com.example.one", "/p/a", "tok", 4242, 99L)) + .isEqualTo(DebuggerEndpoint("com.example.one", "/p/a", null, null, null)) } finally { room.close() } diff --git a/app/src/test/java/com/itsaky/androidide/services/InstallationResultReceiverTest.kt b/app/src/test/java/com/itsaky/androidide/services/InstallationResultReceiverTest.kt index 1513a5e606..67d1491e2b 100644 --- a/app/src/test/java/com/itsaky/androidide/services/InstallationResultReceiverTest.kt +++ b/app/src/test/java/com/itsaky/androidide/services/InstallationResultReceiverTest.kt @@ -11,10 +11,13 @@ import com.itsaky.androidide.repositories.DebuggerEndpointRepository import com.itsaky.androidide.roomData.recentproject.DebuggerEndpointDao import com.itsaky.androidide.roomData.recentproject.RecentProject import com.itsaky.androidide.roomData.recentproject.RecentProjectRoomDatabase +import com.itsaky.androidide.sqlitedebugger.DebuggerEndpointValidation import com.itsaky.androidide.utils.ApkInstaller import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.joinAll import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.greenrobot.eventbus.EventBus @@ -149,6 +152,57 @@ class InstallationResultReceiverTest { assertThat(repository.confirmInstall(2, "com.example")).isNotNull() } + /** Parent of the writes of a repository built with [writesScope], so a test can wait for all of them. */ + private val writes = SupervisorJob() + private val writesScope = CoroutineScope(Dispatchers.IO + writes) + + private fun awaitWrites() = runBlocking { writes.children.toList().joinAll() } + + /** Pairs com.example with the project and stores the endpoint its running build reported. */ + private fun pairWithReportedEndpoint(repository: DebuggerEndpointRepository) = + runBlocking { + assertThat(repository.recordInstalled("com.example", project.canonicalPath)).isTrue() + assertThat(repository.storeEndpoint("com.example", DebuggerEndpointValidation.Endpoint("tok-en_1", 5555))).isTrue() + } + + private fun storedEndpoint(): Pair = + runBlocking { room.debuggerEndpointDao().getByApplicationId("com.example")!! }.let { it.token to it.port } + + @Test + fun `a success clears the endpoint the replaced process reported`() { + val repository = repository(scope = writesScope) + pairWithReportedEndpoint(repository) + repository.notePendingInstall(1, project, "com.example") + + deliver(1, PackageInstaller.STATUS_SUCCESS) + awaitWrites() + + assertThat(storedEndpoint()).isEqualTo(null to null) + } + + @Test + fun `a failure leaves the stored endpoint as it was`() { + val repository = repository(scope = writesScope) + pairWithReportedEndpoint(repository) + val failures = + listOf( + PackageInstaller.STATUS_FAILURE, + PackageInstaller.STATUS_FAILURE_ABORTED, + PackageInstaller.STATUS_FAILURE_BLOCKED, + PackageInstaller.STATUS_FAILURE_CONFLICT, + PackageInstaller.STATUS_FAILURE_INCOMPATIBLE, + PackageInstaller.STATUS_FAILURE_INVALID, + PackageInstaller.STATUS_FAILURE_STORAGE, + ) + failures.indices.forEach { repository.notePendingInstall(it + 1, project, "com.example") } + + // The old APK, and the process that reported, are still there. + failures.forEachIndexed { i, status -> deliver(i + 1, status) } + awaitWrites() + + assertThat(storedEndpoint()).isEqualTo("tok-en_1" to 5555) + } + @Test fun `the event that launches the app is posted before a slow pairing write finishes`() { val release = CountDownLatch(1) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 516f79f558..f689358879 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -23,7 +23,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `get_events`. - `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. - `EndpointBroadcast` runs once the server listens, on every process start (the port changes). It sends an explicit broadcast, action `com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT`, to `com.itsaky.androidide` with `FLAG_INCLUDE_STOPPED_PACKAGES`, carrying the token, the port and a `PendingIntent` that identifies the app. The `PendingIntent` is immutable (on API 23 and later; the flag does not exist before) and wraps an intent that is never sent: Code on the Go reads its `creatorPackage`, which the framework sets and another app cannot forge, as the app's package name. The library manifest declares `` for Code on the Go. A failure to send is logged and never thrown. Before the first send it registers a receiver at run time for `org.appdevforall.sqlitedebugger.ANNOUNCE` (exported, as Code on the Go is another app; `RECEIVER_EXPORTED` on API 33 and later), and sends the same token and port again each time it receives one. Code on the Go sends that request when it pairs the app, because it drops a report from an app it has not paired: an app that was already running then, installed some other way or started before its project was opened, would otherwise stay unknown until its process restarted. The receiver is not in the manifest, so a request never starts an app that is not running, and is not authenticated (ADFA-7131 D8): the reply goes only to Code on the Go. -- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. When `ProjectHandlerActivity` installs a build, it notes the PackageInstaller session ID with the project and the APK's application ID before the session is committed. `InstallationResultReceiver` takes the result app-wide, so a result that arrives while the editor is stopped still counts: on success it moves the app to that session's project (Quick Build's installs are never noted, so they never pair); on failure it drops that session's note, as `ApkInstaller`'s `onCommitFailed` does when staging or committing the session throws, since no result follows. Only the same session's result uses a note, however long the install prompt stayed open, so two projects with the same application ID, such as two made from one template, each pair their own installs. The post-install launch does not wait for the write; the announce request above brings the app's report once the row exists. An install Code on the Go did not start from a project (an APK opened from the file tree), or one whose result arrives after Code on the Go's process restarted (notes are kept in memory), is not paired at install; `LaunchAppAction` pairs it at the next launch. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). +- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. When `ProjectHandlerActivity` installs a build, it notes the PackageInstaller session ID with the project and the APK's application ID before the session is committed. `InstallationResultReceiver` takes the result app-wide, so a result that arrives while the editor is stopped still counts: on success it moves the app to that session's project and clears the token and port it reported, in the same write (Quick Build's installs are never noted, so they never pair); on failure it drops that session's note, as `ApkInstaller`'s `onCommitFailed` does when staging or committing the session throws, since no result follows, and leaves the stored endpoint as it was. The install replaced the process that reported the endpoint, so the endpoint is dead whether or not the new build has the SQLite debugger: a build without it, made after the SQLite debugger was turned off for the project, never reports again, and its row would otherwise keep a dead port. A report the new process sent before the write is cleared too, and sent again in reply to the announce request that follows the write. Only the same session's result uses a note, however long the install prompt stayed open, so two projects with the same application ID, such as two made from one template, each pair their own installs. The post-install launch does not wait for the write; the announce request above brings the app's report once the row exists. An install Code on the Go did not start from a project (an APK opened from the file tree), or one whose result arrives after Code on the Go's process restarted (notes are kept in memory), is not paired at install; `LaunchAppAction` pairs it at the next launch. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). ### The event record From 085eb15a04aa7ae0d22dd364b8988a531033e0ac Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 13:24:40 -0800 Subject: [PATCH 14/21] ADFA-7137 Rethrow an install's cancellation, and let a VirtualMachineError from its callbacks crash ApkInstaller.installUsingSession wraps the session work in runCatching, which caught the CancellationException that withContext throws when the caller is cancelled: a cancelled install was logged as "Package installation failed" and reported as Failed. The fold now rethrows it. The session may be committed by then (the IO block never checks for cancellation), and it reports its result as usual. beforeCommit and onCommitFailed ran in runCatching too, which catches Throwable. They now catch Exception and LinkageError, the stack's rule, and the fold rethrows a VirtualMachineError, so an OutOfMemoryError crashes by design instead of becoming a warning. The fold's rethrow also covers a VirtualMachineError from staging, which was reported as Failed before this PR: narrowing only the callbacks would change nothing, since the session block's catch rethrows to the fold. Tests (ApkInstallerSessionTest): "a cancelled install is neither reported as Failed nor logged as an error"; "an Exception from beforeCommit is logged and the install goes on, while an OutOfMemoryError propagates". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../itsaky/androidide/utils/ApkInstaller.kt | 40 ++++++--- .../utils/ApkInstallerSessionTest.kt | 84 +++++++++++++++++++ 2 files changed, 114 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt index 6ba715f740..9e63c2e40c 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt @@ -11,6 +11,7 @@ import androidx.core.app.PendingIntentCompat import com.itsaky.androidide.actions.build.DebugAction import com.itsaky.androidide.buildinfo.BuildInfo import com.itsaky.androidide.services.InstallationResultReceiver +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.slf4j.LoggerFactory @@ -105,11 +106,13 @@ object ApkInstaller { * launch-after-install behavior; see [EXTRA_SUPPRESS_POST_INSTALL_LAUNCH]. * @param beforeCommit called with the session ID on an IO thread once the APK is staged, just before the session * is committed, so whatever it records is in place when the result arrives. Not called by the intent-based - * fallback installer, which has no session and reports no result. What it throws is logged, and the install - * goes on. + * fallback installer, which has no session and reports no result. An Exception or LinkageError it throws is + * logged, and the install goes on; a VirtualMachineError such as OutOfMemoryError propagates. * @param onCommitFailed called with the session ID on the same IO thread when staging or committing the session * threw. The session is abandoned and reports no result, so this is where to drop what [beforeCommit] recorded. - * What it throws is logged. + * An Exception or LinkageError it throws is logged; a VirtualMachineError propagates. + * @throws CancellationException when the calling coroutine is cancelled, rather than returning a failure. The + * session may be committed by then, and then reports its result as usual. */ @JvmStatic suspend fun installApk( @@ -134,7 +137,8 @@ object ApkInstaller { /** * Starts a session-based package installation workflow and returns a [SessionLaunchResult] * with the committed `sessionId` (or a distinct [SessionLaunchResult.TooManySessions] - * when the UID's active session quota is exhausted). [beforeCommit] and [onCommitFailed] are as for [installApk]. + * when the UID's active session quota is exhausted). [beforeCommit], [onCommitFailed] and cancellation are as for + * [installApk]. */ @JvmStatic suspend fun installApkSession( @@ -504,15 +508,11 @@ object ApkInstaller { "PackageInstaller callback intent is null" } addToSession(session, apk) - beforeCommit?.let { record -> - runCatching { record(sessionId) }.onFailure { log.warn("beforeCommit failed for session {}", sessionId, it) } - } + beforeCommit?.let { record -> runCallback("beforeCommit", sessionId) { record(sessionId) } } session.commit(callback.intentSender) sessionId } catch (t: Throwable) { - onCommitFailed?.let { forget -> - runCatching { forget(sessionId) }.onFailure { log.warn("onCommitFailed failed for session {}", sessionId, it) } - } + onCommitFailed?.let { forget -> runCallback("onCommitFailed", sessionId) { forget(sessionId) } } abandonSession(context, sessionId) throw t } finally { @@ -522,6 +522,8 @@ object ApkInstaller { }.fold( onSuccess = { sessionId -> SessionLaunchResult.Started(sessionId) }, onFailure = { error -> + // Cancellation is not a failed install, and a VirtualMachineError, from a callback or not, crashes by design. + if (error is CancellationException || error is VirtualMachineError) throw error log.error("Package installation failed", error) if (isTooManyActiveSessions(error)) { SessionLaunchResult.TooManySessions @@ -532,6 +534,24 @@ object ApkInstaller { ) } + /** + * Runs a caller's [callback] for [sessionId], logging an Exception or LinkageError it throws. Anything else, such + * as an OutOfMemoryError, propagates. + */ + private inline fun runCallback( + name: String, + sessionId: Int, + callback: () -> Unit, + ) { + try { + callback() + } catch (e: Exception) { + log.warn("{} failed for session {}", name, sessionId, e) + } catch (e: LinkageError) { + log.warn("{} failed for session {}", name, sessionId, e) + } + } + /** * Returns `true` when [error] or any cause in its chain is the `IllegalStateException` * thrown by Android's `PackageInstallerService` when the per-UID session cap is reached. diff --git a/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt b/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt index 1783818582..9887241cb1 100644 --- a/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt +++ b/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt @@ -6,10 +6,13 @@ import android.content.Intent import android.content.pm.PackageInstaller import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.logging.provider.IdeLogRouter import io.mockk.every import io.mockk.justRun import io.mockk.mockk import io.mockk.spyk +import kotlinx.coroutines.job +import kotlinx.coroutines.launch import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Before @@ -19,7 +22,9 @@ import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config +import org.slf4j.event.Level import java.io.ByteArrayOutputStream +import java.util.concurrent.CopyOnWriteArrayList @RunWith(RobolectricTestRunner::class) @Config(application = Application::class) @@ -322,6 +327,85 @@ class ApkInstallerSessionTest { assertThat(notes).isEmpty() } + /** A context whose PackageInstaller creates session [id], whose commit succeeds and whose abandon is recorded. */ + private fun committingContext( + id: Int, + abandoned: MutableList, + ): Context { + val session = mockk(relaxed = true) + every { session.openWrite(any(), any(), any()) } returns ByteArrayOutputStream() + val installer = mockk() + every { installer.createSession(any()) } returns id + every { installer.openSession(id) } returns session + every { installer.abandonSession(id) } answers { abandoned += id } + val baseContext = ApplicationProvider.getApplicationContext() + val pm = spyk(baseContext.packageManager) + every { pm.packageInstaller } returns installer + return spyk(baseContext).also { every { it.packageManager } returns pm } + } + + @Test + fun `a cancelled install is neither reported as Failed nor logged as an error`() = + runTest { + val apk = tempFolder.newFile("app-debug.apk").apply { writeBytes(byteArrayOf(1, 2, 3, 4)) } + val context = committingContext(400, mutableListOf()) + val errors = CopyOnWriteArrayList() + val sink = + IdeLogRouter.ExternalSink { level, loggerName, message, _ -> + if (level == Level.ERROR && loggerName == ApkInstaller::class.java.name) errors += message + } + var result: ApkInstaller.SessionLaunchResult? = null + + IdeLogRouter.addSink(sink) + try { + val install = + launch { + val job = coroutineContext.job + // The caller goes away while the session is staged, as when the editor closes mid-install. + result = ApkInstaller.installUsingSession(context, apk, Intent(), beforeCommit = { job.cancel() }) + } + install.join() + assertThat(install.isCancelled).isTrue() + } finally { + IdeLogRouter.removeSink(sink) + } + + assertThat(result).isNull() + assertThat(errors).isEmpty() + } + + @Test + fun `an Exception from beforeCommit is logged and the install goes on, while an OutOfMemoryError propagates`() = + runTest { + val apk = tempFolder.newFile("app-debug.apk").apply { writeBytes(byteArrayOf(1, 2, 3, 4)) } + val abandoned = mutableListOf() + + val goesOn = + ApkInstaller.installUsingSession( + committingContext(500, abandoned), + apk, + Intent(), + beforeCommit = { throw IllegalStateException("note refused") }, + ) + assertThat(goesOn).isEqualTo(ApkInstaller.SessionLaunchResult.Started(500)) + + val forgotten = mutableListOf() + val thrown = + runCatching { + ApkInstaller.installUsingSession( + committingContext(501, abandoned), + apk, + Intent(), + beforeCommit = { throw OutOfMemoryError("note") }, + onCommitFailed = { forgotten += it }, + ) + }.exceptionOrNull() + assertThat(thrown).isInstanceOf(OutOfMemoryError::class.java) + // Cleaned up on the way out, as for any other failure. + assertThat(forgotten).containsExactly(501) + assertThat(abandoned).containsExactly(501) + } + @Test fun `abandonSession retains tracking when abandonment throws and session is not finalized`() = runTest { From b850ede411bebafaf70ad95400b4cf1320997e1c Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 13:24:41 -0800 Subject: [PATCH 15/21] ADFA-7137 Keep the install note for the real result when a success names another package DebuggerEndpointRepository.confirmInstall removed the session's note before it checked the package the result names. A success naming another package, or none, forged through the exported InstallationResultReceiver, used up the note: the real success then paired nothing, and the app was paired only at its next launch. The check now comes first, and the note is removed with remove(sessionId, note), so of two results that pass it only the first pairs. The KDoc said the framework names the package in every result it sends. That is now labelled unverified: ProxyAppInstallerEdgeTest says some OEM installers omit EXTRA_PACKAGE_NAME. A real success without it leaves the note unused, and the app is paired at its next launch from its project. Not changed: a forged failure result still drops the note (InstallationResultReceiver's else branch). A package check cannot stop that, since a forger can omit the package and real failures often carry none (ProxyAppInstaller's InstallBroadcast KDoc); the cost is the same, pairing at the next launch. Tests (DebuggerEndpointRepositoryTest): "a result naming another package leaves the note, so the session's real result still pairs" (new); "a result without a package name pairs nothing, and leaves the note for the real result" (was "a result without a package name pairs nothing"). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../DebuggerEndpointRepository.kt | 14 +++++++--- .../DebuggerEndpointRepositoryTest.kt | 26 ++++++++++++++++--- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt index b5ea855647..b887d83912 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt @@ -40,7 +40,8 @@ class DebuggerEndpointRepository( * loses them all, and each app is then paired by its next launch from its project (LaunchAppAction). Nothing * expires, so a slow install still finds its note. A session whose staging or commit throws reports no result, * so ApkInstaller's onCommitFailed drops its note through [discardPendingInstall]; a note whose session never - * reports for another reason stays unused until the process ends: session IDs are not reused. + * reports for another reason, or whose real success result names another package or none (see [confirmInstall]), + * stays unused until the process ends: session IDs are not reused. */ private val pendingInstalls = ConcurrentHashMap() @@ -67,18 +68,23 @@ class DebuggerEndpointRepository( * * Returns null, and writes nothing, for an install that was not noted, such as an APK opened from the file * tree; its next launch from a project pairs it. Also when [installedApplicationId], the package the result - * names, is missing or is not the noted one: the result comes through an exported receiver, so it can be forged, - * and the framework names the package in every result it sends. + * names, is missing or is not the noted one: the result comes through an exported receiver, so it can be forged. + * Such a result leaves the note, so the session's real result still pairs. Unverified: that the framework names + * the package in every success result. AOSP's PackageInstallerSession.sendOnPackageInstalled is said to, and + * ProxyAppInstallerEdgeTest says some OEM installers do not; a real success that names none is paired at the + * app's next launch from its project instead. */ fun confirmInstall( sessionId: Int, installedApplicationId: String?, ): Job? { - val note = pendingInstalls.remove(sessionId) ?: return null + val note = pendingInstalls[sessionId] ?: return null if (installedApplicationId != note.applicationId) { log.warn("Session {} installed {}, not {}; not paired", sessionId, installedApplicationId, note.applicationId) return null } + // Of two results that both pass the check, only the first pairs. + if (!pendingInstalls.remove(sessionId, note)) return null return scope.launch { recordInstalled(note.applicationId, note.location) } } diff --git a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt index 54ef0d5a73..c32dbb2b60 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt @@ -255,16 +255,36 @@ class DebuggerEndpointRepositoryTest { } @Test - fun `a result without a package name pairs nothing`() = + fun `a result naming another package leaves the note, so the session's real result still pairs`() = runBlocking { val dir = newProject() try { repository.notePendingInstall(1, dir, "com.example") - // The framework names the package in every result it sends, so this one was forged. - assertThat(repository.confirmInstall(1, installedApplicationId = null)).isNull() + // Forged: the receiver is exported. + assertThat(repository.confirmInstall(1, "com.other")).isNull() + repository.confirmInstall(1, "com.example")?.join() + + assertThat(pairedLocation("com.example")).isEqualTo(dir.canonicalPath) + assertThat(pairedLocation("com.other")).isNull() + } finally { + dir.delete() + } + } + @Test + fun `a result without a package name pairs nothing, and leaves the note for the real result`() = + runBlocking { + val dir = newProject() + try { + repository.notePendingInstall(1, dir, "com.example") + + // Forged, or from an installer that names no package; see confirmInstall. + assertThat(repository.confirmInstall(1, installedApplicationId = null)).isNull() assertThat(pairedLocation()).isNull() + + repository.confirmInstall(1, "com.example")?.join() + assertThat(pairedLocation()).isEqualTo(dir.canonicalPath) } finally { dir.delete() } From f7efd3c67f6c8bac3bbd3a351364563fd4d12eca Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 23:10:10 -0800 Subject: [PATCH 16/21] ADFA-7137 Let a VirtualMachineError out of apkApplicationId and canonicalProjectLocation Both helpers wrapped their call in runCatching, so an OutOfMemoryError was logged (or silently replaced by the absolute path) on the paths the install note and the pairing depend on. They now catch only Exception and LinkageError, with the same fallback and logging, like the rest of the stack. apkApplicationId becomes internal so a test can reach it. Callers checked: apkApplicationId is used by the install-time clobber check and the beforeCommit note, both inside paths that rethrow a VirtualMachineError (ApkInstaller.runCallback and its fold). canonicalProjectLocation callers only use the returned string; none catches an Error. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../editor/ProjectHandlerActivity.kt | 25 +++++++--- .../androidide/utils/ProjectLocation.kt | 15 +++++- .../activities/editor/ApkApplicationIdTest.kt | 49 +++++++++++++++++++ .../androidide/utils/ProjectLocationTest.kt | 33 +++++++++++++ 4 files changed, 114 insertions(+), 8 deletions(-) create mode 100644 app/src/test/java/com/itsaky/androidide/activities/editor/ApkApplicationIdTest.kt diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt index eecc8e19c3..00ec7588b6 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt @@ -286,14 +286,27 @@ abstract class ProjectHandlerActivity : private const val PLUGIN_SEARCH_TIMEOUT_SECONDS = 10L - private fun apkApplicationId( + /** + * Reads the applicationId from the archive, or null when it cannot be read. Catches only + * [Exception] and [LinkageError], like the rest of the plugin stack, so a VirtualMachineError + * (OutOfMemoryError while the package manager parses the APK) still crashes. + */ + internal fun apkApplicationId( packageManager: PackageManager, apk: File, - ): String? = - runCatching { packageManager.getPackageArchiveInfo(apk.absolutePath, 0)?.packageName } - .onFailure { logger.warn("Could not read the applicationId of {}", apk, it) } - .getOrNull() - ?.takeIf { it.isNotBlank() } + ): String? { + val packageName = + try { + packageManager.getPackageArchiveInfo(apk.absolutePath, 0)?.packageName + } catch (e: Exception) { + logger.warn("Could not read the applicationId of {}", apk, e) + null + } catch (e: LinkageError) { + logger.warn("Could not read the applicationId of {}", apk, e) + null + } + return packageName?.takeIf { it.isNotBlank() } + } } abstract fun doCloseAll() diff --git a/app/src/main/java/com/itsaky/androidide/utils/ProjectLocation.kt b/app/src/main/java/com/itsaky/androidide/utils/ProjectLocation.kt index 66d7089577..7fcadeb80a 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/ProjectLocation.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/ProjectLocation.kt @@ -19,8 +19,19 @@ package com.itsaky.androidide.utils import java.io.File -/** Returns a stable path for identifying the same project across app entry points. */ -internal fun File.canonicalProjectLocation(): String = runCatching { canonicalPath }.getOrElse { absolutePath } +/** + * Returns a stable path for identifying the same project across app entry points, or the absolute path + * when the canonical one cannot be resolved. Catches only [Exception] and [LinkageError], so a + * VirtualMachineError still crashes. + */ +internal fun File.canonicalProjectLocation(): String = + try { + canonicalPath + } catch (e: Exception) { + absolutePath + } catch (e: LinkageError) { + absolutePath + } internal fun File.isDeletedProjectDirectory(): Boolean { val parent = parentFile ?: return false diff --git a/app/src/test/java/com/itsaky/androidide/activities/editor/ApkApplicationIdTest.kt b/app/src/test/java/com/itsaky/androidide/activities/editor/ApkApplicationIdTest.kt new file mode 100644 index 0000000000..6e052bc12e --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/activities/editor/ApkApplicationIdTest.kt @@ -0,0 +1,49 @@ +package com.itsaky.androidide.activities.editor + +import android.app.Application +import android.content.pm.PackageInfo +import android.content.pm.PackageManager +import com.google.common.truth.Truth.assertThat +import io.mockk.every +import io.mockk.mockk +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@Config(application = Application::class) +class ApkApplicationIdTest { + private val apk = File("/tmp/app-debug.apk") + + private fun managerThrowing(error: Throwable): PackageManager = + mockk { every { getPackageArchiveInfo(any(), any()) } throws error } + + @Test + fun `returns the package name the archive declares`() { + val info = PackageInfo().apply { packageName = "com.example.app" } + val manager = mockk { every { getPackageArchiveInfo(any(), any()) } returns info } + + assertThat(ProjectHandlerActivity.apkApplicationId(manager, apk)).isEqualTo("com.example.app") + } + + @Test + fun `an Exception from the parse gives null`() { + assertThat(ProjectHandlerActivity.apkApplicationId(managerThrowing(IllegalStateException("bad apk")), apk)).isNull() + } + + @Test + fun `a LinkageError from the parse gives null`() { + assertThat(ProjectHandlerActivity.apkApplicationId(managerThrowing(NoClassDefFoundError("missing")), apk)).isNull() + } + + @Test + fun `an OutOfMemoryError from the parse propagates`() { + val thrown = + runCatching { ProjectHandlerActivity.apkApplicationId(managerThrowing(OutOfMemoryError("test")), apk) } + .exceptionOrNull() + + assertThat(thrown).isInstanceOf(OutOfMemoryError::class.java) + } +} diff --git a/app/src/test/java/com/itsaky/androidide/utils/ProjectLocationTest.kt b/app/src/test/java/com/itsaky/androidide/utils/ProjectLocationTest.kt index f4a228a255..2f3577abb8 100644 --- a/app/src/test/java/com/itsaky/androidide/utils/ProjectLocationTest.kt +++ b/app/src/test/java/com/itsaky/androidide/utils/ProjectLocationTest.kt @@ -5,6 +5,7 @@ import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import java.io.File +import java.io.IOException import java.nio.file.Files class ProjectLocationTest { @@ -25,4 +26,36 @@ class ProjectLocationTest { assertThat(createPath.canonicalProjectLocation()).isEqualTo(openPath.canonicalProjectLocation()) } + + @Test + fun `an Exception from canonicalPath falls back to the absolute path`() { + val file = + object : File(tempFolder.root, "MyApp") { + override fun getCanonicalPath(): String = throw IOException("cannot resolve") + } + + assertThat(file.canonicalProjectLocation()).isEqualTo(file.absolutePath) + } + + @Test + fun `a LinkageError from canonicalPath falls back to the absolute path`() { + val file = + object : File(tempFolder.root, "MyApp") { + override fun getCanonicalPath(): String = throw NoClassDefFoundError("missing") + } + + assertThat(file.canonicalProjectLocation()).isEqualTo(file.absolutePath) + } + + @Test + fun `an OutOfMemoryError from canonicalPath propagates`() { + val file = + object : File(tempFolder.root, "MyApp") { + override fun getCanonicalPath(): String = throw OutOfMemoryError("test") + } + + val thrown = runCatching { file.canonicalProjectLocation() }.exceptionOrNull() + + assertThat(thrown).isInstanceOf(OutOfMemoryError::class.java) + } } From ea44b03c9706cc2961094234e502072977188a6e Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 23:10:16 -0800 Subject: [PATCH 17/21] ADFA-7137 Docs: narrow the endpoint-clearing claim to what the code does Only a Run install from ProjectHandlerActivity whose success result names the package, and arrives in the same Code on the Go process, clears the stored token and port. Name the three installs that keep them until the app reports again: Quick Build, a success with no package name, and a result after a restart. Docs only. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../androidide/roomData/recentproject/DebuggerEndpoint.kt | 8 ++++++-- subprojects/sqlite-debugger/README.md | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt index fb50d6cb8d..5b9d7f794d 100644 --- a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt +++ b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt @@ -8,8 +8,12 @@ import androidx.room.PrimaryKey /** * The SQLite debugger endpoint of one app built from a project (ADFA-7131). [token], [port] and - * [updatedAt] stay null until the app reports them, and go back to null when Code on the Go - * installs the app from a project, until the new process reports. + * [updatedAt] stay null until the app reports them. They go back to null only when a Run install + * from ProjectHandlerActivity succeeds, its result names the package, and it arrives in the same + * Code on the Go process. Three installs keep the old token and port until the app reports again: + * a Quick Build install (the proxy app, installed under the project's application ID, writes no + * install note), a success result with no package name, and a result that arrives after Code on + * the Go restarted. LaunchAppAction pairs the last two later and keeps the stored values. * * ON UPDATE CASCADE as well as ON DELETE: renaming a project rewrites its recent_project_table * location, which would otherwise be refused while foreign keys are on. diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index f689358879..f9012b9729 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -23,7 +23,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `get_events`. - `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. - `EndpointBroadcast` runs once the server listens, on every process start (the port changes). It sends an explicit broadcast, action `com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT`, to `com.itsaky.androidide` with `FLAG_INCLUDE_STOPPED_PACKAGES`, carrying the token, the port and a `PendingIntent` that identifies the app. The `PendingIntent` is immutable (on API 23 and later; the flag does not exist before) and wraps an intent that is never sent: Code on the Go reads its `creatorPackage`, which the framework sets and another app cannot forge, as the app's package name. The library manifest declares `` for Code on the Go. A failure to send is logged and never thrown. Before the first send it registers a receiver at run time for `org.appdevforall.sqlitedebugger.ANNOUNCE` (exported, as Code on the Go is another app; `RECEIVER_EXPORTED` on API 33 and later), and sends the same token and port again each time it receives one. Code on the Go sends that request when it pairs the app, because it drops a report from an app it has not paired: an app that was already running then, installed some other way or started before its project was opened, would otherwise stay unknown until its process restarted. The receiver is not in the manifest, so a request never starts an app that is not running, and is not authenticated (ADFA-7131 D8): the reply goes only to Code on the Go. -- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. When `ProjectHandlerActivity` installs a build, it notes the PackageInstaller session ID with the project and the APK's application ID before the session is committed. `InstallationResultReceiver` takes the result app-wide, so a result that arrives while the editor is stopped still counts: on success it moves the app to that session's project and clears the token and port it reported, in the same write (Quick Build's installs are never noted, so they never pair); on failure it drops that session's note, as `ApkInstaller`'s `onCommitFailed` does when staging or committing the session throws, since no result follows, and leaves the stored endpoint as it was. The install replaced the process that reported the endpoint, so the endpoint is dead whether or not the new build has the SQLite debugger: a build without it, made after the SQLite debugger was turned off for the project, never reports again, and its row would otherwise keep a dead port. A report the new process sent before the write is cleared too, and sent again in reply to the announce request that follows the write. Only the same session's result uses a note, however long the install prompt stayed open, so two projects with the same application ID, such as two made from one template, each pair their own installs. The post-install launch does not wait for the write; the announce request above brings the app's report once the row exists. An install Code on the Go did not start from a project (an APK opened from the file tree), or one whose result arrives after Code on the Go's process restarted (notes are kept in memory), is not paired at install; `LaunchAppAction` pairs it at the next launch. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). +- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. When `ProjectHandlerActivity` installs a build, it notes the PackageInstaller session ID with the project and the APK's application ID before the session is committed. `InstallationResultReceiver` takes the result app-wide, so a result that arrives while the editor is stopped still counts: on a success whose result names the noted package, and that arrives in the same Code on the Go process, it moves the app to that session's project and clears the token and port it reported, in the same write; on failure it drops that session's note, as `ApkInstaller`'s `onCommitFailed` does when staging or committing the session throws, since no result follows, and leaves the stored endpoint as it was. For those installs the endpoint is dead whether or not the new build has the SQLite debugger, because the install replaced the process that reported it: a build without it, made after the SQLite debugger was turned off for the project, never reports again, and its row would otherwise keep a dead port. A report the new process sent before the write is cleared too, and sent again in reply to the announce request that follows the write. Only the same session's result uses a note, however long the install prompt stayed open, so two projects with the same application ID, such as two made from one template, each pair their own installs. The post-install launch does not wait for the write; the announce request above brings the app's report once the row exists. Three installs from a project keep the old token and port until the app reports again, because nothing clears them: (a) a Quick Build install, which installs the proxy app under the project's application ID and never writes a note; (b) a success result with no `EXTRA_PACKAGE_NAME`, which cannot be checked against the note; (c) a result that arrives after Code on the Go's process restarted (notes are kept in memory). `LaunchAppAction` pairs (b) and (c) at the next launch, through `insertPairingIfAbsent`, which keeps the stored values; an app whose old process is gone stays unreachable until its new process reports. An install Code on the Go did not start from a project (an APK opened from the file tree) is not paired at install either; `LaunchAppAction` pairs it at the next launch. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). ### The event record From 3dfb5f4ef6c7fe8adcc1ead8496a9318d781c939 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 16:22:25 -0800 Subject: [PATCH 18/21] ADFA-7137 Docs: the list of installs that keep the old endpoint is five, not three A Run install with no project open, and one whose APK's application ID cannot be read, also write no install note, so they keep the stored token and port like the Quick Build, no-package-name and after-restart cases. Name both in the DebuggerEndpoint KDoc and the SQLite debugger README. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../androidide/roomData/recentproject/DebuggerEndpoint.kt | 8 +++++--- subprojects/sqlite-debugger/README.md | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt index 5b9d7f794d..d339b5cc0d 100644 --- a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt +++ b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt @@ -10,10 +10,12 @@ import androidx.room.PrimaryKey * The SQLite debugger endpoint of one app built from a project (ADFA-7131). [token], [port] and * [updatedAt] stay null until the app reports them. They go back to null only when a Run install * from ProjectHandlerActivity succeeds, its result names the package, and it arrives in the same - * Code on the Go process. Three installs keep the old token and port until the app reports again: + * Code on the Go process. Some installs keep the old token and port until the app reports again: * a Quick Build install (the proxy app, installed under the project's application ID, writes no - * install note), a success result with no package name, and a result that arrives after Code on - * the Go restarted. LaunchAppAction pairs the last two later and keeps the stored values. + * install note), a Run install with no project open, a Run install whose APK's application ID + * cannot be read (neither writes an install note), a success result with no package name, and a + * result that arrives after Code on the Go restarted. LaunchAppAction pairs the last four at the + * next launch from a project and keeps the stored values. * * ON UPDATE CASCADE as well as ON DELETE: renaming a project rewrites its recent_project_table * location, which would otherwise be refused while foreign keys are on. diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index f9012b9729..65782373e8 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -23,7 +23,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `get_events`. - `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. - `EndpointBroadcast` runs once the server listens, on every process start (the port changes). It sends an explicit broadcast, action `com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT`, to `com.itsaky.androidide` with `FLAG_INCLUDE_STOPPED_PACKAGES`, carrying the token, the port and a `PendingIntent` that identifies the app. The `PendingIntent` is immutable (on API 23 and later; the flag does not exist before) and wraps an intent that is never sent: Code on the Go reads its `creatorPackage`, which the framework sets and another app cannot forge, as the app's package name. The library manifest declares `` for Code on the Go. A failure to send is logged and never thrown. Before the first send it registers a receiver at run time for `org.appdevforall.sqlitedebugger.ANNOUNCE` (exported, as Code on the Go is another app; `RECEIVER_EXPORTED` on API 33 and later), and sends the same token and port again each time it receives one. Code on the Go sends that request when it pairs the app, because it drops a report from an app it has not paired: an app that was already running then, installed some other way or started before its project was opened, would otherwise stay unknown until its process restarted. The receiver is not in the manifest, so a request never starts an app that is not running, and is not authenticated (ADFA-7131 D8): the reply goes only to Code on the Go. -- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. When `ProjectHandlerActivity` installs a build, it notes the PackageInstaller session ID with the project and the APK's application ID before the session is committed. `InstallationResultReceiver` takes the result app-wide, so a result that arrives while the editor is stopped still counts: on a success whose result names the noted package, and that arrives in the same Code on the Go process, it moves the app to that session's project and clears the token and port it reported, in the same write; on failure it drops that session's note, as `ApkInstaller`'s `onCommitFailed` does when staging or committing the session throws, since no result follows, and leaves the stored endpoint as it was. For those installs the endpoint is dead whether or not the new build has the SQLite debugger, because the install replaced the process that reported it: a build without it, made after the SQLite debugger was turned off for the project, never reports again, and its row would otherwise keep a dead port. A report the new process sent before the write is cleared too, and sent again in reply to the announce request that follows the write. Only the same session's result uses a note, however long the install prompt stayed open, so two projects with the same application ID, such as two made from one template, each pair their own installs. The post-install launch does not wait for the write; the announce request above brings the app's report once the row exists. Three installs from a project keep the old token and port until the app reports again, because nothing clears them: (a) a Quick Build install, which installs the proxy app under the project's application ID and never writes a note; (b) a success result with no `EXTRA_PACKAGE_NAME`, which cannot be checked against the note; (c) a result that arrives after Code on the Go's process restarted (notes are kept in memory). `LaunchAppAction` pairs (b) and (c) at the next launch, through `insertPairingIfAbsent`, which keeps the stored values; an app whose old process is gone stays unreachable until its new process reports. An install Code on the Go did not start from a project (an APK opened from the file tree) is not paired at install either; `LaunchAppAction` pairs it at the next launch. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). +- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. When `ProjectHandlerActivity` installs a build, it notes the PackageInstaller session ID with the project and the APK's application ID before the session is committed. `InstallationResultReceiver` takes the result app-wide, so a result that arrives while the editor is stopped still counts: on a success whose result names the noted package, and that arrives in the same Code on the Go process, it moves the app to that session's project and clears the token and port it reported, in the same write; on failure it drops that session's note, as `ApkInstaller`'s `onCommitFailed` does when staging or committing the session throws, since no result follows, and leaves the stored endpoint as it was. For those installs the endpoint is dead whether or not the new build has the SQLite debugger, because the install replaced the process that reported it: a build without it, made after the SQLite debugger was turned off for the project, never reports again, and its row would otherwise keep a dead port. A report the new process sent before the write is cleared too, and sent again in reply to the announce request that follows the write. Only the same session's result uses a note, however long the install prompt stayed open, so two projects with the same application ID, such as two made from one template, each pair their own installs. The post-install launch does not wait for the write; the announce request above brings the app's report once the row exists. Some installs from a project keep the old token and port until the app reports again, because nothing clears them: (a) a Quick Build install, which installs the proxy app under the project's application ID and never writes a note; (b) a Run install with no project open, which has no project to note; (c) a Run install whose APK's application ID cannot be read, which has nothing to note; (d) a success result with no `EXTRA_PACKAGE_NAME`, which cannot be checked against the note; (e) a result that arrives after Code on the Go's process restarted (notes are kept in memory). `LaunchAppAction` pairs (b) to (e) at the next launch from a project, through `insertPairingIfAbsent`, which keeps the stored values; an app whose old process is gone stays unreachable until its new process reports. An install Code on the Go did not start from a project (an APK opened from the file tree) is not paired at install either; `LaunchAppAction` pairs it at the next launch. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). ### The event record From a297cc1e9066be144b54518229c0e906d02b4d57 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 20:42:15 -0800 Subject: [PATCH 19/21] ADFA-7137 Docs: add the fallback installer and a catch-all to the installs that keep the old endpoint The intent-based fallback installer (MIUI or debugFallbackInstaller, Run installs included) never calls beforeCommit and has no session or result, so nothing clears or pairs. Add it as a sixth case, name the remaining installs that keep the old values, and say that only the Launch action pairs at the next launch: the automatic post-install launch, RestartVmAction and the SQLite debugger launch never call recordLaunched. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../roomData/recentproject/DebuggerEndpoint.kt | 14 +++++++++++--- subprojects/sqlite-debugger/README.md | 2 +- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt index d339b5cc0d..995a3a2747 100644 --- a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt +++ b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt @@ -13,9 +13,17 @@ import androidx.room.PrimaryKey * Code on the Go process. Some installs keep the old token and port until the app reports again: * a Quick Build install (the proxy app, installed under the project's application ID, writes no * install note), a Run install with no project open, a Run install whose APK's application ID - * cannot be read (neither writes an install note), a success result with no package name, and a - * result that arrives after Code on the Go restarted. LaunchAppAction pairs the last four at the - * next launch from a project and keeps the stored values. + * cannot be read (neither writes an install note), a success result with no package name, a + * result that arrives after Code on the Go restarted, and an install by the intent-based fallback + * installer (on MIUI, or when debugFallbackInstaller is set; Run installs too), which never calls + * beforeCommit and has no session or result. Only the Launch action (LaunchAppAction) pairs the + * last five at the next launch from a project, and keeps the stored values; the automatic + * post-install launch (BaseEditorActivity.doLaunchApp), RestartVmAction and the SQLite debugger + * launch never call recordLaunched. Other installs keep them too: recordInstalled returns false and + * keeps the old values when the project has no recent-project row or the write fails; a result that + * names a different package is dropped without clearing; a beforeCommit that throws is logged and the + * install goes on with no note; and an install not made from a project (the file tab, adb) leaves an + * already-paired app listed with its dead token and port. * * ON UPDATE CASCADE as well as ON DELETE: renaming a project rewrites its recent_project_table * location, which would otherwise be refused while foreign keys are on. diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 65782373e8..d001408592 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -23,7 +23,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `get_events`. - `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. - `EndpointBroadcast` runs once the server listens, on every process start (the port changes). It sends an explicit broadcast, action `com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT`, to `com.itsaky.androidide` with `FLAG_INCLUDE_STOPPED_PACKAGES`, carrying the token, the port and a `PendingIntent` that identifies the app. The `PendingIntent` is immutable (on API 23 and later; the flag does not exist before) and wraps an intent that is never sent: Code on the Go reads its `creatorPackage`, which the framework sets and another app cannot forge, as the app's package name. The library manifest declares `` for Code on the Go. A failure to send is logged and never thrown. Before the first send it registers a receiver at run time for `org.appdevforall.sqlitedebugger.ANNOUNCE` (exported, as Code on the Go is another app; `RECEIVER_EXPORTED` on API 33 and later), and sends the same token and port again each time it receives one. Code on the Go sends that request when it pairs the app, because it drops a report from an app it has not paired: an app that was already running then, installed some other way or started before its project was opened, would otherwise stay unknown until its process restarted. The receiver is not in the manifest, so a request never starts an app that is not running, and is not authenticated (ADFA-7131 D8): the reply goes only to Code on the Go. -- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. When `ProjectHandlerActivity` installs a build, it notes the PackageInstaller session ID with the project and the APK's application ID before the session is committed. `InstallationResultReceiver` takes the result app-wide, so a result that arrives while the editor is stopped still counts: on a success whose result names the noted package, and that arrives in the same Code on the Go process, it moves the app to that session's project and clears the token and port it reported, in the same write; on failure it drops that session's note, as `ApkInstaller`'s `onCommitFailed` does when staging or committing the session throws, since no result follows, and leaves the stored endpoint as it was. For those installs the endpoint is dead whether or not the new build has the SQLite debugger, because the install replaced the process that reported it: a build without it, made after the SQLite debugger was turned off for the project, never reports again, and its row would otherwise keep a dead port. A report the new process sent before the write is cleared too, and sent again in reply to the announce request that follows the write. Only the same session's result uses a note, however long the install prompt stayed open, so two projects with the same application ID, such as two made from one template, each pair their own installs. The post-install launch does not wait for the write; the announce request above brings the app's report once the row exists. Some installs from a project keep the old token and port until the app reports again, because nothing clears them: (a) a Quick Build install, which installs the proxy app under the project's application ID and never writes a note; (b) a Run install with no project open, which has no project to note; (c) a Run install whose APK's application ID cannot be read, which has nothing to note; (d) a success result with no `EXTRA_PACKAGE_NAME`, which cannot be checked against the note; (e) a result that arrives after Code on the Go's process restarted (notes are kept in memory). `LaunchAppAction` pairs (b) to (e) at the next launch from a project, through `insertPairingIfAbsent`, which keeps the stored values; an app whose old process is gone stays unreachable until its new process reports. An install Code on the Go did not start from a project (an APK opened from the file tree) is not paired at install either; `LaunchAppAction` pairs it at the next launch. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). +- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. When `ProjectHandlerActivity` installs a build, it notes the PackageInstaller session ID with the project and the APK's application ID before the session is committed. `InstallationResultReceiver` takes the result app-wide, so a result that arrives while the editor is stopped still counts: on a success whose result names the noted package, and that arrives in the same Code on the Go process, it moves the app to that session's project and clears the token and port it reported, in the same write; on failure it drops that session's note, as `ApkInstaller`'s `onCommitFailed` does when staging or committing the session throws, since no result follows, and leaves the stored endpoint as it was. For those installs the endpoint is dead whether or not the new build has the SQLite debugger, because the install replaced the process that reported it: a build without it, made after the SQLite debugger was turned off for the project, never reports again, and its row would otherwise keep a dead port. A report the new process sent before the write is cleared too, and sent again in reply to the announce request that follows the write. Only the same session's result uses a note, however long the install prompt stayed open, so two projects with the same application ID, such as two made from one template, each pair their own installs. The post-install launch does not wait for the write; the announce request above brings the app's report once the row exists. Some installs from a project keep the old token and port until the app reports again, because nothing clears them: (a) a Quick Build install, which installs the proxy app under the project's application ID and never writes a note; (b) a Run install with no project open, which has no project to note; (c) a Run install whose APK's application ID cannot be read, which has nothing to note; (d) a success result with no `EXTRA_PACKAGE_NAME`, which cannot be checked against the note; (e) a result that arrives after Code on the Go's process restarted (notes are kept in memory); (f) an install by the intent-based fallback installer, used on MIUI or when `debugFallbackInstaller` is set, Run installs included, which never calls `beforeCommit` and has no session or result, so nothing clears or pairs. Only the Launch action (`LaunchAppAction`) pairs (b) to (f) at the next launch from a project, through `insertPairingIfAbsent`, which keeps the stored values; the automatic post-install launch (`BaseEditorActivity.doLaunchApp`), `RestartVmAction` and the SQLite debugger launch never call `recordLaunched`. An app whose old process is gone stays unreachable until its new process reports. Other installs keep the old values too: `recordInstalled` returns false and keeps them when the project has no recent-project row or the write fails; a result that names a different package is dropped without clearing; a `beforeCommit` that throws is logged and the install goes on with no note; and an install not made from a project (an APK opened from the file tree, or adb) leaves an already-paired app listed with its dead token and port. An APK opened from the file tree is not paired at install either; the Launch action pairs it at the next launch. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). ### The event record From 7dbd5b4cfdf1b353ee687a837029fdbce3f225f2 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 09:03:55 -0800 Subject: [PATCH 20/21] ADFA-7137 Docs: name the real launches that skip recordLaunched, say an unpaired app, say file tab once "The SQLite debugger launch" named a path that does not exist: the SQLite debugger starts inside the app from its ContentProvider and launches nothing. The launches that never call recordLaunched are BaseEditorActivity.doLaunchApp (in debug mode too, for the Debug action), RestartVmAction and Quick Build's launch of the proxy app (AndroidProxyAppLauncher). The Launch action pairs only an unpaired app: insertPairingIfAbsent leaves an already-paired app's row and stored values alone. The README said "file tree" twice in one sentence; the install comes from the file tab's Install action (InstallFileAction, a FileTabAction), so it now says "file tab" once. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../roomData/recentproject/DebuggerEndpoint.kt | 17 +++++++++-------- subprojects/sqlite-debugger/README.md | 2 +- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt index 995a3a2747..2aa12d8d60 100644 --- a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt +++ b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt @@ -16,14 +16,15 @@ import androidx.room.PrimaryKey * cannot be read (neither writes an install note), a success result with no package name, a * result that arrives after Code on the Go restarted, and an install by the intent-based fallback * installer (on MIUI, or when debugFallbackInstaller is set; Run installs too), which never calls - * beforeCommit and has no session or result. Only the Launch action (LaunchAppAction) pairs the - * last five at the next launch from a project, and keeps the stored values; the automatic - * post-install launch (BaseEditorActivity.doLaunchApp), RestartVmAction and the SQLite debugger - * launch never call recordLaunched. Other installs keep them too: recordInstalled returns false and - * keeps the old values when the project has no recent-project row or the write fails; a result that - * names a different package is dropped without clearing; a beforeCommit that throws is logged and the - * install goes on with no note; and an install not made from a project (the file tab, adb) leaves an - * already-paired app listed with its dead token and port. + * beforeCommit and has no session or result. Only the Launch action (LaunchAppAction) pairs an + * unpaired app installed by the last five, at the next launch from a project, and keeps an + * already-paired app's stored values; the automatic post-install launch + * (BaseEditorActivity.doLaunchApp, in debug mode too), RestartVmAction and Quick Build's launch of + * the proxy app never call recordLaunched. Other installs keep them too: recordInstalled returns + * false and keeps the old values when the project has no recent-project row or the write fails; a + * result that names a different package is dropped without clearing; a beforeCommit that throws is + * logged and the install goes on with no note; and an install not made from a project (the file + * tab, adb) leaves an already-paired app listed with its dead token and port. * * ON UPDATE CASCADE as well as ON DELETE: renaming a project rewrites its recent_project_table * location, which would otherwise be refused while foreign keys are on. diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index d001408592..537f47d762 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -23,7 +23,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `get_events`. - `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. - `EndpointBroadcast` runs once the server listens, on every process start (the port changes). It sends an explicit broadcast, action `com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT`, to `com.itsaky.androidide` with `FLAG_INCLUDE_STOPPED_PACKAGES`, carrying the token, the port and a `PendingIntent` that identifies the app. The `PendingIntent` is immutable (on API 23 and later; the flag does not exist before) and wraps an intent that is never sent: Code on the Go reads its `creatorPackage`, which the framework sets and another app cannot forge, as the app's package name. The library manifest declares `` for Code on the Go. A failure to send is logged and never thrown. Before the first send it registers a receiver at run time for `org.appdevforall.sqlitedebugger.ANNOUNCE` (exported, as Code on the Go is another app; `RECEIVER_EXPORTED` on API 33 and later), and sends the same token and port again each time it receives one. Code on the Go sends that request when it pairs the app, because it drops a report from an app it has not paired: an app that was already running then, installed some other way or started before its project was opened, would otherwise stay unknown until its process restarted. The receiver is not in the manifest, so a request never starts an app that is not running, and is not authenticated (ADFA-7131 D8): the reply goes only to Code on the Go. -- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. When `ProjectHandlerActivity` installs a build, it notes the PackageInstaller session ID with the project and the APK's application ID before the session is committed. `InstallationResultReceiver` takes the result app-wide, so a result that arrives while the editor is stopped still counts: on a success whose result names the noted package, and that arrives in the same Code on the Go process, it moves the app to that session's project and clears the token and port it reported, in the same write; on failure it drops that session's note, as `ApkInstaller`'s `onCommitFailed` does when staging or committing the session throws, since no result follows, and leaves the stored endpoint as it was. For those installs the endpoint is dead whether or not the new build has the SQLite debugger, because the install replaced the process that reported it: a build without it, made after the SQLite debugger was turned off for the project, never reports again, and its row would otherwise keep a dead port. A report the new process sent before the write is cleared too, and sent again in reply to the announce request that follows the write. Only the same session's result uses a note, however long the install prompt stayed open, so two projects with the same application ID, such as two made from one template, each pair their own installs. The post-install launch does not wait for the write; the announce request above brings the app's report once the row exists. Some installs from a project keep the old token and port until the app reports again, because nothing clears them: (a) a Quick Build install, which installs the proxy app under the project's application ID and never writes a note; (b) a Run install with no project open, which has no project to note; (c) a Run install whose APK's application ID cannot be read, which has nothing to note; (d) a success result with no `EXTRA_PACKAGE_NAME`, which cannot be checked against the note; (e) a result that arrives after Code on the Go's process restarted (notes are kept in memory); (f) an install by the intent-based fallback installer, used on MIUI or when `debugFallbackInstaller` is set, Run installs included, which never calls `beforeCommit` and has no session or result, so nothing clears or pairs. Only the Launch action (`LaunchAppAction`) pairs (b) to (f) at the next launch from a project, through `insertPairingIfAbsent`, which keeps the stored values; the automatic post-install launch (`BaseEditorActivity.doLaunchApp`), `RestartVmAction` and the SQLite debugger launch never call `recordLaunched`. An app whose old process is gone stays unreachable until its new process reports. Other installs keep the old values too: `recordInstalled` returns false and keeps them when the project has no recent-project row or the write fails; a result that names a different package is dropped without clearing; a `beforeCommit` that throws is logged and the install goes on with no note; and an install not made from a project (an APK opened from the file tree, or adb) leaves an already-paired app listed with its dead token and port. An APK opened from the file tree is not paired at install either; the Launch action pairs it at the next launch. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). +- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. When `ProjectHandlerActivity` installs a build, it notes the PackageInstaller session ID with the project and the APK's application ID before the session is committed. `InstallationResultReceiver` takes the result app-wide, so a result that arrives while the editor is stopped still counts: on a success whose result names the noted package, and that arrives in the same Code on the Go process, it moves the app to that session's project and clears the token and port it reported, in the same write; on failure it drops that session's note, as `ApkInstaller`'s `onCommitFailed` does when staging or committing the session throws, since no result follows, and leaves the stored endpoint as it was. For those installs the endpoint is dead whether or not the new build has the SQLite debugger, because the install replaced the process that reported it: a build without it, made after the SQLite debugger was turned off for the project, never reports again, and its row would otherwise keep a dead port. A report the new process sent before the write is cleared too, and sent again in reply to the announce request that follows the write. Only the same session's result uses a note, however long the install prompt stayed open, so two projects with the same application ID, such as two made from one template, each pair their own installs. The post-install launch does not wait for the write; the announce request above brings the app's report once the row exists. Some installs from a project keep the old token and port until the app reports again, because nothing clears them: (a) a Quick Build install, which installs the proxy app under the project's application ID and never writes a note; (b) a Run install with no project open, which has no project to note; (c) a Run install whose APK's application ID cannot be read, which has nothing to note; (d) a success result with no `EXTRA_PACKAGE_NAME`, which cannot be checked against the note; (e) a result that arrives after Code on the Go's process restarted (notes are kept in memory); (f) an install by the intent-based fallback installer, used on MIUI or when `debugFallbackInstaller` is set, Run installs included, which never calls `beforeCommit` and has no session or result, so nothing clears or pairs. Only the Launch action (`LaunchAppAction`) pairs an unpaired app installed by (b) to (f), at the next launch from a project, through `insertPairingIfAbsent`, which keeps an already-paired app's stored values; the automatic post-install launch (`BaseEditorActivity.doLaunchApp`, in debug mode too), `RestartVmAction` and Quick Build's launch of the proxy app never call `recordLaunched`. An app whose old process is gone stays unreachable until its new process reports. Other installs keep the old values too: `recordInstalled` returns false and keeps them when the project has no recent-project row or the write fails; a result that names a different package is dropped without clearing; a `beforeCommit` that throws is logged and the install goes on with no note; and an install not made from a project (the file tab's Install action, or adb) leaves an already-paired app listed with its dead token and port, and does not pair an unpaired app; the Launch action pairs that app at the next launch. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). ### The event record From ff1fea43858d95873b489a59121337fddd7b7ec9 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 10:12:36 -0800 Subject: [PATCH 21/21] ADFA-7137 Docs: Launch pairs an unpaired app from all six install cases, (a) to (f) The README and DebuggerEndpoint KDoc said Launch pairs an app installed by (b) to (f) or "the last five". A Quick Build install (a) is paired too: LaunchAppAction has no Quick Build check and the proxy app is installed under the project's real application ID. Also say "installed from the file tab" in a test comment, as the test does. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../androidide/roomData/recentproject/DebuggerEndpoint.kt | 2 +- .../androidide/repositories/DebuggerEndpointRepositoryTest.kt | 2 +- subprojects/sqlite-debugger/README.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt index 2aa12d8d60..11cc9931cd 100644 --- a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt +++ b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/DebuggerEndpoint.kt @@ -17,7 +17,7 @@ import androidx.room.PrimaryKey * result that arrives after Code on the Go restarted, and an install by the intent-based fallback * installer (on MIUI, or when debugFallbackInstaller is set; Run installs too), which never calls * beforeCommit and has no session or result. Only the Launch action (LaunchAppAction) pairs an - * unpaired app installed by the last five, at the next launch from a project, and keeps an + * unpaired app installed by any of the six, at the next launch from a project, and keeps an * already-paired app's stored values; the automatic post-install launch * (BaseEditorActivity.doLaunchApp, in debug mode too), RestartVmAction and Quick Build's launch of * the proxy app never call recordLaunched. Other installs keep them too: recordInstalled returns diff --git a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt index c32dbb2b60..26c15d66d5 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt @@ -171,7 +171,7 @@ class DebuggerEndpointRepositoryTest { try { repository.notePendingInstall(1, dir, "com.example") - // Session 2 has no note: an APK opened from the file tree, say, of the same application ID. + // Session 2 has no note: an APK installed from the file tab, say, of the same application ID. assertThat(repository.confirmInstall(2, "com.example")).isNull() assertThat(pairedLocation()).isNull() diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 537f47d762..e29454484b 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -23,7 +23,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `get_events`. - `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. - `EndpointBroadcast` runs once the server listens, on every process start (the port changes). It sends an explicit broadcast, action `com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT`, to `com.itsaky.androidide` with `FLAG_INCLUDE_STOPPED_PACKAGES`, carrying the token, the port and a `PendingIntent` that identifies the app. The `PendingIntent` is immutable (on API 23 and later; the flag does not exist before) and wraps an intent that is never sent: Code on the Go reads its `creatorPackage`, which the framework sets and another app cannot forge, as the app's package name. The library manifest declares `` for Code on the Go. A failure to send is logged and never thrown. Before the first send it registers a receiver at run time for `org.appdevforall.sqlitedebugger.ANNOUNCE` (exported, as Code on the Go is another app; `RECEIVER_EXPORTED` on API 33 and later), and sends the same token and port again each time it receives one. Code on the Go sends that request when it pairs the app, because it drops a report from an app it has not paired: an app that was already running then, installed some other way or started before its project was opened, would otherwise stay unknown until its process restarted. The receiver is not in the manifest, so a request never starts an app that is not running, and is not authenticated (ADFA-7131 D8): the reply goes only to Code on the Go. -- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. When `ProjectHandlerActivity` installs a build, it notes the PackageInstaller session ID with the project and the APK's application ID before the session is committed. `InstallationResultReceiver` takes the result app-wide, so a result that arrives while the editor is stopped still counts: on a success whose result names the noted package, and that arrives in the same Code on the Go process, it moves the app to that session's project and clears the token and port it reported, in the same write; on failure it drops that session's note, as `ApkInstaller`'s `onCommitFailed` does when staging or committing the session throws, since no result follows, and leaves the stored endpoint as it was. For those installs the endpoint is dead whether or not the new build has the SQLite debugger, because the install replaced the process that reported it: a build without it, made after the SQLite debugger was turned off for the project, never reports again, and its row would otherwise keep a dead port. A report the new process sent before the write is cleared too, and sent again in reply to the announce request that follows the write. Only the same session's result uses a note, however long the install prompt stayed open, so two projects with the same application ID, such as two made from one template, each pair their own installs. The post-install launch does not wait for the write; the announce request above brings the app's report once the row exists. Some installs from a project keep the old token and port until the app reports again, because nothing clears them: (a) a Quick Build install, which installs the proxy app under the project's application ID and never writes a note; (b) a Run install with no project open, which has no project to note; (c) a Run install whose APK's application ID cannot be read, which has nothing to note; (d) a success result with no `EXTRA_PACKAGE_NAME`, which cannot be checked against the note; (e) a result that arrives after Code on the Go's process restarted (notes are kept in memory); (f) an install by the intent-based fallback installer, used on MIUI or when `debugFallbackInstaller` is set, Run installs included, which never calls `beforeCommit` and has no session or result, so nothing clears or pairs. Only the Launch action (`LaunchAppAction`) pairs an unpaired app installed by (b) to (f), at the next launch from a project, through `insertPairingIfAbsent`, which keeps an already-paired app's stored values; the automatic post-install launch (`BaseEditorActivity.doLaunchApp`, in debug mode too), `RestartVmAction` and Quick Build's launch of the proxy app never call `recordLaunched`. An app whose old process is gone stays unreachable until its new process reports. Other installs keep the old values too: `recordInstalled` returns false and keeps them when the project has no recent-project row or the write fails; a result that names a different package is dropped without clearing; a `beforeCommit` that throws is logged and the install goes on with no note; and an install not made from a project (the file tab's Install action, or adb) leaves an already-paired app listed with its dead token and port, and does not pair an unpaired app; the Launch action pairs that app at the next launch. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). +- On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. When `ProjectHandlerActivity` installs a build, it notes the PackageInstaller session ID with the project and the APK's application ID before the session is committed. `InstallationResultReceiver` takes the result app-wide, so a result that arrives while the editor is stopped still counts: on a success whose result names the noted package, and that arrives in the same Code on the Go process, it moves the app to that session's project and clears the token and port it reported, in the same write; on failure it drops that session's note, as `ApkInstaller`'s `onCommitFailed` does when staging or committing the session throws, since no result follows, and leaves the stored endpoint as it was. For those installs the endpoint is dead whether or not the new build has the SQLite debugger, because the install replaced the process that reported it: a build without it, made after the SQLite debugger was turned off for the project, never reports again, and its row would otherwise keep a dead port. A report the new process sent before the write is cleared too, and sent again in reply to the announce request that follows the write. Only the same session's result uses a note, however long the install prompt stayed open, so two projects with the same application ID, such as two made from one template, each pair their own installs. The post-install launch does not wait for the write; the announce request above brings the app's report once the row exists. Some installs from a project keep the old token and port until the app reports again, because nothing clears them: (a) a Quick Build install, which installs the proxy app under the project's application ID and never writes a note; (b) a Run install with no project open, which has no project to note; (c) a Run install whose APK's application ID cannot be read, which has nothing to note; (d) a success result with no `EXTRA_PACKAGE_NAME`, which cannot be checked against the note; (e) a result that arrives after Code on the Go's process restarted (notes are kept in memory); (f) an install by the intent-based fallback installer, used on MIUI or when `debugFallbackInstaller` is set, Run installs included, which never calls `beforeCommit` and has no session or result, so nothing clears or pairs. Only the Launch action (`LaunchAppAction`) pairs an unpaired app installed by (a) to (f), at the next launch from a project, through `insertPairingIfAbsent`, which keeps an already-paired app's stored values; the automatic post-install launch (`BaseEditorActivity.doLaunchApp`, in debug mode too), `RestartVmAction` and Quick Build's launch of the proxy app never call `recordLaunched`. An app whose old process is gone stays unreachable until its new process reports. Other installs keep the old values too: `recordInstalled` returns false and keeps them when the project has no recent-project row or the write fails; a result that names a different package is dropped without clearing; a `beforeCommit` that throws is logged and the install goes on with no note; and an install not made from a project (the file tab's Install action, or adb) leaves an already-paired app listed with its dead token and port, and does not pair an unpaired app; the Launch action pairs that app at the next launch. After each pairing, `DebuggerEndpointAnnounce` sends the app the announce request above. The row is deleted with its project (foreign key, ON DELETE CASCADE). ### The event record