Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
b2aa2f8
ADFA-7178: Stop a plugin's shell command and all it started at its ti…
davidschachterADFA Nov 17, 2026
6b5ecba
ADFA-7178: Show control characters in a plugin's Terminal command line
davidschachterADFA Nov 17, 2026
6249342
ADFA-7178: Check a plugin's Terminal command with extglob on
davidschachterADFA Nov 17, 2026
f1d9248
ADFA-7178: Group commands only where setsid runs them in place
davidschachterADFA Nov 17, 2026
8028609
ADFA-7178: Reach children a command starts as an early stop lands
davidschachterADFA Nov 17, 2026
83edad4
ADFA-7178: Use the Terminal's setsid where Android's forks
davidschachterADFA Nov 17, 2026
472652f
ADFA-7178: Say when the Terminal's setsid is used
davidschachterADFA Nov 17, 2026
e4e9e7d
ADFA-7178: Pin the cancel paths' reader threads and the grace timing
davidschachterADFA Nov 17, 2026
7647dfb
ADFA-7178: Release the child-holding tests' shells once the readers read
davidschachterADFA Nov 17, 2026
0575806
Merge branch 'stage' into fix/ADFA-7178-plugin-command-stop
davidschachterADFA Nov 23, 2026
81984ca
ADFA-7178: Check a Terminal command's syntax on stdin
davidschachterADFA Nov 23, 2026
2c12dc4
Merge origin/stage into fix/ADFA-7178-plugin-command-stop
davidschachterADFA Nov 23, 2026
0c60cc2
ADFA-7178: Move the changelog entry under 26.48
davidschachterADFA Nov 23, 2026
ef32ab8
Merge origin/stage into fix/ADFA-7178-plugin-command-stop
davidschachterADFA Nov 24, 2026
2a703d3
Merge origin/stage into fix/ADFA-7178-plugin-command-stop
davidschachterADFA Nov 24, 2026
a62c780
ADFA-7178: Free a command's slot only once it has stopped; find setsi…
davidschachterADFA Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions docs/PLUGIN_API_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,23 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed]
= diffed from `plugin-api/src` history (predates the dump; symbol-accurate).

### 26.48 — unreleased
- **breaking — A `ShellCommand` stops at its timeout or `cancel()`, with every process it started** _(ADFA-7178)_
A timeout used to wait for the command to exit, and a stop killed only the command's own
process, never its children. Each command now runs in a process group of its own, and a
timeout, `cancel()` or `cancelAllCommands()` stops the whole group: SIGTERM, then SIGKILL
250 ms later. `await()` returns within a second of the timeout. A stopped command frees its slot,
and `await()` returns, once the group has stopped, so after a `cancel()` too it can take up to
about 750 ms.
On Android 11, whose `setsid` always forks, the IDE uses the Terminal's `setsid` instead, if that
one runs commands in place. Until the Terminal is installed, the IDE checks again as each command
starts, and meanwhile commands get no group of their own: a stop leaves their children running,
as before.
A command that exits on its own is never reported as timed out. If a background child still
holds its output 500 ms after the command exits, the child is stopped, and `await()` returns
within about 1.5 s of the exit. A command that exits before the IDE starts reading its output
is the exception: Java drains and closes the output as it exits, so such a child is not seen.
A child whose output goes elsewhere (`server >log 2>&1 &`) is left running, as is a process
that calls `setsid` itself.
- **added — Hear the editor open and close a project, and save a file** _(ADFA-3570)_ **[verified]**
`IdeProjectService.addProjectLifecycleListener(ProjectLifecycleListener)` calls
`onProjectOpened(projectDir)` when the editor starts opening a project (its sync does not wait
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,27 @@ import com.itsaky.androidide.plugins.extensions.CommandSpec
import com.itsaky.androidide.plugins.services.CommandExecution
import com.itsaky.androidide.plugins.services.IdeCommandService
import com.itsaky.androidide.utils.TermuxProcessEnvironment
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.cancel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.runInterruptible
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import java.io.BufferedReader
import java.io.Closeable
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.nio.file.InvalidPathException
import java.util.UUID
Expand All @@ -32,6 +39,9 @@ class IdeCommandServiceImpl internal constructor(
private val projectRootProvider: () -> File?,
private val appFilesDir: File,
private val gradleTaskRunner: GradleTaskRunner = GradleTaskRunner(IdeBuildServiceImpl.getInstance()::startTasks),
// Called as each shell command starts, never here: finding a usable setsid runs it, which a
// plugin that runs no shell command should not pay for as it loads.
private val processGroups: () -> ProcessGroups = { ProcessGroups.android(File(appFilesDir, "usr/bin/setsid")) },
) : IdeCommandService {
private val runningCommands = ConcurrentHashMap<String, RunningCommand>()

Expand Down Expand Up @@ -62,32 +72,43 @@ class IdeCommandServiceImpl internal constructor(
}
val processBuilder =
try {
shellProcess(spec, workDir)
shellProcess(listOf(spec.executable) + spec.arguments, spec.environment, workDir)
} catch (e: IllegalArgumentException) {
return RejectedCommandExecution(executionId, "Invalid environment: ${e.message}")
}
CommandExecutionImpl(executionId, processBuilder, timeoutMs)
CommandExecutionImpl(executionId, { startInGroup(processBuilder, workDir) }, timeoutMs)
}
}
runningCommands[executionId] = execution
execution.start { runningCommands.remove(executionId) }
return execution
}

