From 7168758c16297f487e5d5ca8e50eb906819dd4b8 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 22:51:24 -0800 Subject: [PATCH 1/5] ADFA-7249 AI-Core: wait for a failed run to unwind in ChatViewModelCompactionTest A failed run sets AgentState.Error, adds its error message, and clears its in-flight flag last. send() and retry() stopped waiting at the error state, so the next step could read before the message existed, or retry while the run was still in flight, which ignores the retry. Both now wait on canChangePrompts, which turns true only after the flag is cleared. With a 300 ms sleep added before the flag is cleared (proof only), the old helpers fail and the new ones pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../viewmodel/ChatViewModelCompactionTest.kt | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) 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 2a265f0af..b45cb8364 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 @@ -340,7 +340,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 +348,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 until the run has unwound. A failed run sets [AgentState.Error] first, then adds its + * error message, and clears its in-flight flag last, in a `finally`; only then does + * [ChatViewModel.canChangePrompts] turn true ([AgentState.Error] doesn't count as running). + * 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) { + awaitCondition { viewModel.canChangePrompts.value } } /** From 0aad9fd8433f8853c1064fd004b004d3f333b8fc Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 22:51:24 -0800 Subject: [PATCH 2/5] ADFA-7249 AI-Core: wait for the run to unwind in ChatViewModelPromptEditTest A run sets AgentState.Idle before it clears its in-flight flag. The waits stopped at Idle, so editPrompt could return BUSY, a fork never started, or sendMessage returned false. They now also wait on canChangePrompts. The hunks are the same as in #154 (ADFA-6767), so both merge cleanly. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../viewmodel/ChatViewModelPromptEditTest.kt | 25 +++++++++++-------- 1 file changed, 14 insertions(+), 11 deletions(-) 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 d78dc8464..549f91683 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 @@ -167,14 +167,14 @@ class ChatViewModelPromptEditTest { } assertTrue(viewModel.sendMessage("build teh app")) val prompt = awaitUserMessage(viewModel, "build teh app") - awaitCondition { viewModel.history.value.size == 2 && viewModel.agentState.value == AgentState.Idle } + awaitCondition { viewModel.history.value.size == 2 && viewModel.runFinished() } val result = viewModel.editPrompt(prompt, "build the app") assertEquals(ChatViewModel.EditResult.STARTED, result) awaitCondition { viewModel.history.value.firstOrNull()?.content == "build the app" && - viewModel.agentState.value == AgentState.Idle + viewModel.runFinished() } assertEquals(listOf(Role.USER, Role.ASSISTANT), viewModel.history.value.map { it.role }) assertEquals( @@ -195,7 +195,7 @@ class ChatViewModelPromptEditTest { assertEquals(ChatViewModel.EditResult.STARTED, result) awaitCondition { - viewModel.history.value.size == 2 && viewModel.agentState.value == AgentState.Idle + viewModel.history.value.size == 2 && viewModel.runFinished() } assertEquals( listOf("build the release app"), @@ -215,7 +215,7 @@ class ChatViewModelPromptEditTest { sendAndAwait(viewModel, "now run the tests") viewModel.editPrompt(first, "build the release app") awaitCondition { - viewModel.history.value.size == 2 && viewModel.agentState.value == AgentState.Idle + viewModel.history.value.size == 2 && viewModel.runFinished() } val edited = viewModel.messages.value.first { it.sender == Sender.USER }.id @@ -239,7 +239,7 @@ class ChatViewModelPromptEditTest { sendAndAwait(viewModel, "now run the tests") viewModel.editPrompt(first, "build the release app") awaitCondition { - viewModel.history.value.size == 2 && viewModel.agentState.value == AgentState.Idle + viewModel.history.value.size == 2 && viewModel.runFinished() } viewModel.persistState() awaitCondition { "now run the tests" in stored.getValue(SESSIONS_KEY) } @@ -259,7 +259,7 @@ class ChatViewModelPromptEditTest { val first = sendAndAwait(viewModel, "build the app") sendAndAwait(viewModel, "now run the tests") viewModel.editPrompt(first, "build the release app") - awaitCondition { viewModel.agentState.value == AgentState.Idle && viewModel.history.value.size == 2 } + awaitCondition { viewModel.runFinished() && viewModel.history.value.size == 2 } viewModel.clearMessages() @@ -295,7 +295,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.agentState.value == AgentState.Idle } + awaitCondition { viewModel.runFinished() } } @Test @@ -306,11 +306,11 @@ class ChatViewModelPromptEditTest { val first = sendAndAwait(viewModel, "build the app") sendAndAwait(viewModel, "now run the tests") viewModel.editPrompt(first, "build the release app") - awaitCondition { viewModel.agentState.value == AgentState.Idle && viewModel.history.value.size == 2 } + awaitCondition { viewModel.runFinished() && 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.agentState.value == AgentState.Idle && viewModel.history.value.size == 2 } + awaitCondition { viewModel.runFinished() && viewModel.history.value.size == 2 } val replacement = viewModel.messages.value.single { it.sender == Sender.USER } assertEquals("build the debug app", replacement.text) @@ -329,7 +329,7 @@ class ChatViewModelPromptEditTest { val first = sendAndAwait(viewModel, "build the app") sendAndAwait(viewModel, "now run the tests") viewModel.editPrompt(first, "build the release app") - awaitCondition { viewModel.agentState.value == AgentState.Idle && viewModel.history.value.size == 2 } + awaitCondition { viewModel.runFinished() && viewModel.history.value.size == 2 } val edited = viewModel.messages.value.single { it.sender == Sender.USER }.id assertFalse(viewModel.switchPromptVersion(edited, 1)) @@ -381,7 +381,7 @@ class ChatViewModelPromptEditTest { assertTrue(viewModel.sendMessage(text)) val id = awaitUserMessage(viewModel, text) awaitCondition { - viewModel.history.value.size == before + 2 && viewModel.agentState.value == AgentState.Idle + viewModel.history.value.size == before + 2 && viewModel.runFinished() } return id } @@ -431,6 +431,9 @@ class ChatViewModelPromptEditTest { } } + private fun ChatViewModel.runFinished(): Boolean = + agentState.value == AgentState.Idle && canChangePrompts.value + private fun seedTwoExchanges() { stored[SESSIONS_KEY] = """[{"id":"s1","createdAt":1000,"projectKey":"$TEST_PROJECT_KEY","messages":[""" + From 022ccc2d7c3eebb4a6cd58eacc1bf8a38cc1cb16 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 22:51:24 -0800 Subject: [PATCH 3/5] ADFA-7249 AI-Core: wait for the title request in ChatViewModelTitleQueueTest The title request runs on Dispatchers.IO. Two tests verified the generateCompletion call without waiting for it; they now verify with a timeout. With a 300 ms delay at the start of the request (proof only), the old checks fail and the new ones pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aicore/viewmodel/ChatViewModelTitleQueueTest.kt | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) 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 053a81faf..1e6bc93b1 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" }, From 846db447716b1a4e62cb6a9f668c651d71442c7c Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 23 Nov 2026 18:40:03 -0800 Subject: [PATCH 4/5] ADFA-7249 AI-Core: wait for the whole run with awaitRun() in the chat tests Failure: awaitRunUnwound (ChatViewModelCompactionTest) and runFinished (ChatViewModelPromptEditTest) waited on canChangePrompts. A run's finally clears isGenerating first and only then runs finishActivity() and persistState(), so canChangePrompts turns true while the old run is still closing its activity line and saving. launchRun resets activityMessageId and runToolNames, so the next send or edit could race the old run's finishActivity(). The KDoc also wrongly said the flag is cleared last. The two helpers also disagreed on "done" (Error accepted vs Idle only). Fix: add internal suspend fun awaitRun() { generationJob?.join() } next to awaitTitleRequest(), and use it as the one definition of "run done" in both classes. generationJob is now @Volatile, since tests read it from another thread. The production order in finally is not changed (ticket ADFA-7283). What awaitRun does for each place that touches generationJob (read in ChatViewModel.kt): launchRun assigns the job synchronously, so after sendMessage/editPrompt/retryLastRun returns true the job exists and awaitRun joins the whole run including its finally; cancelGenerationJob (Stop, new chat, clear) sets it to null, so awaitRun returns at once and does not wait for that cancelled run's finally; with no run yet it returns at once; after a run ends the finished job stays set and join returns at once. The tests call it after sendMessage/editPrompt returned, so the job exists; no extra wait for a delayed launch is needed (launchRun is synchronous in both). The helpers wrap it in withTimeout(WAIT_MS) so a stuck run fails instead of hanging. PromptEdit's helper keeps the Idle check as a separate assertion after the join; Compaction does not check Idle (a failed run ends in Error). New test givenARunHeldAfterCanChangePromptsTurnsTrue_...: an Unconfined collector on canChangePrompts blocks the run's thread in the finally, right after isGenerating is cleared. While blocked, canChangePrompts is true and awaitRun() must not return (bounded 300 ms wait for a TimeoutException); after release it returns and the state is Idle and saved. Revert proof: with awaitRun's body replaced by canChangePrompts.first { it }, that test fails with "expected java.util.concurrent.TimeoutException to be thrown, but nothing was thrown" (ChatViewModelPromptEditTest.kt:411); with the join restored it passes. Checked: no other test class reads canChangePrompts (grep over src/test), so ChatViewModelTitleQueueTest and the rest needed no change. The persisted write itself runs on persistScope after persistState() returns, so awaitRun covers persistState() being called, not the write landing; the new test therefore waits separately for the stored text. Version: AI-Core 3.7.0 -> 3.7.1, versionCode 11 -> 12 (PATCH, once per PR, CLAUDE.md Versioning). No other file names 3.7.0 (grep). Tests: the three test classes pass; full AI-Core testDebugUnitTest passes. Review threads 4674442265 and 4674442275 (Hal) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Core/build.gradle.kts | 4 +- .../plugins/aicore/viewmodel/ChatViewModel.kt | 10 ++ .../viewmodel/ChatViewModelCompactionTest.kt | 13 +-- .../viewmodel/ChatViewModelPromptEditTest.kt | 98 ++++++++++++++----- 4 files changed, 93 insertions(+), 32 deletions(-) diff --git a/plugins/AI-Core/build.gradle.kts b/plugins/AI-Core/build.gradle.kts index 6febd3069..7d22df249 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 e13ced1dc..e32c72743 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 b45cb8364..1adb077b1 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 @@ -352,14 +353,14 @@ class ChatViewModelCompactionTest { } /** - * Waits until the run has unwound. A failed run sets [AgentState.Error] first, then adds its - * error message, and clears its in-flight flag last, in a `finally`; only then does - * [ChatViewModel.canChangePrompts] turn true ([AgentState.Error] doesn't count as running). - * 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. + * 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) { - awaitCondition { viewModel.canChangePrompts.value } + 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 549f91683..e583e46d2 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,6 +16,9 @@ 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 java.util.concurrent.TimeoutException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -26,9 +29,11 @@ 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 +import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test @@ -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,52 @@ 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) + + val waiting = CompletableFuture.runAsync { runBlocking { viewModel.awaitRun() } } + + // Still inside the finally: bounded wait, expected to time out. + assertThrows(TimeoutException::class.java) { waiting.get(300, TimeUnit.MILLISECONDS) } + release.countDown() + waiting.get(WAIT_MS, TimeUnit.MILLISECONDS) + 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 +474,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] = From 9ea98a83f4f844bf2ec90de904f4d35a72f20965 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 23 Nov 2026 23:47:31 -0800 Subject: [PATCH 5/5] ADFA-7249 AI-Core: start the awaitRun() waiter undispatched in its test givenARunHeldAfterCanChangePromptsTurnsTrue_whenAwaitingTheRun_thenItWaitsForTheCleanup started the waiter with CompletableFuture.runAsync and checked that it had not finished within 300 ms. runAsync doesn't guarantee the waiter has called awaitRun() by then: if the pool starts it late, the check passes even when awaitRun() returns at once, so the test could pass with a broken hook. The waiter now starts with CoroutineStart.UNDISPATCHED, which runs awaitRun() on the test thread up to its first suspension. The test checks Deferred.isCompleted straight after, with no timing window, then releases the run and awaits the waiter under withTimeout(WAIT_MS). Revert proof: with awaitRun()'s body replaced by a wait on canChangePrompts.value (what the old helpers waited for), the test fails with "awaitRun() returned while the run was still in its finally". With the join restored, it passes; ChatViewModelPromptEditTest, ChatViewModelCompactionTest and ChatViewModelTitleQueueTest pass (48 tests), and the new test passed 5 runs in a row. Review thread 4675018013 (CodeRabbit; Hal asked for it before merge) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../viewmodel/ChatViewModelPromptEditTest.kt | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) 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 e583e46d2..d44e28687 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 @@ -18,11 +18,12 @@ import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit -import java.util.concurrent.TimeoutException 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 @@ -33,7 +34,6 @@ import kotlinx.coroutines.withTimeout import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse -import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test @@ -405,12 +405,15 @@ class ChatViewModelPromptEditTest { assertTrue("run never reached its finally", entered.await(WAIT_MS, TimeUnit.MILLISECONDS)) assertTrue(viewModel.canChangePrompts.value) - val waiting = CompletableFuture.runAsync { runBlocking { viewModel.awaitRun() } } - - // Still inside the finally: bounded wait, expected to time out. - assertThrows(TimeoutException::class.java) { waiting.get(300, TimeUnit.MILLISECONDS) } + // 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() - waiting.get(WAIT_MS, TimeUnit.MILLISECONDS) + runBlocking { withTimeout(WAIT_MS) { waiting.await() } } assertEquals(AgentState.Idle, viewModel.agentState.value) awaitCondition { "build the app" in stored.getValue(SESSIONS_KEY) } } finally {