diff --git a/app/src/main/java/com/itsaky/androidide/fragments/output/BuildOutputBuffer.kt b/app/src/main/java/com/itsaky/androidide/fragments/output/BuildOutputBuffer.kt
new file mode 100644
index 0000000000..1e3e28f5a4
--- /dev/null
+++ b/app/src/main/java/com/itsaky/androidide/fragments/output/BuildOutputBuffer.kt
@@ -0,0 +1,160 @@
+/*
+ * This file is part of AndroidIDE.
+ *
+ * AndroidIDE is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * AndroidIDE is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with AndroidIDE. If not, see .
+ */
+
+package com.itsaky.androidide.fragments.output
+
+import kotlinx.coroutines.channels.Channel
+
+/**
+ * Thread-safe pending build output with fixed memory and batch budgets.
+ *
+ * Inputs are indivisible unless one exceeds [maxPendingChars], in which case only its newest tail
+ * is retained. Older pending output is evicted first, while batches preserve the retained order.
+ */
+internal class BuildOutputBuffer(
+ private val maxPendingChars: Int = DEFAULT_MAX_PENDING_CHARS,
+ private val maxBatchChars: Int = DEFAULT_MAX_BATCH_CHARS,
+) {
+ data class Batch(
+ val text: String,
+ val sessionToken: Int,
+ val sourceChars: Int,
+ val omittedLines: Long,
+ )
+
+ private sealed interface Entry {
+ val sessionToken: Int
+
+ data class Text(
+ val value: String,
+ override val sessionToken: Int,
+ ) : Entry
+
+ data class Omission(
+ var lineCount: Long,
+ var sourceChars: Int,
+ override val sessionToken: Int,
+ ) : Entry
+ }
+
+ private val entries = ArrayDeque()
+ private val available = Channel(Channel.CONFLATED)
+ private val lock = Any()
+ private var retainedChars = 0
+
+ internal val pendingChars: Int
+ get() = synchronized(lock) { retainedChars }
+
+ init {
+ require(maxPendingChars > 0) { "maxPendingChars must be positive" }
+ require(maxBatchChars > 0) { "maxBatchChars must be positive" }
+ }
+
+ fun offer(
+ text: String,
+ sessionToken: Int,
+ ) {
+ if (text.isEmpty()) return
+ val normalized = if (text.endsWith('\n')) text else "$text\n"
+ synchronized(lock) {
+ val existingOmission = entries.firstOrNull() as? Entry.Omission
+ if (existingOmission != null) entries.removeFirst()
+
+ var retained = normalized
+ var omittedLines = existingOmission?.lineCount ?: 0
+ var omittedChars = existingOmission?.sourceChars ?: 0
+ if (retained.length > maxPendingChars) {
+ val droppedPrefix = retained.dropLast(maxPendingChars)
+ omittedLines += lineCount(droppedPrefix)
+ omittedChars = saturatedAdd(omittedChars, droppedPrefix.length)
+ retained = retained.takeLast(maxPendingChars)
+ }
+ while (retainedChars > maxPendingChars - retained.length) {
+ val evicted = entries.removeFirst() as Entry.Text
+ retainedChars -= evicted.value.length
+ omittedLines += lineCount(evicted.value)
+ omittedChars = saturatedAdd(omittedChars, evicted.value.length)
+ }
+
+ if (omittedLines > 0) {
+ entries.addFirst(Entry.Omission(omittedLines, omittedChars, sessionToken))
+ }
+ entries.addLast(Entry.Text(retained, sessionToken))
+ retainedChars += retained.length
+ available.trySend(Unit)
+ }
+ }
+
+ suspend fun takeBatch(): Batch {
+ while (true) {
+ available.receive()
+ val batch = synchronized(lock) { takeAvailableBatch() }
+ if (batch != null) return batch
+ }
+ }
+
+ fun clear() {
+ synchronized(lock) {
+ entries.clear()
+ retainedChars = 0
+ while (available.tryReceive().isSuccess) {
+ // Discard stale wakeups from the cleared build session.
+ }
+ }
+ }
+
+ private fun takeAvailableBatch(): Batch? {
+ if (entries.isEmpty()) return null
+ val sessionToken = entries.first().sessionToken
+ val batch = StringBuilder(minOf(retainedChars, maxBatchChars))
+ var sourceChars = 0
+ var omittedLines = 0L
+ while (entries.isNotEmpty()) {
+ val entry = entries.first()
+ if (entry.sessionToken != sessionToken) break
+ if (entry is Entry.Text && batch.isNotEmpty() && batch.length + entry.value.length > maxBatchChars) break
+
+ entries.removeFirst()
+ when (entry) {
+ is Entry.Text -> {
+ batch.append(entry.value)
+ retainedChars -= entry.value.length
+ sourceChars = saturatedAdd(sourceChars, entry.value.length)
+ }
+
+ is Entry.Omission -> {
+ omittedLines += entry.lineCount
+ sourceChars = saturatedAdd(sourceChars, entry.sourceChars)
+ }
+ }
+ }
+ if (entries.isNotEmpty()) available.trySend(Unit)
+ return Batch(batch.toString(), sessionToken, sourceChars, omittedLines)
+ }
+
+ private fun lineCount(text: String): Long = text.count { it == '\n' }.toLong() + if (text.endsWith('\n')) 0 else 1
+
+ private fun saturatedAdd(
+ left: Int,
+ right: Int,
+ ): Int = (left.toLong() + right).coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
+
+ companion object {
+ private const val DEFAULT_MAX_PENDING_CHARS = 256 * 1024
+ private const val DEFAULT_MAX_BATCH_CHARS = 32 * 1024
+ }
+}
diff --git a/app/src/main/java/com/itsaky/androidide/fragments/output/BuildOutputFragment.kt b/app/src/main/java/com/itsaky/androidide/fragments/output/BuildOutputFragment.kt
index d85d34d867..3a4d74154a 100644
--- a/app/src/main/java/com/itsaky/androidide/fragments/output/BuildOutputFragment.kt
+++ b/app/src/main/java/com/itsaky/androidide/fragments/output/BuildOutputFragment.kt
@@ -37,8 +37,6 @@ import com.itsaky.androidide.utils.dpToPx
import com.itsaky.androidide.utils.flashInfo
import com.itsaky.androidide.viewmodel.BuildOutputViewModel
import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.channels.Channel
-import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.drop
@@ -62,7 +60,9 @@ class BuildOutputFragment :
override val currentEditor: IDEEditor? get() = editor
- private val logChannel = Channel(Channel.UNLIMITED)
+ // Fixed pending budget: a flooding build drops its oldest queued lines behind one omission
+ // marker instead of holding an unlimited backlog in memory until the editor catches up.
+ private val outputBuffer = BuildOutputBuffer(maxBatchChars = MAX_BATCH_CHARS)
private var searchLayout: EditorSearchLayout? = null
private var filterBar: LogFilterBarController? = null
@@ -353,9 +353,8 @@ class BuildOutputFragment :
// Avoid forcing the activityViewModels lazy init (which calls requireActivity())
// when the fragment is detached, otherwise an IllegalStateException is thrown.
if (!isAdded || activity == null) return
- while (logChannel.tryReceive().isSuccess) {
- // Discard: these lines belong to the session being cleared.
- }
+ // Discard: these lines belong to the session being cleared.
+ outputBuffer.clear()
// Invalidate in-flight flushes before deleting content, so a batch drained from the
// channel earlier cannot re-seed the cleared session.
sessionGeneration++
@@ -381,35 +380,7 @@ class BuildOutputFragment :
fun appendOutput(output: String?) {
if (!output.isNullOrEmpty()) {
- logChannel.trySend(output)
- }
- }
-
- /**
- * Ensures the string ends with a newline character (`\n`).
- * Useful for maintaining correct formatting when concatenating log lines.
- */
- private fun String.ensureNewline(): String = if (endsWith('\n')) this else "$this\n"
-
- /**
- * Immediately drains (consumes) all available messages from the channel into the [buffer].
- *
- * This is a **non-blocking** operation that enables batching, grouping hundreds of pending lines
- * into a single memory operation to avoid saturating the UI queue.
- */
- private fun ReceiveChannel.drainTo(buffer: StringBuilder) {
- // Bounded: the main thread word-wraps each batch in one appendBatch call, so draining a
- // flooding build in one go stalled it into an ANR (WordwrapLayout.afterInsert). The rest
- // stays queued for the next batch.
- if (buffer.length >= MAX_BATCH_CHARS) return
- var result = tryReceive()
- while (result.isSuccess) {
- val line = result.getOrNull()
- if (!line.isNullOrEmpty()) {
- buffer.append(line.ensureNewline())
- }
- if (buffer.length >= MAX_BATCH_CHARS) return
- result = tryReceive()
+ outputBuffer.offer(output, sessionGeneration)
}
}
@@ -420,21 +391,15 @@ class BuildOutputFragment :
* 2. Wakes up and drains the entire queue (Batching).
* 3. Sends the complete block to the UI in a single pass.
*/
- private suspend fun processLogs() =
- with(StringBuilder()) {
- for (firstLine in logChannel) {
- val sessionGenAtDrain = sessionGeneration
- val editorGenAtDrain = editorContentGeneration
- append(firstLine.ensureNewline())
- logChannel.drainTo(this)
-
- if (isNotEmpty()) {
- val batchText = toString()
- clear()
- flushToEditor(batchText, sessionGenAtDrain, editorGenAtDrain)
- }
- }
+ private suspend fun processLogs() {
+ while (true) {
+ val batch = outputBuffer.takeBatch()
+ val editorGenAtDrain = editorContentGeneration
+ // A batch queued before clearOutput() belongs to the previous build.
+ if (batch.sessionToken != sessionGeneration) continue
+ flushToEditor(batch.text, batch.omittedLines, batch.sessionToken, editorGenAtDrain)
}
+ }
/**
* Performs the safe UI update on the Main Thread.
@@ -448,6 +413,7 @@ class BuildOutputFragment :
*/
private suspend fun flushToEditor(
text: String,
+ omittedLines: Long,
sessionGen: Int,
editorGen: Int,
) {
@@ -456,13 +422,16 @@ class BuildOutputFragment :
if (sessionGen != sessionGeneration) return
// The editor shows only the lines matching the current filter; the file keeps them all.
+ // The omission marker is shown whatever the filter, so dropped output is never silent.
+ val omissionMarker = if (omittedLines > 0) formatOmissionMarker(omittedLines) else ""
val visibleText =
- BuildOutputViewModel.filterLines(
- text,
- buildOutputViewModel.filterText.value,
- buildOutputViewModel.showTimestamps.value,
- buildOutputViewModel.showDeltas.value,
- )
+ omissionMarker +
+ BuildOutputViewModel.filterLines(
+ text,
+ buildOutputViewModel.filterText.value,
+ buildOutputViewModel.showTimestamps.value,
+ buildOutputViewModel.showDeltas.value,
+ )
if (visibleText.isEmpty()) {
return
}
@@ -529,6 +498,13 @@ class BuildOutputFragment :
* until they ANR'd. Trims the editor's own (already filtered) text rather than re-reading the
* session file, whose writer can lag the editor. Call on the main thread under [editorContentMutex].
*/
+ private fun formatOmissionMarker(lineCount: Long): String {
+ val quantity = lineCount.coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
+ return resources
+ .getQuantityString(R.plurals.msg_build_output_lines_omitted, quantity, lineCount)
+ .plus('\n')
+ }
+
private fun IDEEditor.trimToWindow() {
if (isReleased) return
val tail = BuildOutputViewModel.editorTail(text) ?: return
diff --git a/app/src/test/java/com/itsaky/androidide/fragments/output/BuildOutputBufferTest.kt b/app/src/test/java/com/itsaky/androidide/fragments/output/BuildOutputBufferTest.kt
new file mode 100644
index 0000000000..c93e736884
--- /dev/null
+++ b/app/src/test/java/com/itsaky/androidide/fragments/output/BuildOutputBufferTest.kt
@@ -0,0 +1,144 @@
+/*
+ * This file is part of AndroidIDE.
+ *
+ * AndroidIDE is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * AndroidIDE is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with AndroidIDE. If not, see .
+ */
+
+package com.itsaky.androidide.fragments.output
+
+import com.google.common.truth.Truth.assertThat
+import com.itsaky.androidide.viewmodel.BuildOutputViewModel
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+
+@RunWith(RobolectricTestRunner::class)
+class BuildOutputBufferTest {
+ private fun BuildOutputBuffer.offer(text: String) {
+ offer(text, sessionToken = 0)
+ }
+
+ @Test
+ fun `output below limits is emitted in order with one trailing newline`() =
+ runTest {
+ val buffer = BuildOutputBuffer(maxPendingChars = 64, maxBatchChars = 64)
+
+ buffer.offer("first")
+ buffer.offer("second\n")
+
+ assertThat(buffer.takeBatch().text).isEqualTo("first\nsecond\n")
+ }
+
+ @Test
+ fun `output is split into bounded batches without reordering`() =
+ runTest {
+ val buffer = BuildOutputBuffer(maxPendingChars = 64, maxBatchChars = 6)
+
+ buffer.offer("aa")
+ buffer.offer("bb")
+ buffer.offer("cc")
+
+ val first = buffer.takeBatch().text
+ val second = buffer.takeBatch().text
+ assertThat(first).isEqualTo("aa\nbb\n")
+ assertThat(second).isEqualTo("cc\n")
+ assertThat(first.length).isAtMost(6)
+ assertThat(second.length).isAtMost(6)
+ }
+
+ @Test
+ fun `one indivisible input may exceed the batch limit`() =
+ runTest {
+ val buffer = BuildOutputBuffer(maxPendingChars = 64, maxBatchChars = 4)
+
+ buffer.offer("oversized")
+
+ assertThat(buffer.takeBatch().text).isEqualTo("oversized\n")
+ }
+
+ @Test
+ fun `overflow evicts oldest output and keeps newest output`() =
+ runTest {
+ val buffer = BuildOutputBuffer(maxPendingChars = 11, maxBatchChars = 128)
+
+ buffer.offer("one")
+ buffer.offer("two")
+ buffer.offer("three")
+ buffer.offer("four")
+
+ val batch = buffer.takeBatch()
+ assertThat(batch.text).isEqualTo("three\nfour\n")
+ assertThat(batch.omittedLines).isEqualTo(2)
+ assertThat(batch.sourceChars).isEqualTo(19)
+ assertThat(buffer.pendingChars).isAtMost(11)
+ }
+
+ @Test
+ fun `oversized input retains its newest bounded tail`() =
+ runTest {
+ val buffer = BuildOutputBuffer(maxPendingChars = 8, maxBatchChars = 128)
+
+ buffer.offer("0123456789")
+
+ val batch = buffer.takeBatch()
+ assertThat(batch.text).isEqualTo("3456789\n")
+ assertThat(batch.omittedLines).isEqualTo(1)
+ assertThat(batch.sourceChars).isEqualTo(11)
+ assertThat(buffer.pendingChars).isEqualTo(0)
+ }
+
+ @Test
+ fun `clear resets pending output and overflow accounting`() =
+ runTest {
+ val buffer = BuildOutputBuffer(maxPendingChars = 4, maxBatchChars = 64)
+
+ buffer.offer("kept")
+ buffer.offer("dropped")
+ buffer.clear()
+ buffer.offer("new")
+
+ assertThat(buffer.takeBatch().text).isEqualTo("new\n")
+ }
+
+ @Test
+ fun `in-flight batch keeps the session token from its producer`() =
+ runTest {
+ val buffer = BuildOutputBuffer(maxPendingChars = 64, maxBatchChars = 64)
+
+ buffer.offer("old", sessionToken = 3)
+ val inFlight = buffer.takeBatch()
+ buffer.clear()
+ buffer.offer("new", sessionToken = 4)
+
+ assertThat(inFlight.sessionToken).isEqualTo(3)
+ assertThat(buffer.takeBatch().sessionToken).isEqualTo(4)
+ }
+
+ @Test
+ fun `refreshed tail applies filtering and timing visibility`() {
+ val prefix = BuildOutputViewModel.formatLinePrefix(1_722_000_000_000L, 42L)
+ val tail = prefix + "ignored\n" + prefix + "newest output\n"
+
+ val visible =
+ BuildOutputViewModel.filterLines(
+ tail,
+ query = "newest",
+ showTimestamps = false,
+ showDeltas = false,
+ )
+
+ assertThat(visible).isEqualTo("newest output\n")
+ }
+}
diff --git a/app/src/test/java/com/itsaky/androidide/fragments/output/BuildOutputFragmentDetachedTest.kt b/app/src/test/java/com/itsaky/androidide/fragments/output/BuildOutputFragmentDetachedTest.kt
index 8f871447a3..61c3066914 100644
--- a/app/src/test/java/com/itsaky/androidide/fragments/output/BuildOutputFragmentDetachedTest.kt
+++ b/app/src/test/java/com/itsaky/androidide/fragments/output/BuildOutputFragmentDetachedTest.kt
@@ -34,7 +34,8 @@ import org.robolectric.RobolectricTestRunner
* Both methods therefore guard with `if (!isAdded || activity == null) return`. These tests
* assert that a detached fragment does NOT crash and returns the safe no-op values; drop the
* guard and each call forces the activityViewModels delegate -> requireActivity() ->
- * IllegalStateException, taking the test RED.
+ * IllegalStateException, taking the test RED. [BuildOutputFragment.appendOutput] only queues into
+ * the fragment's own buffer, so it needs no guard; the last test pins that it stays safe.
*/
@RunWith(RobolectricTestRunner::class)
class BuildOutputFragmentDetachedTest {
@@ -67,4 +68,14 @@ class BuildOutputFragmentDetachedTest {
assertThat(content).isEmpty()
}
+
+ /** Verifies appendOutput() is a safe no-op on a detached fragment instead of crashing. */
+ @Test
+ fun `appendOutput on a detached fragment does not crash`() {
+ val fragment = BuildOutputFragment()
+
+ assertThat(fragment.isAdded).isFalse()
+
+ fragment.appendOutput("build output")
+ }
}
diff --git a/resources/src/main/res/values/strings.xml b/resources/src/main/res/values/strings.xml
index 34f17553e8..160fae28f4 100644
--- a/resources/src/main/res/values/strings.xml
+++ b/resources/src/main/res/values/strings.xml
@@ -837,6 +837,10 @@
Open a file to show its diagnostic results
Filter lines
No matching log entries found.
+
+ - [%1$d build output line omitted]
+ - [%1$d build output lines omitted]
+
No project source found for %1$s
Could not open the source for %1$s
No search matches found.