diff --git a/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt b/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt index 82f0d511ce..663ca06994 100644 --- a/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt +++ b/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt @@ -21,11 +21,13 @@ import com.itsaky.androidide.managers.ToolsManager import com.itsaky.androidide.plugins.PluginLogger import com.itsaky.androidide.plugins.base.PluginFragmentHelper import com.itsaky.androidide.plugins.manager.core.PluginManager +import com.itsaky.androidide.plugins.manager.services.DebuggerEndpointSources import com.itsaky.androidide.plugins.manager.services.IdeBuildServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeLogServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeTerminalServiceImpl import com.itsaky.androidide.preferences.internal.DevOpsPreferences import com.itsaky.androidide.preferences.internal.GeneralPreferences +import com.itsaky.androidide.repositories.DebuggerEndpointRepository import com.itsaky.androidide.resources.localization.LocaleProvider import com.itsaky.androidide.services.builder.BuildOutputLocation import com.itsaky.androidide.tooling.api.messages.result.TaskExecutionResult @@ -41,10 +43,12 @@ import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode +import org.koin.core.context.GlobalContext import org.slf4j.LoggerFactory import java.io.File import java.util.concurrent.atomic.AtomicBoolean @@ -404,6 +408,10 @@ internal object CredentialProtectedApplicationLoader : ApplicationLoader { setupBuildServiceProviders() setupProjectManipulationProviders() IdeLogServiceImpl.getInstance().setLogReader(LogsProvider::read) + // Plugins call it on a background thread (DebuggerEndpointService), so blocking on Room is fine. + DebuggerEndpointSources.install { location -> + runBlocking { GlobalContext.get().get().reportedEndpoints(File(location)) } + } IdeTerminalServiceImpl.setSessionLauncher(PluginTerminalLauncher { application.foregroundActivity }) logger.info("Plugin services configured successfully") } 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..97501b3851 100644 --- a/app/src/main/java/com/itsaky/androidide/di/AppModule.kt +++ b/app/src/main/java/com/itsaky/androidide/di/AppModule.kt @@ -63,7 +63,12 @@ val coreModule = } single { - DebuggerEndpointRepository(get(), get(named(APPLICATION_SCOPE))) + val packageManager = androidContext().packageManager + DebuggerEndpointRepository( + get(), + get(named(APPLICATION_SCOPE)), + isInstalled = { DebuggerEndpointRepository.isPackageInstalled(packageManager, 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..bf74041864 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt @@ -1,5 +1,6 @@ package com.itsaky.androidide.repositories +import android.content.pm.PackageManager import com.itsaky.androidide.roomData.recentproject.DebuggerEndpointDao import com.itsaky.androidide.sqlitedebugger.DebuggerEndpointValidation import com.itsaky.androidide.utils.canonicalProjectLocation @@ -11,6 +12,7 @@ import kotlinx.coroutines.withContext import org.slf4j.LoggerFactory import java.io.File import java.util.concurrent.ConcurrentHashMap +import com.itsaky.androidide.plugins.services.DebuggerEndpoint as PluginDebuggerEndpoint /** * Which app each project builds, and the SQLite debugger endpoint the app last reported (ADFA-7137). @@ -22,6 +24,7 @@ class DebuggerEndpointRepository( private val dao: DebuggerEndpointDao, private val scope: CoroutineScope, private val clock: () -> Long = System::currentTimeMillis, + private val isInstalled: (String) -> Boolean = { true }, ) { private class PendingInstall( val location: String, @@ -132,7 +135,38 @@ class DebuggerEndpointRepository( false } - private companion object { + /** + * The endpoints the apps of [projectDir] have reported, for the plugin API (ADFA-7139). Looked + * up by the canonical path, as the pairing stores it; apps that have not reported yet are left + * out, and so are apps that are no longer installed: their stored port and token would otherwise + * come back as live. An endpoint can still be stale when the app's process has died. Unlike the writes, a read failure is thrown: the plugin API reports it rather than + * answering "no apps". + */ + suspend fun reportedEndpoints(projectDir: File): List = + dao.getByProjectLocation(projectDir.canonicalProjectLocation()).mapNotNull { row -> + if (!isInstalled(row.applicationId)) return@mapNotNull null + val token = row.token ?: return@mapNotNull null + val port = row.port ?: return@mapNotNull null + PluginDebuggerEndpoint(row.applicationId, port, token, row.updatedAt ?: 0L) + } + + companion object { + /** + * Whether [applicationId] is installed. Every package is visible because Code on the Go targets SDK 28; at a + * target of 30 or later, package visibility filtering would make every endpoint look uninstalled unless the + * manifest declares a matching ``. + */ + fun isPackageInstalled( + packageManager: PackageManager, + applicationId: String, + ): Boolean = + try { + packageManager.getPackageInfo(applicationId, 0) + true + } catch (e: PackageManager.NameNotFoundException) { + false + } + 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 b0e6d0c6fb..71f8af57d5 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt @@ -337,4 +337,68 @@ class DebuggerEndpointRepositoryTest { assertThat(result.exceptionOrNull()).isInstanceOf(kotlinx.coroutines.CancellationException::class.java) } + + @Test + fun `reported endpoints are found through a non-canonical path and unreported apps are left out`() = + runBlocking { + val dir = + java.nio.file.Files + .createTempDirectory("proj") + .toFile() + try { + addProject(dir.canonicalPath) + assertThat(repository.recordInstalled("com.example.reported", dir.canonicalPath)).isTrue() + assertThat(repository.recordInstalled("com.example.silent", dir.canonicalPath)).isTrue() + assertThat(repository.storeEndpoint("com.example.reported", endpoint)).isTrue() + + val endpoints = repository.reportedEndpoints(File(dir, "../" + dir.name)) + + assertThat(endpoints.map { it.applicationId }).containsExactly("com.example.reported") + val e = endpoints.single() + assertThat(e.port).isEqualTo(5555) + assertThat(e.token).isEqualTo("tok-en_1") + assertThat(e.updatedAtMillis).isEqualTo(1234L) + } finally { + dir.delete() + } + } + + @Test + fun `an app that is no longer installed is left out and installed ones are returned`() = + runBlocking { + val dir = + java.nio.file.Files + .createTempDirectory("proj") + .toFile() + try { + addProject(dir.canonicalPath) + val installed = setOf("com.example.alive") + val pruning = + DebuggerEndpointRepository( + room.debuggerEndpointDao(), + CoroutineScope(Dispatchers.IO), + clock = { 1234L }, + isInstalled = { it in installed }, + ) + for (id in listOf("com.example.alive", "com.example.gone")) { + assertThat(pruning.recordInstalled(id, dir.canonicalPath)).isTrue() + assertThat(pruning.storeEndpoint(id, endpoint)).isTrue() + } + + val endpoints = pruning.reportedEndpoints(dir) + + assertThat(endpoints.map { it.applicationId }).containsExactly("com.example.alive") + } finally { + dir.delete() + } + } + + @Test + fun `the package manager check tells installed from missing apps`() { + val app = ApplicationProvider.getApplicationContext() + val packageManager = app.packageManager + + assertThat(DebuggerEndpointRepository.isPackageInstalled(packageManager, app.packageName)).isTrue() + assertThat(DebuggerEndpointRepository.isPackageInstalled(packageManager, "com.example.not.installed")).isFalse() + } } diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index d37c7f42c7..536419803c 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -35,6 +35,20 @@ need a source change, a recompile, or both · `tooling` = API-stability milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed]** = diffed from `plugin-api/src` history (predates the dump; symbol-accurate). +### 26.47 — unreleased +- **added — Find the SQLite debugger of the open project's apps** _(ADFA-7139)_ **[verified]** + `DebuggerEndpointService.getEndpoints()` returns a `List`, one per app of the open + project that has reported to the IDE: `applicationId`, `port` (on `127.0.0.1`), `token` (the bearer + token the server requires) and `updatedAtMillis`. The list is empty, never null, when no project is + open or no app has reported. Port and token change every time the app starts, so call again after a + refused connection or a 401/403. An app that was uninstalled is left out, but one whose process died stays + listed until it reports again (`updatedAtMillis` is when it last reported). The call reads the IDE's database: use a background thread. It needs + the new `debugger.endpoints` permission (`PluginPermission.DEBUGGER_ENDPOINTS`) and throws + `SecurityException` without it, and `IllegalStateException` on the main thread or when the database + cannot be read (an unreadable database is not reported as an empty list). Floor `plugin.min_ide_version` + at `26.47`: an IDE of 26.46 or older rejects the unknown `debugger.endpoints` permission when it + validates the manifest, so it refuses to install a plugin that declares it. + ### 26.43 — unreleased - **tooling — Interface bodies are Java default methods again** _(ADFA-6560)_ **[verified]** Since ADFA-4058 (May 2026) pinned `languageVersion`, `plugin-api` compiled each Kotlin interface diff --git a/docs/PLUGIN_AUTHORING.md b/docs/PLUGIN_AUTHORING.md index eff39136fe..72d536332e 100644 --- a/docs/PLUGIN_AUTHORING.md +++ b/docs/PLUGIN_AUTHORING.md @@ -343,6 +343,7 @@ Defined by `PluginPermission` in `plugin-api/src/main/kotlin/com/itsaky/androidi | `project.structure` | Modify project structure | | `native.code` | Execute native machine code | | `ide.environment.write` | Write to IDE-managed directories (Android SDK, NDK, cache) | +| `debugger.endpoints` | Read the port and token of the open project's SQLite debugger servers | ## Contributing a language diff --git a/docs/plugin-api.md b/docs/plugin-api.md index 3eb7d85b76..7eeec75834 100644 --- a/docs/plugin-api.md +++ b/docs/plugin-api.md @@ -22,7 +22,7 @@ The surface a plugin binds to is broader than one module. All of the following a - **Wire/format contracts outside the module:** - Manifest `` keys — `plugin.id`, `plugin.name`, `plugin.version`, `plugin.description`, `plugin.author`, `plugin.main_class`, `plugin.min_ide_version`, `plugin.max_ide_version`, `plugin.permissions`, `plugin.sidebar_items`, `plugin.icon_day`, `plugin.icon_night`, `plugin.vcs_revision`, `plugin.build_timestamp`. Matched **by string** — a rename silently breaks every plugin. - Plugin language assets: `lib//libtree-sitter-.so` exporting `tree_sitter_`, the query file names under `TreeSitterGrammar.queriesAssetPath`, and the standard capture names mapped by each colour scheme's `generic.json`. - - Permission **key strings** (`filesystem.read`, `filesystem.write`, `network.access`, `system.commands`, `ide.settings`, `project.structure`, `native.code`, `ide.environment.write`) — also matched by string. + - Permission **key strings** (`filesystem.read`, `filesystem.write`, `network.access`, `system.commands`, `ide.settings`, `project.structure`, `native.code`, `ide.environment.write`, `debugger.endpoints`) — also matched by string. - The path allowlist and per-plugin data directories enforced by `IdeFileService` / `IdeArchiveService`. - File/format contracts: the `.cgp` package format (including `assets/cgp-build.properties`, the provenance record the builder writes into every artifact — see [PLUGIN_AUTHORING.md](PLUGIN_AUTHORING.md#provenance)), the `.cgt` template format, the `plugin_documentation.db` schema, `.codeonthego/scripts.json`, the TextMate snippet syntax, and the `http://localhost:6174/` help-server URL scheme with the `plugin//` namespace. diff --git a/plugin-api/api/plugin-api.api b/plugin-api/api/plugin-api.api index df35e7d108..85403778ad 100644 --- a/plugin-api/api/plugin-api.api +++ b/plugin-api/api/plugin-api.api @@ -107,6 +107,7 @@ public final class com/itsaky/androidide/plugins/PluginMetadata : android/os/Par } public final class com/itsaky/androidide/plugins/PluginPermission : java/lang/Enum { + public static final field DEBUGGER_ENDPOINTS Lcom/itsaky/androidide/plugins/PluginPermission; public static final field FILESYSTEM_READ Lcom/itsaky/androidide/plugins/PluginPermission; public static final field FILESYSTEM_WRITE Lcom/itsaky/androidide/plugins/PluginPermission; public static final field IDE_ENVIRONMENT_WRITE Lcom/itsaky/androidide/plugins/PluginPermission; @@ -1651,6 +1652,22 @@ public final class com/itsaky/androidide/plugins/services/CursorPosition { public fun toString ()Ljava/lang/String; } +public final class com/itsaky/androidide/plugins/services/DebuggerEndpoint { + public fun (Ljava/lang/String;ILjava/lang/String;J)V + public fun equals (Ljava/lang/Object;)Z + public fun getApplicationId ()Ljava/lang/String; + public fun getPort ()I + public fun getToken ()Ljava/lang/String; + public fun getUpdatedAtMillis ()J + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public abstract interface class com/itsaky/androidide/plugins/services/DebuggerEndpointService { + public static final field CONTRACT_VERSION I + public abstract fun getEndpoints ()Ljava/util/List; +} + public abstract interface class com/itsaky/androidide/plugins/services/EditorContentChangeListener { public abstract fun onContentChanged (Ljava/lang/String;IILjava/lang/String;)V } diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpoint.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpoint.java new file mode 100644 index 0000000000..943fd5a236 --- /dev/null +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpoint.java @@ -0,0 +1,101 @@ +package com.itsaky.androidide.plugins.services; + +import androidx.annotation.NonNull; +import java.util.Objects; + +/** + * Where one app's SQLite debugger server is listening, as the app last reported it to the IDE. Immutable. + * + *

+ * The port and the token are chosen by the app on every start, so a value read here goes stale when the app dies or is relaunched; a client that is refused (or answered 401/403) asks {@link DebuggerEndpointService#getEndpoints} again instead of retrying the same values. The token is a credential for the debugger server: do not log it or persist it. {@link #toString} leaves it out. + * + *

+ * An endpoint whose app has been uninstalled is not returned, but one whose process has died is: nothing removes it until the app reports again. {@link #getUpdatedAtMillis} is when the app last reported, not a sign that it is still running. + */ +public final class DebuggerEndpoint { + + private final String applicationId; + private final int port; + private final String token; + private final long updatedAtMillis; + + /** + * Creates an endpoint. + * + * @param applicationId + * the app's package name (must not be null) + * @param port + * the TCP port the debugger server listens on, on the loopback interface + * @param token + * the bearer token the server requires (must not be null) + * @param updatedAtMillis + * when the app reported these values, in milliseconds since the Unix epoch + */ + public DebuggerEndpoint(@NonNull String applicationId, int port, @NonNull String token, long updatedAtMillis) { + this.applicationId = Objects.requireNonNull(applicationId, "applicationId"); + this.port = port; + this.token = Objects.requireNonNull(token, "token"); + this.updatedAtMillis = updatedAtMillis; + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof DebuggerEndpoint)) { + return false; + } + final DebuggerEndpoint that = (DebuggerEndpoint) other; + return port == that.port && updatedAtMillis == that.updatedAtMillis && applicationId.equals(that.applicationId) && token.equals(that.token); + } + + /** + * Gets the app's package name, which identifies the app within the project. + * + * @return the application ID (never null) + */ + @NonNull + public String getApplicationId() { + return applicationId; + } + + /** + * Gets the port the debugger server listens on, on {@code 127.0.0.1}. + * + * @return the port + */ + public int getPort() { + return port; + } + + /** + * Gets the bearer token the server requires on every request. + * + * @return the token (never null) + */ + @NonNull + public String getToken() { + return token; + } + + /** + * Gets when the app reported {@link #getPort} and {@link #getToken}. + * + * @return milliseconds since the Unix epoch + */ + public long getUpdatedAtMillis() { + return updatedAtMillis; + } + + @Override + public int hashCode() { + return Objects.hash(applicationId, port, token, updatedAtMillis); + } + + @NonNull + @Override + public String toString() { + return "DebuggerEndpoint{applicationId=" + applicationId + ", port=" + port + ", updatedAtMillis=" + updatedAtMillis + "}"; + } +} diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java new file mode 100644 index 0000000000..afc28d2aa8 --- /dev/null +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java @@ -0,0 +1,36 @@ +package com.itsaky.androidide.plugins.services; + +import androidx.annotation.NonNull; +import java.util.List; + +/** + * Tells a plugin where the SQLite debugger servers of the open project's apps are listening, so a plugin such as an MCP client can connect without the user typing a port or token. + * + *

+ * The host registers this service for every plugin; a call needs the {@link com.itsaky.androidide.plugins.PluginPermission#DEBUGGER_ENDPOINTS} permission and throws {@link SecurityException} without it, like the other permission-gated services. + * + *

+ * Calls are synchronous, as in {@link IdeLogService} and {@link IdeProjectService}, rather than returning a {@link java.util.concurrent.CompletableFuture} as the services that start long work do: the answer is a small read of the IDE's own database, not an operation with a lifecycle. That read is disk I/O, so call from a background thread: on the main thread the call throws {@link IllegalStateException}. + */ +public interface DebuggerEndpointService { + + /** + * Contract revision, bumped whenever a member is added here. It marks the revision and does not negotiate one; see {@link ToolSourceRegistry#CONTRACT_VERSION}. + */ + int CONTRACT_VERSION = 1; + + /** + * Gets the debugger endpoints of the open project, one per app that has reported. Read fresh on every call, so call it again after a connection fails: a relaunched app has a new port and token. + * + *

+ * An app the IDE installed or launched but that has not yet reported is not listed, and neither is an app that has since been uninstalled. An endpoint can still be stale: when the app's process has died, its last reported port and token stay here until the app reports again, so treat {@link DebuggerEndpoint#getUpdatedAtMillis} (when it last reported) as a hint, and when a connection is refused, call this again and reconnect. + * + * @return the endpoints (never null; empty when no project is open or no app has reported) + * @throws SecurityException + * if the plugin lacks the {@code debugger.endpoints} permission + * @throws IllegalStateException + * if called on the main thread, or if the IDE's database could not be read. A failed read is not the same as no apps: keep what you had and try again later + */ + @NonNull + List getEndpoints(); +} diff --git a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt index c54581cc1f..c0db691a08 100644 --- a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt +++ b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt @@ -54,6 +54,7 @@ enum class PluginPermission( PROJECT_STRUCTURE("project.structure", "Modify project structure"), NATIVE_CODE("native.code", "Execute native machine code"), IDE_ENVIRONMENT_WRITE("ide.environment.write", "Write to IDE-managed directories such as the Android SDK, NDK, and cache"), + DEBUGGER_ENDPOINTS("debugger.endpoints", "Read the port and token of the open project's SQLite debugger servers"), } data class PluginInfo( diff --git a/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/DebuggerEndpointTest.java b/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/DebuggerEndpointTest.java new file mode 100644 index 0000000000..db35c1407d --- /dev/null +++ b/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/DebuggerEndpointTest.java @@ -0,0 +1,56 @@ +package com.itsaky.androidide.plugins.services; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.itsaky.androidide.plugins.PluginPermission; +import org.junit.Test; + +public class DebuggerEndpointTest { + + @Test + public void equalityCoversEveryField() { + final DebuggerEndpoint base = new DebuggerEndpoint("a", 1, "t", 2L); + assertEquals(base, new DebuggerEndpoint("a", 1, "t", 2L)); + assertEquals(base.hashCode(), new DebuggerEndpoint("a", 1, "t", 2L).hashCode()); + assertNotEquals(base, new DebuggerEndpoint("b", 1, "t", 2L)); + assertNotEquals(base, new DebuggerEndpoint("a", 9, "t", 2L)); + assertNotEquals(base, new DebuggerEndpoint("a", 1, "u", 2L)); + assertNotEquals(base, new DebuggerEndpoint("a", 1, "t", 3L)); + } + + @Test + public void exposesWhatItWasBuiltWith() { + final DebuggerEndpoint endpoint = new DebuggerEndpoint("com.example.app", 43210, "secret", 1234L); + assertEquals("com.example.app", endpoint.getApplicationId()); + assertEquals(43210, endpoint.getPort()); + assertEquals("secret", endpoint.getToken()); + assertEquals(1234L, endpoint.getUpdatedAtMillis()); + } + + @Test + public void nullApplicationIdOrTokenIsRejected() { + try { + new DebuggerEndpoint(null, 1, "t", 0L); + fail(); + } catch (NullPointerException expected) {} + try { + new DebuggerEndpoint("a", 1, null, 0L); + fail(); + } catch (NullPointerException expected) {} + } + + @Test + public void permissionKeyIsStable() { + assertEquals("debugger.endpoints", PluginPermission.DEBUGGER_ENDPOINTS.getKey()); + assertTrue(DebuggerEndpointService.CONTRACT_VERSION >= 1); + } + + @Test + public void toStringDoesNotLeakTheToken() { + assertFalse(new DebuggerEndpoint("a", 1, "hunter2", 2L).toString().contains("hunter2")); + } +} diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt index 03e42340e7..d6d1b57665 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt @@ -42,6 +42,7 @@ import com.itsaky.androidide.plugins.manager.loaders.toPluginMetadata import com.itsaky.androidide.plugins.manager.project.PluginProjectManager import com.itsaky.androidide.plugins.manager.security.PluginSecurityManager import com.itsaky.androidide.plugins.manager.services.CogoProjectProvider +import com.itsaky.androidide.plugins.manager.services.DebuggerEndpointServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeArchiveServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeCommandServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeEditorServiceImpl @@ -62,6 +63,7 @@ import com.itsaky.androidide.plugins.manager.services.IdeUIServiceImpl import com.itsaky.androidide.plugins.manager.services.PluginBuildService import com.itsaky.androidide.plugins.manager.snippets.PluginSnippetManager import com.itsaky.androidide.plugins.manager.ui.PluginEditorTabManager +import com.itsaky.androidide.plugins.services.DebuggerEndpointService import com.itsaky.androidide.plugins.services.IdeArchiveService import com.itsaky.androidide.plugins.services.IdeBuildService import com.itsaky.androidide.plugins.services.IdeCommandService @@ -1577,6 +1579,19 @@ class PluginManager private constructor( IdeFeatureFlagServiceImpl() } + registerServiceWithErrorHandling( + pluginServiceRegistry, + DebuggerEndpointService::class.java, + pluginId, + "debugger_endpoint", + ) { + DebuggerEndpointServiceImpl( + pluginId = pluginId, + permissions = permissions, + projectRootProvider = { projectProvider.getCurrentProject()?.rootDir }, + ) + } + registerServiceWithErrorHandling( pluginServiceRegistry, IdeTemplateService::class.java, @@ -1846,6 +1861,19 @@ class PluginManager private constructor( IdeFeatureFlagServiceImpl() } + registerServiceWithErrorHandling( + pluginServiceRegistry, + DebuggerEndpointService::class.java, + pluginId, + "debugger_endpoint", + ) { + DebuggerEndpointServiceImpl( + pluginId = pluginId, + permissions = permissions, + projectRootProvider = { projectProvider.getCurrentProject()?.rootDir }, + ) + } + registerServiceWithErrorHandling( pluginServiceRegistry, IdeTemplateService::class.java, diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt new file mode 100644 index 0000000000..9b8d180845 --- /dev/null +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt @@ -0,0 +1,65 @@ +package com.itsaky.androidide.plugins.manager.services + +import android.os.Looper +import com.itsaky.androidide.plugins.PluginPermission +import com.itsaky.androidide.plugins.services.DebuggerEndpoint +import com.itsaky.androidide.plugins.services.DebuggerEndpointService +import org.slf4j.LoggerFactory +import java.io.File +import java.util.concurrent.CancellationException + +/** + * Where the host keeps what apps reported: the app module's `debugger_endpoint_table`. The app + * installs an implementation with [DebuggerEndpointSources.install]; this module cannot reach the + * table itself. + */ +fun interface DebuggerEndpointSource { + /** Returns the endpoints stored for the project at [projectLocation], as it appears in `recent_project_table.location`. */ + fun endpointsFor(projectLocation: String): List +} + +object DebuggerEndpointSources { + @Volatile + var current: DebuggerEndpointSource = DebuggerEndpointSource { emptyList() } + private set + + /** Installs the app's source, or restores the empty default when [source] is null. */ + fun install(source: DebuggerEndpointSource?) { + current = source ?: DebuggerEndpointSource { emptyList() } + } +} + +class DebuggerEndpointServiceImpl( + private val pluginId: String, + private val permissions: Set, + private val projectRootProvider: () -> File?, + private val sourceProvider: () -> DebuggerEndpointSource = { DebuggerEndpointSources.current }, + private val isMainThread: () -> Boolean = { Looper.myLooper() == Looper.getMainLooper() }, +) : DebuggerEndpointService { + override fun getEndpoints(): List { + if (PluginPermission.DEBUGGER_ENDPOINTS !in permissions) { + throw SecurityException( + "Plugin $pluginId does not have required permissions: ${PluginPermission.DEBUGGER_ENDPOINTS.name}", + ) + } + + check(!isMainThread()) { "DebuggerEndpointService.getEndpoints() reads a database; call it off the main thread" } + + val root = projectRootProvider() ?: return emptyList() + return try { + sourceProvider().endpointsFor(root.absolutePath) + } catch (e: InterruptedException) { + Thread.currentThread().interrupt() + throw e + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("getEndpoints failed for plugin {}", pluginId, e) + throw IllegalStateException("Could not read the debugger endpoints: ${e.message}", e) + } + } + + private companion object { + private val log = LoggerFactory.getLogger(DebuggerEndpointServiceImpl::class.java) + } +} diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt new file mode 100644 index 0000000000..4d6d1d4e11 --- /dev/null +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt @@ -0,0 +1,103 @@ +package com.itsaky.androidide.plugins.manager.services + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.plugins.PluginPermission +import com.itsaky.androidide.plugins.services.DebuggerEndpoint +import org.junit.Assert.assertThrows +import org.junit.Test +import java.io.File + +class DebuggerEndpointServiceImplTest { + private val project = File("/data/projects/demo") + private val endpoint = DebuggerEndpoint("com.example.demo", 4321, "tok", 99L) + private val seen = mutableListOf() + private val source = + DebuggerEndpointSource { location -> + seen += location + if (location == project.absolutePath) listOf(endpoint) else emptyList() + } + + private fun service( + permissions: Set = setOf(PluginPermission.DEBUGGER_ENDPOINTS), + root: File? = project, + source: DebuggerEndpointSource = this.source, + mainThread: Boolean = false, + ) = DebuggerEndpointServiceImpl("p", permissions, { root }, { source }, { mainThread }) + + @Test + fun `returns the endpoints stored for the open project`() { + assertThat(service().getEndpoints()).containsExactly(endpoint) + assertThat(seen).containsExactly(project.absolutePath) + } + + @Test + fun `is empty and never asks the source when no project is open`() { + assertThat(service(root = null).getEndpoints()).isEmpty() + assertThat(seen).isEmpty() + } + + @Test + fun `is empty when the project has no endpoint`() { + assertThat(service(root = File("/data/projects/other")).getEndpoints()).isEmpty() + } + + @Test + fun `refuses a plugin without the permission`() { + val denied = service(permissions = setOf(PluginPermission.FILESYSTEM_READ, PluginPermission.NETWORK_ACCESS)) + + assertThrows(SecurityException::class.java) { denied.getEndpoints() } + assertThat(seen).isEmpty() + } + + @Test + fun `a failing source is reported, not mistaken for no apps`() { + val cause = IllegalStateException("db closed") + val failing = service(source = { throw cause }) + + val thrown = assertThrows(IllegalStateException::class.java) { failing.getEndpoints() } + assertThat(thrown).hasCauseThat().isSameInstanceAs(cause) + } + + @Test + fun `an interrupt from the source is rethrown unchanged and keeps the flag`() { + val interrupted = service(source = { throw InterruptedException("stop") }) + + try { + val thrown = assertThrows(InterruptedException::class.java) { interrupted.getEndpoints() } + assertThat(thrown).hasMessageThat().isEqualTo("stop") + assertThat(Thread.currentThread().isInterrupted).isTrue() + } finally { + Thread.interrupted() + } + } + + @Test + fun `a cancellation from the source is rethrown unchanged`() { + val cancelled = service(source = { throw java.util.concurrent.CancellationException("cancelled") }) + + val thrown = assertThrows(java.util.concurrent.CancellationException::class.java) { cancelled.getEndpoints() } + assertThat(thrown).hasMessageThat().isEqualTo("cancelled") + } + + @Test + fun `refuses to read on the main thread`() { + val onMain = service(mainThread = true) + + assertThrows(IllegalStateException::class.java) { onMain.getEndpoints() } + assertThat(seen).isEmpty() + } + + @Test + fun `the default source is empty until the app installs one`() { + DebuggerEndpointSources.install(null) + val defaulted = DebuggerEndpointServiceImpl("p", setOf(PluginPermission.DEBUGGER_ENDPOINTS), { project }, isMainThread = { false }) + assertThat(defaulted.getEndpoints()).isEmpty() + + DebuggerEndpointSources.install(source) + try { + assertThat(defaulted.getEndpoints()).containsExactly(endpoint) + } finally { + DebuggerEndpointSources.install(null) + } + } +} diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 8cc1ab441f..43304c94ca 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -24,6 +24,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `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). +- Plugins get the stored endpoints through `DebuggerEndpointService` (plugin API), which needs the `debugger.endpoints` permission. `getEndpoints()` returns one entry per app of the open project that has reported (application ID, port, token, last update), read fresh on every call and not on the main thread, so a plugin asks again after a refused connection. Apps that are no longer installed are left out; an app whose process died is still listed until it reports again. The AI-Agent-MCP plugin (addons repository) is the first client. ### The event record @@ -51,5 +52,4 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han ## Not done yet - 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). - A device run of the current code. The device results on ADFA-7135 (statements captured on both ABIs, the overhead) predate the review fixes.