Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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<DebuggerEndpointRepository>().reportedEndpoints(File(location)) }
}
IdeTerminalServiceImpl.setSessionLauncher(PluginTerminalLauncher { application.foregroundActivity })
logger.info("Plugin services configured successfully")
}
Expand Down
7 changes: 6 additions & 1 deletion app/src/main/java/com/itsaky/androidide/di/AppModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<RecentProjectRepository> {
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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).
Expand All @@ -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,
Expand Down Expand Up @@ -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<PluginDebuggerEndpoint> =
dao.getByProjectLocation(projectDir.canonicalProjectLocation()).mapNotNull { row ->

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MINOR: reportedEndpoints returns every stored row with a token and port, with no age or liveness bound.

The row survives the app being killed or uninstalled (nothing in DebuggerEndpointDao clears token/port except clearEndpointIfProjectDiffers on a project move). A plugin calling getEndpoints() then gets a dead endpoint, and the bearer token goes to whatever listens on that port next. Not reachable as a bug today because the API docs tell callers to re-ask after a refused connection or 401/403 and the token only goes to 127.0.0.1, and the only consumer (addons#166) is in a separate PR I did not verify for this. A client that ignores updatedAtMillis is the one at risk.

Say in the KDoc here (or the plugin-api docs) that rows are not pruned, so clients treat updatedAtMillis as a hint, or filter out rows older than some bound.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6a99814: endpoints of apps that are no longer installed are left out (injected check; PackageManager in the app; every package is visible because Code on the Go targets SDK 28). The Javadoc now says an endpoint can still be stale after the process dies, that updatedAtMillis is when it last reported, and that clients reconnect after a refused connection.

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 `<queries>`.
*/
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)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Unit> {
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<Unit> {
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<android.app.Application>()
val packageManager = app.packageManager

assertThat(DebuggerEndpointRepository.isPackageInstalled(packageManager, app.packageName)).isTrue()
assertThat(DebuggerEndpointRepository.isPackageInstalled(packageManager, "com.example.not.installed")).isFalse()
}
}
14 changes: 14 additions & 0 deletions docs/PLUGIN_API_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<DebuggerEndpoint>`, 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
Expand Down
1 change: 1 addition & 0 deletions docs/PLUGIN_AUTHORING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion docs/plugin-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<meta-data>` 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/<abi>/libtree-sitter-<name>.so` exporting `tree_sitter_<name>`, 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/<pluginId>/` namespace.

Expand Down
17 changes: 17 additions & 0 deletions plugin-api/api/plugin-api.api
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 <init> (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
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>
* 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.
*
* <p>
* 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 + "}";
}
}
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>
* 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.
*
* <p>
* 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.
*
* <p>
* 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<DebuggerEndpoint> getEndpoints();
}
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading
Loading