/** Run by the command's coroutine, so that finding a usable setsid never holds up the caller. */
private fun startInGroup(
processBuilder: ProcessBuilder,
workDir: File?,
): StartedCommand {
val groups = processGroups()
val command = groups.isolate(processBuilder.command(), workDir)
return StartedCommand(processBuilder.command(command.command).start(), command.grouped, groups)
}

private fun shellProcess(
spec: CommandSpec.ShellCommand,
command: List<String>,
environment: Map<String, String>,
workDir: File?,
): ProcessBuilder =
ProcessBuilder(listOf(spec.executable) + spec.arguments).apply {
ProcessBuilder(command).apply {
workDir?.let { directory(it) }
environment().putAll(spec.environment)
environment().putAll(environment)
redirectErrorStream(false)
TermuxProcessEnvironment.applyTo(environment(), appFilesDir)
}

override fun isCommandRunning(executionId: String): Boolean = runningCommands[executionId]?.isRunning() == true

// onComplete removes the entry: a GradleTask stays running until Gradle has stopped.
// onComplete removes the entry: a command keeps its slot until it has stopped.
override fun cancelCommand(executionId: String): Boolean =
runningCommands[executionId]?.let {
it.cancel()
Expand All @@ -96,11 +117,9 @@ class IdeCommandServiceImpl internal constructor(

override fun getRunningCommandCount(): Int = runningCommands.size

// As with cancelCommand, each command frees its slot once it has stopped.
fun cancelAllCommands() {
runningCommands.entries.removeAll { (_, execution) ->
execution.cancel()
true
}
runningCommands.values.forEach { it.cancel() }
}

private fun requirePermission() {
Expand All @@ -124,126 +143,191 @@ class IdeCommandServiceImpl internal constructor(
}
}

/** A started shell command: its process, which leads a group of its own if [grouped], and what stops it. */
internal class StartedCommand(
val process: Process,
val grouped: Boolean,
val processGroups: ProcessGroups,
)

internal interface RunningCommand : CommandExecution {
/** Starts the command; [onComplete] runs once it ends or is cancelled. */
/** Starts the command; [onComplete] runs once it has ended, or has stopped after a cancel. */
fun start(onComplete: () -> Unit)

fun isRunning(): Boolean
}

private class CommandExecutionImpl(
/**
* A shell command. However it ends - on its own, by timing out, by [cancel], or with an error -
* nothing it started is left running and no thread is left reading its output, with two
* exceptions. A command that exits on its own with its output closed may leave a process behind on
* purpose, as `nohup server >log 2>&1 &` does. And a process that left the group with its own
* `setsid` is not stopped; on a desktop JVM, its reader is not freed either. Its slot is freed, and
* [await] returns, only once that is done.
*
* @param startCommand starts the process, on the command's coroutine.
* @param outputGraceMs how long output may stay open once the command has exited.
*/
internal class CommandExecutionImpl(
override val executionId: String,
private val processBuilder: ProcessBuilder,
private val startCommand: () -> StartedCommand,
private val timeoutMs: Long,
private val outputGraceMs: Long = OUTPUT_GRACE_MS,
) : RunningCommand {
private val outputChannel = Channel<CommandOutput>(capacity = Channel.UNLIMITED)
private val resultDeferred = CompletableDeferred<CommandResult>()
private val scope = CoroutineScope(Dispatchers.IO + Job())
private var process: Process? = null
private val stdoutBuilder = StringBuilder()
private val stderrBuilder = StringBuilder()

// Also run by cancel(): a cancel landing before the launched body starts skips its call.
@Volatile
private var onComplete: () -> Unit = {}

override val output: Flow<CommandOutput> = outputChannel.receiveAsFlow()

override fun start(onComplete: () -> Unit) {
this.onComplete = onComplete
scope.launch {
val startTime = System.currentTimeMillis()

runCatching {
withTimeout(timeoutMs) {
process = processBuilder.start()
val proc = process!!
private var process: Process? = null

val stdoutJob = launch { readStream(proc, isStdErr = false) }
val stderrJob = launch { readStream(proc, isStdErr = true) }
@Volatile
private var startTime = 0L

val exitCode = proc.waitFor()
stdoutJob.join()
stderrJob.join()
@Volatile
private var result: CommandResult? = null

outputChannel.send(CommandOutput.ExitCode(exitCode))
outputChannel.close()
// Appended to by the reader threads, read by whichever thread ends the command.
private val stdoutBuilder = StringBuilder()
private val stderrBuilder = StringBuilder()

val duration = System.currentTimeMillis() - startTime
if (exitCode == 0) {
CommandResult.Success(exitCode, stdoutBuilder.toString(), stderrBuilder.toString(), duration)
} else {
CommandResult.Failure(exitCode, stdoutBuilder.toString(), stderrBuilder.toString(), null, duration)
}
}
}.onSuccess { result ->
resultDeferred.complete(result)
}.onFailure { e ->
process?.destroyForcibly()
outputChannel.close()
val stdout = stdoutBuilder.toString()
val stderr = stderrBuilder.toString()
val duration = System.currentTimeMillis() - startTime
val failureResult =
when (e) {
is kotlinx.coroutines.TimeoutCancellationException -> {
CommandResult.Failure(-1, stdout, stderr, "Command timed out after ${timeoutMs}ms: ${e.message}", duration)
}
override val output: Flow<CommandOutput> = outputChannel.receiveAsFlow()

is kotlinx.coroutines.CancellationException -> {
CommandResult.Cancelled(stdout, stderr)
}
override fun start(onComplete: () -> Unit) {
startTime = System.currentTimeMillis()
val job = scope.launch { result = runCommand() }
// However the coroutine ends: also when a cancel() before it ran skipped its body, or when
// stopping the command threw.
job.invokeOnCompletion { cause ->
val stdout = snapshot(stdoutBuilder)
val stderr = snapshot(stderrBuilder)
outputChannel.close()
// First, so that a caller resuming from await() finds the slot free.
onComplete()
resultDeferred.complete(
result ?: when (cause) {
is CancellationException -> CommandResult.Cancelled(stdout, stderr)
else -> CommandResult.Failure(-1, stdout, stderr, "Unexpected error: ${cause?.message}", duration())
},
)
}
}

else -> {
CommandResult.Failure(-1, stdout, stderr, "Unexpected error: ${e.message}", duration)
}
}
if (resultDeferred.isActive) {
resultDeferred.complete(failureResult)
private suspend fun runCommand(): CommandResult {
var started: StartedCommand? = null
var readers = emptyList<Job>()
var exitCode: Int? = null
var outputClosed = false
var cancelled = false
var error: Throwable? = null
try {
withTimeoutOrNull(timeoutMs) {
// Recorded before the next suspension point, so that a cancel() landing while
// startCommand() ran, when there was no process yet to stop, has the finally below
// stop it (ADFA-7109).
val command = startCommand()
started = command
process = command.process
readers =
listOf(
readLines(command.process.inputStream, isStdErr = false),
readLines(command.process.errorStream, isStdErr = true),
)
// Interruptible, so that the timeout and cancel() end the wait at once.
runInterruptible { command.process.waitFor() }
}
// Read from the process, not the block's result: one that exits just as the time runs
// out ended on its own.
exitCode = started?.process?.takeUnless { it.isAlive }?.exitValue()
if (exitCode != null) {
// Not under the timeout: the command has ended. A background child can hold the
// output open long after that, and is then stopped below. Unless no reader was in
// read() yet when the command exited: Process then drains the pipe and closes its
// end (ProcessPipeInputStream.processExited), so the output looks closed.
outputClosed = withTimeoutOrNull(outputGraceMs) { readers.joinAll() } != null
}
} catch (e: CancellationException) {
cancelled = true
} catch (e: Throwable) {
// An Error too, as stage's runCatching did: it ends the command, not the IDE.
error = e
} finally {
withContext(NonCancellable) {
started?.let { command ->
if (exitCode == null || !outputClosed) command.processGroups.stop(command.process, command.grouped)
// Ends the reads of any process that escaped the group or outlived the kill.
// A desktop JVM, where the unit tests run, does not wake a read on close.
closeQuietly(command.process.inputStream, command.process.errorStream, command.process.outputStream)
}
withTimeoutOrNull(READERS_STOP_MS) { readers.joinAll() }
}
}

onComplete()
val stdout = snapshot(stdoutBuilder)
val stderr = snapshot(stderrBuilder)
exitCode?.let { outputChannel.trySend(CommandOutput.ExitCode(it)) }
return when {
error != null -> CommandResult.Failure(-1, stdout, stderr, "Unexpected error: ${error.message}", duration())
exitCode == 0 -> CommandResult.Success(0, stdout, stderr, duration())
exitCode != null -> CommandResult.Failure(exitCode, stdout, stderr, null, duration())
cancelled -> CommandResult.Cancelled(stdout, stderr)
else -> CommandResult.Failure(-1, stdout, stderr, "Command timed out after ${timeoutMs}ms", duration())
}
}

private suspend fun readStream(
process: Process,
private fun duration() = System.currentTimeMillis() - startTime

private fun readLines(
stream: InputStream,
isStdErr: Boolean,
) {
val stream = if (isStdErr) process.errorStream else process.inputStream
val builder = if (isStdErr) stderrBuilder else stdoutBuilder
BufferedReader(InputStreamReader(stream)).use { reader ->
var line = reader.readLine()
while (line != null) {
if (builder.length + line.length <= MAX_OUTPUT_BYTES) {
builder.appendLine(line)
): Job =
scope.launch {
val builder = if (isStdErr) stderrBuilder else stdoutBuilder
try {
BufferedReader(InputStreamReader(stream)).use { reader ->
while (true) {
val line = reader.readLine() ?: break
synchronized(builder) {
if (builder.length + line.length <= MAX_OUTPUT_BYTES) builder.appendLine(line)
}
outputChannel.trySend(if (isStdErr) CommandOutput.StdErr(line) else CommandOutput.StdOut(line))
}
}
val output = if (isStdErr) CommandOutput.StdErr(line) else CommandOutput.StdOut(line)
outputChannel.send(output)
line = reader.readLine()
} catch (e: IOException) {
// Closed under the read when the command was stopped.
}
}
}

private fun snapshot(builder: StringBuilder): String = synchronized(builder) { builder.toString() }

override suspend fun await(): CommandResult = resultDeferred.await()

override fun cancel() {
process?.destroyForcibly()
outputChannel.close()
if (resultDeferred.isActive) {
resultDeferred.complete(
CommandResult.Cancelled(stdoutBuilder.toString(), stderrBuilder.toString()),
)
}
// The command's coroutine stops the process and its group, then frees the slot and completes.
scope.cancel()
onComplete()
}

override fun isRunning(): Boolean = process?.isAlive == true

companion object {
private const val MAX_OUTPUT_BYTES = 10 * 1024 * 1024

/** How long output may stay open once the command has exited. */
const val OUTPUT_GRACE_MS = 500L

/** How long a reader may take to end once the command is stopped and its output closed. */
private const val READERS_STOP_MS = 500L
}
}

private fun closeQuietly(vararg closeables: Closeable) {
for (closeable in closeables) {
try {
closeable.close()
} catch (e: IOException) {
// An InterruptedIOException here (ADFA-3945) only means a read was cut short.
}
}
}

Expand Down
Loading
Loading