From 0db0a04fb89796e1faca93003ba5d27edb3467e7 Mon Sep 17 00:00:00 2001 From: Yu-ga <74749461+yuga-hashimoto@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:07:27 +0000 Subject: [PATCH 1/3] fix(runtime): keep the agent list and catalogue usable during a restart A local OpenCode installs its plugins on the first GET /agent after every start, which can take over a minute. The agent read was awaited inside the catalogue load while holding its refresh lock, so sessions, providers and workspaces waited on it and the mode chip showed a spinner. - Move the load-time agent read outside the refresh lock, publishing agents as soon as they answer without holding up the next load. - Cache the last good agent list and show it while the fresh read runs. - Keep an agent list through a failed connect instead of clearing it. --- .../andcode/AndCodeApplication.kt | 20 +- .../data/repository/AgentCatalogCache.kt | 43 +++++ .../repository/RuntimeCatalogRepository.kt | 180 ++++++++++++------ .../data/repository/AgentCatalogCacheTest.kt | 50 +++++ .../RuntimeCatalogRepositoryTest.kt | 79 ++++++++ 5 files changed, 301 insertions(+), 71 deletions(-) create mode 100644 app/src/main/java/com/yugahashimoto/andcode/data/repository/AgentCatalogCache.kt create mode 100644 app/src/test/java/com/yugahashimoto/andcode/data/repository/AgentCatalogCacheTest.kt diff --git a/app/src/main/java/com/yugahashimoto/andcode/AndCodeApplication.kt b/app/src/main/java/com/yugahashimoto/andcode/AndCodeApplication.kt index 144e21ac1..11e59ecd7 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/AndCodeApplication.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/AndCodeApplication.kt @@ -21,6 +21,7 @@ import com.yugahashimoto.andcode.core.storage.DeviceStorage import com.yugahashimoto.andcode.core.storage.DeviceStorageAccess import com.yugahashimoto.andcode.core.util.debounceFalseEdge import com.yugahashimoto.andcode.data.connection.SecureSettingsRepository +import com.yugahashimoto.andcode.data.repository.AgentCatalogCache import com.yugahashimoto.andcode.data.repository.AndroidRuntimeActivityMessages import com.yugahashimoto.andcode.data.repository.AndroidRuntimeCatalogMessages import com.yugahashimoto.andcode.data.repository.ProviderCatalogCache @@ -532,20 +533,19 @@ class AndCodeApplication : Application() { runtimeWork = runtimeWork, messages = claudeMessages, ) + val catalogCacheJson = + Json { + ignoreUnknownKeys = true + isLenient = true + encodeDefaults = true + } + val catalogCacheDir = File(filesDir, "catalog-cache") catalogRepository = RuntimeCatalogRepository( registry = runtimeRegistry, scope = applicationScope, - providerCache = - ProviderCatalogCache( - directory = File(filesDir, "catalog-cache"), - json = - Json { - ignoreUnknownKeys = true - isLenient = true - encodeDefaults = true - }, - ), + providerCache = ProviderCatalogCache(catalogCacheDir, catalogCacheJson), + agentCache = AgentCatalogCache(catalogCacheDir, catalogCacheJson), messages = AndroidRuntimeCatalogMessages(this), ) // Learns each recent chat's pull requests from its transcript, so the drawer can badge a diff --git a/app/src/main/java/com/yugahashimoto/andcode/data/repository/AgentCatalogCache.kt b/app/src/main/java/com/yugahashimoto/andcode/data/repository/AgentCatalogCache.kt new file mode 100644 index 000000000..b4a758ad3 --- /dev/null +++ b/app/src/main/java/com/yugahashimoto/andcode/data/repository/AgentCatalogCache.kt @@ -0,0 +1,43 @@ +package com.yugahashimoto.andcode.data.repository + +import com.yugahashimoto.andcode.core.api.OpenCodeAgent +import com.yugahashimoto.andcode.core.api.selectablePrimaryAgents +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json +import java.io.File + +/** + * Disk cache for a runtime's agent list. + * + * A local OpenCode installs its plugins on the first `GET /agent` after every start, which can take + * over a minute on a phone. Without this the mode chip shows its spinner for that whole window even + * though the list rarely changes between restarts, and the user cannot tell which agent a new chat + * would use. The last list is shown straight away and replaced as soon as the fresh read lands. + * + * Keyed on the runtime only, not on its version: unlike the provider catalogue, an agent list stays + * meaningful across an OpenCode upgrade until the new server says otherwise, and every load refreshes + * it in the background anyway. An empty list is never stored, because that is the shape a server + * gives while it is still starting. + */ +class AgentCatalogCache( + private val directory: File, + private val json: Json, +) { + fun read(runtimeId: String): List? = + runCatching { json.decodeFromString>(file(runtimeId).readText()) } + .getOrNull() + ?.takeIf { it.selectablePrimaryAgents().isNotEmpty() } + + fun write( + runtimeId: String, + agents: List, + ) { + if (agents.selectablePrimaryAgents().isEmpty()) return + runCatching { + directory.mkdirs() + file(runtimeId).writeText(json.encodeToString(agents)) + } + } + + private fun file(runtimeId: String) = File(directory, "agents-${runtimeId.replace(Regex("[^A-Za-z0-9._-]"), "_")}.json") +} diff --git a/app/src/main/java/com/yugahashimoto/andcode/data/repository/RuntimeCatalogRepository.kt b/app/src/main/java/com/yugahashimoto/andcode/data/repository/RuntimeCatalogRepository.kt index 72320f312..3122b1562 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/data/repository/RuntimeCatalogRepository.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/data/repository/RuntimeCatalogRepository.kt @@ -55,6 +55,7 @@ class RuntimeCatalogRepository( private val registry: RuntimeRegistry, private val scope: CoroutineScope, private val providerCache: ProviderCatalogCache? = null, + private val agentCache: AgentCatalogCache? = null, private val messages: RuntimeCatalogMessages = RuntimeCatalogMessages, ) { private val mutableState = MutableStateFlow(RuntimeCatalogState(runtime = registry.selected.value)) @@ -71,6 +72,14 @@ class RuntimeCatalogRepository( val state: StateFlow = mutableState.asStateFlow() private val refreshMutex = Mutex() + /** + * The one load-time agent read in flight and the runtime it is for, so overlapping loads do not + * each start a plugin install. Separate from [refreshMutex] on purpose: a slow `GET /agent` must + * not hold up the rest of the catalogue or the next load. + */ + private var agentRead: Pair? = null + private val agentReadLock = Any() + /** * The one agent retry in flight and the runtime it is for, so repeated taps on an empty mode * chip do not stack polls. Guarded by [agentRetryLock]: taps (main) and load (IO) both start it. @@ -202,6 +211,20 @@ class RuntimeCatalogRepository( mutableState.update { it.copy(runtime = target, providers = cached) } } + // The agent list has the same wait, and a longer one: a restarted local OpenCode + // installs its plugins on the first `GET /agent`, which can take over a minute. Show the + // last list instead of a spinner for that whole window and let the read below replace + // it. Only fills an empty list, so a refresh never downgrades agents already on screen. + agentCache?.read(target.id)?.let { cached -> + mutableState.update { state -> + if (state.runtime?.id == target.id && !state.agents.hasSelectableAgent()) { + state.copy(agents = cached, agentsLoading = false) + } else { + state + } + } + } + // The local runtime is usually still starting when the app opens, so a single attempt // fails and nothing ever retried: the catalogue stayed empty until something else asked // for it, which is what made the model picker look slow. @@ -212,49 +235,39 @@ class RuntimeCatalogRepository( connection = target.connect() } if (connection.isFailure) { - mutableState.value = + mutableState.update { current -> + // Keep the agent list this runtime already had - cached, or from before the + // restart - so a stopped server does not empty the mode chip and force the user + // to wait for the next connect before they can pick an agent again. + val keptAgents = current.agentsFor(target) RuntimeCatalogState( runtime = target, + agents = keptAgents, isRefreshing = false, + agentsLoading = false, error = connection.exceptionOrNull().safeMessage(messages.connectionFailed), ) + } return } mutableState.update { if (it.runtime?.id == target.id) it.copy(health = connection.getOrNull()) else it } + // Started before the other reads, and on the repository scope rather than under the + // refresh lock: a local OpenCode installing its plugins can take over a minute on its + // first `GET /agent`, and sessions, providers and workspaces must publish without it. + // [readAgents] publishes the agents the moment they arrive and retries in the background. + startAgentRead(target) + val catalog = supervisorScope { val sessions = async { runCatching { target.listSessions() } } val providers = async { runCatching { target.listProviders() } } - // The picker can use agents as soon as they arrive, even if a provider or - // workspace request is still waiting on the runtime. - val agents = - async { - runCatching { target.listAgents() }.also { result -> - val list = result.getOrNull() - if (registry.selected.value?.id == target.id) { - mutableState.update { state -> - if (state.runtime?.id != target.id) { - state - } else { - val completed = state.copy(agentsInitialReadPending = false) - if (list.hasSelectableAgent()) completed.withAgents(list.orEmpty()) else completed - } - } - if (!mutableState.value.agentsFor(target).hasSelectableAgent()) { - // Retry immediately; unrelated requests may remain in flight. - refreshAgents() - } - } - } - } val workspaces = async { runCatching { target.listWorkspaces() } } LoadedCatalog( sessions = sessions.await(), providers = providers.await(), - agents = agents.await(), workspaces = workspaces.await(), ) } @@ -283,43 +296,25 @@ class RuntimeCatalogRepository( } } } - // Like the providers above: a read that failed or offered no agent to pick must not blank - // a list this runtime already showed, or a flaky `GET /agent` empties a working picker. - val loadedAgents = catalog.agents.getOrNull() - // Read and written in one update: a background agent retry can land between this load's - // fetch and its write, and taking the list from before that would put an empty one back. + // The agent list is not written here: [readAgents] owns it, so a slow or failed + // `GET /agent` can neither delay the rest of the catalogue nor blank a list on screen. + // Its last failure, if any, is folded back into the catalogue error so the existing + // "Agents: ..." line still shows while nothing selectable has arrived. mutableState.update { current -> - val agentsToUse = - if (loadedAgents.hasSelectableAgent()) { - loadedAgents.orEmpty() - } else { - current.agentsFor(target).ifEmpty { loadedAgents.orEmpty() } - } - val agentsFound = agentsToUse.hasSelectableAgent() - // A list kept on screen - from an earlier load or a retry that already succeeded - - // carries no failure of its own, so neither the chip nor the "Agents: ..." line in - // the catalogue error reports this read's failure. - val readFailure = catalog.agentsFailure(messages) - val agentsFailure = readFailure.takeUnless { agentsFound && !loadedAgents.hasSelectableAgent() } - val errors = catalog.failures(messages).filterNot { agentsFailure == null && it == readFailure } - RuntimeCatalogState( + if (current.runtime?.id != target.id) return@update current + val agentsError = current.agentsError.takeIf { !current.agentsFor(target).hasSelectableAgent() } + val errors = (catalog.failures(messages) + listOfNotNull(agentsError)).distinct() + current.copy( runtime = target, health = connection.getOrNull(), sessions = catalog.sessions.getOrDefault(emptyList()), providers = providersToUse, - agents = agentsToUse, workspaces = catalog.workspaces.getOrDefault(emptyList()), isRefreshing = false, error = errors.takeIf { it.isNotEmpty() }?.joinToString("\n"), - agentsError = agentsFailure, - // Still loading when nothing selectable came back: the retry below takes over. - agentsLoading = !agentsFound, ) } } - // Outside the lock: a local OpenCode installing its plugins can take tens of seconds per - // `GET /agent`, and the rest of the catalogue - and every other refresh - must not wait on it. - if (!mutableState.value.agentsFor(target).hasSelectableAgent()) refreshAgents() } /** @@ -340,6 +335,70 @@ class RuntimeCatalogRepository( return result } + /** + * One line, so [withAgents] can find it again in [RuntimeCatalogState.error]: decoding errors + * carry the JSON input on a second line, which a line-by-line removal would never match. + */ + private fun agentsFailure(result: Result>): String? = + result.exceptionOrNull()?.let { + messages.agents(it.safeMessage(messages.connectionFailed).replace(Regex("\\s*\\n\\s*"), " ")) + } + + /** + * Starts the one load-time agent read, replacing any read left over from another runtime. + * + * A local OpenCode installs its plugins on the first `GET /agent` after a start, which can take + * over a minute. That read runs outside the refresh lock so sessions, providers and workspaces + * publish (and the next load can start) while it is still running. + */ + private fun startAgentRead(target: RuntimeTarget) { + synchronized(agentReadLock) { + val running = agentRead + if (running != null && running.second.isActive) { + // One read per runtime at a time: a repeated warmup must not stack plugin installs. + if (running.first == target.id) return + // A read left over from the runtime the user switched away from must not make the + // new runtime wait for it. + running.second.cancel() + } + agentRead = target.id to scope.launch { readAgents(target) } + } + } + + /** + * Reads the agents once and publishes them the moment they answer. A read that offers nothing + * hands over to [refreshAgents]; a list already on screen is kept and not blamed for this + * read's failure. + */ + private suspend fun readAgents(target: RuntimeTarget) { + if (registry.selected.value?.id != target.id) return + val result = runCatching { target.listAgents() } + val list = result.getOrNull() + // Keep the last good list for the next cold start, where the same read can take a + // minute again while the plugins install. + if (list.hasSelectableAgent()) agentCache?.write(target.id, list.orEmpty()) + if (registry.selected.value?.id != target.id) return + val failure = agentsFailure(result) + mutableState.update { state -> + if (state.runtime?.id != target.id) { + state + } else { + val completed = state.copy(agentsInitialReadPending = false) + when { + list.hasSelectableAgent() -> completed.withAgents(list.orEmpty()) + state.agents.hasSelectableAgent() -> completed + else -> + completed.copy( + agentsLoading = true, + agentsError = failure, + error = appendError(completed.error, failure), + ) + } + } + } + if (!mutableState.value.agentsFor(target).hasSelectableAgent()) refreshAgents() + } + /** * Re-reads the agent list in the background until the runtime offers one to pick, for a load * whose `GET /agent` failed or for a mode chip tapped while empty. @@ -377,6 +436,7 @@ class RuntimeCatalogRepository( target.id to scope.launch { val list = loadAgents(target).getOrNull()?.takeIf { it.hasSelectableAgent() } + list?.let { agentCache?.write(target.id, it) } if (registry.selected.value?.id != target.id) return@launch mutableState.update { when { @@ -394,23 +454,12 @@ class RuntimeCatalogRepository( private data class LoadedCatalog( val sessions: Result>, val providers: Result, - val agents: Result>, val workspaces: Result>, ) { - /** - * One line, so [withAgents] can find it again in [RuntimeCatalogState.error]: decoding errors - * carry the JSON input on a second line, which a line-by-line removal would never match. - */ - fun agentsFailure(messages: RuntimeCatalogMessages): String? = - agents.exceptionOrNull()?.let { - messages.agents(it.safeMessage(messages.connectionFailed).replace(Regex("\\s*\\n\\s*"), " ")) - } - fun failures(messages: RuntimeCatalogMessages): List = listOfNotNull( sessions.exceptionOrNull()?.let { messages.sessions(it.safeMessage(messages.connectionFailed)) }, providers.exceptionOrNull()?.let { messages.providers(it.safeMessage(messages.connectionFailed)) }, - agentsFailure(messages), workspaces.exceptionOrNull()?.let { messages.workspaces(it.safeMessage(messages.connectionFailed)) }, ) } @@ -425,6 +474,15 @@ class RuntimeCatalogRepository( private fun Throwable?.safeMessage(fallback: String): String = this?.message?.takeIf { it.isNotBlank() } ?: fallback +/** [error] with [line] appended, skipping either when blank. Used to add one failure to a catalogue error. */ +private fun appendError( + error: String?, + line: String?, +): String? = + listOfNotNull(error?.takeIf { it.isNotBlank() }, line?.takeIf { it.isNotBlank() }) + .takeIf { it.isNotEmpty() } + ?.joinToString("\n") + /** * The providers on screen, but only while the state still belongs to [target]: another runtime's * catalogue must never be treated as this one's, so its models cannot show under a runtime that diff --git a/app/src/test/java/com/yugahashimoto/andcode/data/repository/AgentCatalogCacheTest.kt b/app/src/test/java/com/yugahashimoto/andcode/data/repository/AgentCatalogCacheTest.kt new file mode 100644 index 000000000..e05329fd3 --- /dev/null +++ b/app/src/test/java/com/yugahashimoto/andcode/data/repository/AgentCatalogCacheTest.kt @@ -0,0 +1,50 @@ +package com.yugahashimoto.andcode.data.repository + +import com.yugahashimoto.andcode.core.api.OpenCodeAgent +import kotlinx.serialization.json.Json +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class AgentCatalogCacheTest { + @get:Rule + val temporaryFolder = TemporaryFolder() + + private fun cache() = AgentCatalogCache(temporaryFolder.newFolder("agents"), Json { ignoreUnknownKeys = true }) + + @Test + fun `stores and reads back a selectable list`() { + val cache = cache() + val agents = + listOf( + OpenCodeAgent("build", mode = "primary"), + OpenCodeAgent("plan", mode = "primary"), + ) + + cache.write("mac", agents) + + assertEquals(agents, cache.read("mac")) + } + + @Test + fun `does not store a list with nothing selectable`() { + val cache = cache() + + cache.write( + "mac", + listOf( + OpenCodeAgent("title", mode = "subagent"), + OpenCodeAgent("memory", hidden = true), + ), + ) + + assertNull(cache.read("mac")) + } + + @Test + fun `returns null before anything is stored`() { + assertNull(cache().read("mac")) + } +} diff --git a/app/src/test/java/com/yugahashimoto/andcode/data/repository/RuntimeCatalogRepositoryTest.kt b/app/src/test/java/com/yugahashimoto/andcode/data/repository/RuntimeCatalogRepositoryTest.kt index b4848b473..1fe516985 100644 --- a/app/src/test/java/com/yugahashimoto/andcode/data/repository/RuntimeCatalogRepositoryTest.kt +++ b/app/src/test/java/com/yugahashimoto/andcode/data/repository/RuntimeCatalogRepositoryTest.kt @@ -294,6 +294,22 @@ class RuntimeCatalogRepositoryTest { private fun cache() = ProviderCatalogCache(temporaryFolder.newFolder("cache"), Json { ignoreUnknownKeys = true }) + private fun agentCache() = AgentCatalogCache(temporaryFolder.newFolder("agent-cache"), Json { ignoreUnknownKeys = true }) + + private fun repositoryWithAgentCache( + target: RuntimeTarget, + agentCache: AgentCatalogCache, + scope: TestScope, + ): RuntimeCatalogRepository { + val registry = + RuntimeRegistry( + store = FakeStore(selectedRuntimeId = "mac"), + localTarget = FakeTarget("local-android", RuntimeType.LOCAL), + remoteFactory = { target }, + ) + return RuntimeCatalogRepository(registry, scope, agentCache = agentCache) + } + private fun repositoryWithCache( target: RuntimeTarget, providerCache: ProviderCatalogCache, @@ -513,6 +529,65 @@ class RuntimeCatalogRepositoryTest { assertFalse(repository.state.value.agentsLoading) } + @Test + fun `cached agents are shown while a slow agent read is still running`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val cache = agentCache() + cache.write("mac", listOf(OpenCodeAgent("orchestrator", mode = "primary"))) + val target = FakeTarget("mac") + val gate = CompletableDeferred() + target.agentsGate = gate + val repository = repositoryWithAgentCache(target, cache, TestScope(dispatcher)) + + // A restarted local OpenCode installing its plugins: the read has not answered yet. + testScheduler.runCurrent() + + assertEquals(listOf("orchestrator"), repository.state.value.agents.map { it.name }) + assertFalse(repository.state.value.agentsLoading) + // The rest of the catalogue is done even though the agent read is still running. + assertFalse(repository.state.value.isRefreshing) + + gate.complete(Unit) + advanceUntilIdle() + + assertEquals(listOf("build"), repository.state.value.agents.map { it.name }) + assertFalse(repository.state.value.agentsLoading) + } + + @Test + fun `a successful agent read replaces the stored list`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val cache = agentCache() + cache.write("mac", listOf(OpenCodeAgent("stale", mode = "primary"))) + val target = FakeTarget("mac") + val repository = repositoryWithAgentCache(target, cache, TestScope(dispatcher)) + + advanceUntilIdle() + + assertEquals(listOf("build"), repository.state.value.agents.map { it.name }) + assertEquals(listOf("build"), cache.read("mac")?.map { it.name }) + } + + @Test + fun `a failed agent read keeps the cached list`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val cache = agentCache() + cache.write("mac", listOf(OpenCodeAgent("orchestrator", mode = "primary"))) + val target = FakeTarget("mac") + target.agentAnswers.add { error("plugin load failed") } + val repository = repositoryWithAgentCache(target, cache, TestScope(dispatcher)) + + advanceUntilIdle() + + assertEquals(listOf("orchestrator"), repository.state.value.agents.map { it.name }) + assertFalse(repository.state.value.agentsLoading) + // A failed read must not erase the list a later restart could show again. + assertEquals(listOf("orchestrator"), cache.read("mac")?.map { it.name }) + } + private class FakeStore( profiles: List = listOf(profileStatic("mac")), override var selectedRuntimeId: String? = null, @@ -623,8 +698,12 @@ class RuntimeCatalogRepositoryTest { val agentAnswers = ArrayDeque<() -> List>() var agentCalls = 0 + /** Holds [listAgents] until a test wants to simulate a slow plugin install on the server. */ + var agentsGate: CompletableDeferred? = null + override suspend fun listAgents(): List { agentCalls++ + agentsGate?.await() return agentAnswers.removeFirstOrNull()?.invoke() ?: listOf(OpenCodeAgent("build", mode = "primary")) } From 68f9cd381747626642a8c52c44b4b754c7d47835 Mon Sep 17 00:00:00 2001 From: Yu-ga <74749461+yuga-hashimoto@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:21:26 +0000 Subject: [PATCH 2/3] fix(runtime): apply pre-PR review nits Clear a stale agentsError when a new load starts, and give the Koin-built catalog the same on-disk caches as the hand-built one so the two cannot diverge. --- .../repository/RuntimeCatalogRepository.kt | 1 + .../com/yugahashimoto/andcode/di/AppModule.kt | 20 ++++++++++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/yugahashimoto/andcode/data/repository/RuntimeCatalogRepository.kt b/app/src/main/java/com/yugahashimoto/andcode/data/repository/RuntimeCatalogRepository.kt index 3122b1562..3fc960c25 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/data/repository/RuntimeCatalogRepository.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/data/repository/RuntimeCatalogRepository.kt @@ -199,6 +199,7 @@ class RuntimeCatalogRepository( runtime = target, isRefreshing = true, error = null, + agentsError = null, agentsLoading = !current.agents.hasSelectableAgent(), agentsInitialReadPending = true, ) diff --git a/app/src/main/java/com/yugahashimoto/andcode/di/AppModule.kt b/app/src/main/java/com/yugahashimoto/andcode/di/AppModule.kt index da235f412..95a2be1a7 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/di/AppModule.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/di/AppModule.kt @@ -5,8 +5,10 @@ import com.yugahashimoto.andcode.AndCodeApplication import com.yugahashimoto.andcode.core.api.GitHubApiClient import com.yugahashimoto.andcode.core.notification.RuntimeNotificationHelper import com.yugahashimoto.andcode.data.connection.SecureSettingsRepository +import com.yugahashimoto.andcode.data.repository.AgentCatalogCache import com.yugahashimoto.andcode.data.repository.AndroidRuntimeActivityMessages import com.yugahashimoto.andcode.data.repository.AndroidRuntimeCatalogMessages +import com.yugahashimoto.andcode.data.repository.ProviderCatalogCache import com.yugahashimoto.andcode.data.repository.PullRequestSessionStore import com.yugahashimoto.andcode.data.repository.PullRequestStatusRepository import com.yugahashimoto.andcode.data.repository.RuntimeActivityRepository @@ -38,6 +40,7 @@ import com.yugahashimoto.andcode.runtime.local.VerifiedRuntimeDownloader import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob +import kotlinx.serialization.json.Json import okhttp3.OkHttpClient import org.koin.android.ext.koin.androidContext import org.koin.dsl.module @@ -207,7 +210,22 @@ val appModule = } single { - RuntimeCatalogRepository(get(), get(), messages = get()) + // Keep this in step with AndCodeApplication's hand-built repository: the screens use + // that one today, but a Koin-resolved catalog must not lose the on-disk caches. + val cacheDir = File(androidContext().filesDir, "catalog-cache") + val cacheJson = + Json { + ignoreUnknownKeys = true + isLenient = true + encodeDefaults = true + } + RuntimeCatalogRepository( + registry = get(), + scope = get(), + providerCache = ProviderCatalogCache(cacheDir, cacheJson), + agentCache = AgentCatalogCache(cacheDir, cacheJson), + messages = get(), + ) } single { From 146b5a379e59937ff3ef56287acf11462afb7818 Mon Sep 17 00:00:00 2001 From: Yu-ga <74749461+yuga-hashimoto@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:27:30 +0000 Subject: [PATCH 3/3] test(runtime): cover cached agents surviving a failed connect --- .../repository/RuntimeCatalogRepositoryTest.kt | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/app/src/test/java/com/yugahashimoto/andcode/data/repository/RuntimeCatalogRepositoryTest.kt b/app/src/test/java/com/yugahashimoto/andcode/data/repository/RuntimeCatalogRepositoryTest.kt index 1fe516985..4978597b5 100644 --- a/app/src/test/java/com/yugahashimoto/andcode/data/repository/RuntimeCatalogRepositoryTest.kt +++ b/app/src/test/java/com/yugahashimoto/andcode/data/repository/RuntimeCatalogRepositoryTest.kt @@ -588,6 +588,24 @@ class RuntimeCatalogRepositoryTest { assertEquals(listOf("orchestrator"), cache.read("mac")?.map { it.name }) } + @Test + fun `a failed connect keeps the cached agents`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val cache = agentCache() + cache.write("mac", listOf(OpenCodeAgent("orchestrator", mode = "primary"))) + val target = FakeTarget("mac", connectError = IllegalStateException("offline")) + val repository = repositoryWithAgentCache(target, cache, TestScope(dispatcher)) + + advanceUntilIdle() + + // A stopped runtime must not empty the mode chip and make the user wait for a connect. + assertEquals(listOf("orchestrator"), repository.state.value.agents.map { it.name }) + assertFalse(repository.state.value.agentsLoading) + assertNull(repository.state.value.agentsError) + assertEquals("offline", repository.state.value.error) + } + private class FakeStore( profiles: List = listOf(profileStatic("mac")), override var selectedRuntimeId: String? = null,