From 813c352d89d212e15a842710354196b2a7aa0ed7 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 21:33:44 -0800 Subject: [PATCH 1/6] 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 2/6] 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 3/6] 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 6/6] 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) + } +}