Skip to content
Open
4 changes: 2 additions & 2 deletions plugins/AI-Core/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ android {
applicationId = "com.itsaky.androidide.plugins.aicore"
minSdk = 33
targetSdk = 36
versionCode = 11
versionName = "3.7.0"
versionCode = 12
versionName = "3.7.1"
}

buildFeatures {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,7 @@ class ChatViewModel(
private val toolSourcesChanged: () -> Unit = { rebuildAgentTools() }

/** The in-flight agent run (streaming + tool loop), so it can be cancelled. */
@Volatile
private var generationJob: Job? = null

/**
Expand Down Expand Up @@ -1496,6 +1497,15 @@ class ChatViewModel(
return true
}

/**
* Test hook: returns once the current run's `finally` has finished, `finishActivity()` and
* `persistState()` included. [canChangePrompts] turns true before that. Returns at once when
* there is no run, or when Stop has set the job to null.
*/
internal suspend fun awaitRun() {
generationJob?.join()
}

/**
* Holds a new prompt until a title still being written has finished, so the two never generate
* at once. Bounded by the title's own [ChatTitle.TIMEOUT_MS]; the title job settles itself.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import kotlinx.coroutines.withTimeout
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
Expand Down Expand Up @@ -340,15 +341,26 @@ class ChatViewModelCompactionTest {
val turns = sentHistories.size
viewModel.retryLastRun()
awaitCondition { sentHistories.size == turns + 1 && viewModel.agentState.value !is AgentState.Processing }
awaitCondition { viewModel.canChangePrompts.value || viewModel.agentState.value is AgentState.Error }
awaitRunUnwound(viewModel)
}

/** Sends [text] and waits for its run to finish. */
private fun send(viewModel: ChatViewModel, text: String) {
val turns = sentHistories.size
awaitCondition { viewModel.sendMessage(text) }
awaitCondition { sentHistories.size == turns + 1 && viewModel.agentState.value !is AgentState.Processing }
awaitCondition { viewModel.canChangePrompts.value || viewModel.agentState.value is AgentState.Error }
awaitRunUnwound(viewModel)
}

/**
* Waits for the run to finish, `finally` included: [ChatViewModel.canChangePrompts] turns true
* before the run has closed its activity line and saved, so it cannot say the run is done. A
* failed run ends in [AgentState.Error], which is why this does not check for Idle. Stopping at
* the error state instead let the next step read before the message existed, or call
* [ChatViewModel.retryLastRun] while the run was still in flight, which ignores it.
*/
private fun awaitRunUnwound(viewModel: ChatViewModel) {
Comment thread
hal-eisen-adfa marked this conversation as resolved.
Resolved
runBlocking { withTimeout(WAIT_MS) { viewModel.awaitRun() } }
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,21 @@ import io.mockk.mockk
import java.io.File
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import kotlinx.coroutines.withTimeout
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
Expand Down Expand Up @@ -167,15 +172,14 @@ class ChatViewModelPromptEditTest {
}
assertTrue(viewModel.sendMessage("build teh app"))
val prompt = awaitUserMessage(viewModel, "build teh app")
awaitCondition { viewModel.history.value.size == 2 && viewModel.runFinished() }
viewModel.awaitRunFinished()
awaitCondition { viewModel.history.value.size == 2 }

val result = viewModel.editPrompt(prompt, "build the app")

assertEquals(ChatViewModel.EditResult.STARTED, result)
awaitCondition {
viewModel.history.value.firstOrNull()?.content == "build the app" &&
viewModel.runFinished()
}
viewModel.awaitRunFinished()
awaitCondition { viewModel.history.value.firstOrNull()?.content == "build the app" }
assertEquals(listOf(Role.USER, Role.ASSISTANT), viewModel.history.value.map { it.role })
assertEquals(
listOf("build the app"),
Expand All @@ -194,9 +198,8 @@ class ChatViewModelPromptEditTest {
val result = viewModel.editPrompt(first, "build the release app")

assertEquals(ChatViewModel.EditResult.STARTED, result)
awaitCondition {
viewModel.history.value.size == 2 && viewModel.runFinished()
}
viewModel.awaitRunFinished()
awaitCondition { viewModel.history.value.size == 2 }
assertEquals(
listOf("build the release app"),
viewModel.messages.value.filter { it.sender == Sender.USER }.map { it.text },
Expand All @@ -214,9 +217,8 @@ class ChatViewModelPromptEditTest {
val first = sendAndAwait(viewModel, "build the app")
sendAndAwait(viewModel, "now run the tests")
viewModel.editPrompt(first, "build the release app")
awaitCondition {
viewModel.history.value.size == 2 && viewModel.runFinished()
}
viewModel.awaitRunFinished()
awaitCondition { viewModel.history.value.size == 2 }
val edited = viewModel.messages.value.first { it.sender == Sender.USER }.id

assertTrue(viewModel.switchPromptVersion(edited, -1))
Expand All @@ -238,9 +240,8 @@ class ChatViewModelPromptEditTest {
val first = sendAndAwait(viewModel, "build the app")
sendAndAwait(viewModel, "now run the tests")
viewModel.editPrompt(first, "build the release app")
awaitCondition {
viewModel.history.value.size == 2 && viewModel.runFinished()
}
viewModel.awaitRunFinished()
awaitCondition { viewModel.history.value.size == 2 }
viewModel.persistState()
awaitCondition { "now run the tests" in stored.getValue(SESSIONS_KEY) }

Expand All @@ -259,7 +260,8 @@ class ChatViewModelPromptEditTest {
val first = sendAndAwait(viewModel, "build the app")
sendAndAwait(viewModel, "now run the tests")
viewModel.editPrompt(first, "build the release app")
awaitCondition { viewModel.runFinished() && viewModel.history.value.size == 2 }
viewModel.awaitRunFinished()
awaitCondition { viewModel.history.value.size == 2 }

viewModel.clearMessages()

Expand Down Expand Up @@ -295,7 +297,7 @@ class ChatViewModelPromptEditTest {
composer.cancel()
val edited = viewModel.messages.value.single { it.sender == Sender.USER }
assertEquals(listOf(File("/project/Edited.kt").absolutePath), edited.contextFiles)
awaitCondition { viewModel.runFinished() }
viewModel.awaitRunFinished()
}

@Test
Expand All @@ -306,11 +308,13 @@ class ChatViewModelPromptEditTest {
val first = sendAndAwait(viewModel, "build the app")
sendAndAwait(viewModel, "now run the tests")
viewModel.editPrompt(first, "build the release app")
awaitCondition { viewModel.runFinished() && viewModel.history.value.size == 2 }
viewModel.awaitRunFinished()
awaitCondition { viewModel.history.value.size == 2 }
val version = viewModel.messages.value.single { it.sender == Sender.USER }.id

assertEquals(ChatViewModel.EditResult.STARTED, viewModel.editPrompt(version, "build the debug app"))
awaitCondition { viewModel.runFinished() && viewModel.history.value.size == 2 }
viewModel.awaitRunFinished()
awaitCondition { viewModel.history.value.size == 2 }

val replacement = viewModel.messages.value.single { it.sender == Sender.USER }
assertEquals("build the debug app", replacement.text)
Expand All @@ -329,7 +333,8 @@ class ChatViewModelPromptEditTest {
val first = sendAndAwait(viewModel, "build the app")
sendAndAwait(viewModel, "now run the tests")
viewModel.editPrompt(first, "build the release app")
awaitCondition { viewModel.runFinished() && viewModel.history.value.size == 2 }
viewModel.awaitRunFinished()
awaitCondition { viewModel.history.value.size == 2 }
val edited = viewModel.messages.value.single { it.sender == Sender.USER }.id

assertFalse(viewModel.switchPromptVersion(edited, 1))
Expand Down Expand Up @@ -375,14 +380,55 @@ class ChatViewModelPromptEditTest {
awaitCondition { viewModel.sendMessage("and run it") }
}

@Test
fun givenARunHeldAfterCanChangePromptsTurnsTrue_whenAwaitingTheRun_thenItWaitsForTheCleanup() {
val viewModel = newViewModelWithBackend { callback ->
callback.onComplete(LlmInferenceService.LlmResponse.success(RESPOND_REPLY, 4, 10))
}
val entered = CountDownLatch(1)
val release = CountDownLatch(1)
// Unconfined, so the callback runs on the run's thread inside the `finally`, right after
// it clears isGenerating and before finishActivity() and persistState().
val observer = CoroutineScope(Dispatchers.Unconfined).launch {
var sawBusy = false
viewModel.canChangePrompts.collect { idle ->
if (!idle) {
sawBusy = true
} else if (sawBusy) {
entered.countDown()
release.await(WAIT_MS, TimeUnit.MILLISECONDS)
}
}
}
try {
assertTrue(viewModel.sendMessage("build the app"))
assertTrue("run never reached its finally", entered.await(WAIT_MS, TimeUnit.MILLISECONDS))
assertTrue(viewModel.canChangePrompts.value)

// UNDISPATCHED runs awaitRun() on this thread up to its first suspension, so the waiter
// has already joined the run when the check below reads it; no timing window.
val waiting =
CoroutineScope(Dispatchers.Default).async(start = CoroutineStart.UNDISPATCHED) {
viewModel.awaitRun()
}
assertFalse("awaitRun() returned while the run was still in its finally", waiting.isCompleted)
release.countDown()
runBlocking { withTimeout(WAIT_MS) { waiting.await() } }
assertEquals(AgentState.Idle, viewModel.agentState.value)
awaitCondition { "build the app" in stored.getValue(SESSIONS_KEY) }
} finally {
release.countDown()
observer.cancel()
}
}

/** Sends [text], waits for its run to finish, and returns the prompt's message id. */
private fun sendAndAwait(viewModel: ChatViewModel, text: String): String {
val before = viewModel.history.value.size
assertTrue(viewModel.sendMessage(text))
val id = awaitUserMessage(viewModel, text)
awaitCondition {
viewModel.history.value.size == before + 2 && viewModel.runFinished()
}
viewModel.awaitRunFinished()
awaitCondition { viewModel.history.value.size == before + 2 }
return id
}

Expand Down Expand Up @@ -431,8 +477,15 @@ class ChatViewModelPromptEditTest {
}
}

private fun ChatViewModel.runFinished(): Boolean =
agentState.value == AgentState.Idle && canChangePrompts.value
/**
* Waits for the run to finish, `finally` included (it closes the activity line and saves after
* [ChatViewModel.canChangePrompts] has already turned true), then checks it ended Idle.
* Call it after the edit or send that starts the run, which has set the job by then.
*/
private fun ChatViewModel.awaitRunFinished() {
runBlocking { withTimeout(WAIT_MS) { awaitRun() } }
assertEquals(AgentState.Idle, agentState.value)
}

private fun seedTwoExchanges() {
stored[SESSIONS_KEY] =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,10 @@ class ChatViewModelTitleQueueTest {
assertTrue(viewModel.requestTitleIfUntitled(llmService, "add a dark mode toggle"))

assertTrue(SESSION_ID in viewModel.titlePending.value)
verify { llmService.generateCompletion(match { it.contains("add a dark mode toggle") }, any()) }
// The request runs on Dispatchers.IO, so the call can land after this line is reached.
verify(timeout = WAIT_MS) {
llmService.generateCompletion(match { it.contains("add a dark mode toggle") }, any())
}
}

@Test
Expand All @@ -264,7 +267,8 @@ class ChatViewModelTitleQueueTest {

assertTrue(viewModel.requestTitleIfUntitled(llmService, " add a dark mode toggle \n"))

verify {
// The request runs on Dispatchers.IO, so the call can land after this line is reached.
verify(timeout = WAIT_MS) {
llmService.generateCompletion(
any(),
match { it.extraParams?.get(ChatTitle.EXTRA_PARAM_SOURCE) == "add a dark mode toggle" },
Expand Down
Loading