diff --git a/plugins/AI-Core/build.gradle.kts b/plugins/AI-Core/build.gradle.kts index 6febd306..7d22df24 100644 --- a/plugins/AI-Core/build.gradle.kts +++ b/plugins/AI-Core/build.gradle.kts @@ -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 { diff --git a/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModel.kt b/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModel.kt index e13ced1d..e32c7274 100644 --- a/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModel.kt +++ b/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModel.kt @@ -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 /** @@ -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. diff --git a/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModelCompactionTest.kt b/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModelCompactionTest.kt index 2a265f0a..1adb077b 100644 --- a/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModelCompactionTest.kt +++ b/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModelCompactionTest.kt @@ -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 @@ -340,7 +341,7 @@ 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. */ @@ -348,7 +349,18 @@ class ChatViewModelCompactionTest { 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) { + runBlocking { withTimeout(WAIT_MS) { viewModel.awaitRun() } } } /** diff --git a/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModelPromptEditTest.kt b/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModelPromptEditTest.kt index 549f9168..d44e2868 100644 --- a/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModelPromptEditTest.kt +++ b/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModelPromptEditTest.kt @@ -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 @@ -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"), @@ -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 }, @@ -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)) @@ -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) } @@ -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() @@ -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 @@ -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) @@ -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)) @@ -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 } @@ -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] = diff --git a/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModelTitleQueueTest.kt b/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModelTitleQueueTest.kt index 053a81fa..1e6bc93b 100644 --- a/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModelTitleQueueTest.kt +++ b/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModelTitleQueueTest.kt @@ -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 @@ -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" },