test(connect): phase 5 — restart lands on the selected profile, no login (#827)

* test(connect): pin restart-with-scoped-profile token resolution (phase 5)

* fix(profiles): scope switch via un-clamped active-profile state

The switch persisted the server profile through serverStore.selectedProfileId,
whose selfHealed() clamps ids absent from the local connection list — server
profiles like "meow" never exist there, so the scope silently reset to
default and the re-dialed socket created the fresh session in the wrong
profile (live logcat 2026-08-06: session.create carried profile=default
right after switching to meow).

- AuthManager: prefs-backed activeProfileId state, immune to the clamp,
  restored on startup; resetAuthStateForTest clears it
- ProfileScopeInterceptor + WsProfileParams + ChatViewModel fetchContextUsage:
  read the active profile instead of the connection selection
- ProfileSwitchCoordinator: write activeProfileId; dial the socket on
  Dispatchers.IO (the ticket mint did blocking I/O on the main thread —
  NetworkOnMainThreadException — and fell back to a 1s reconnect)
- ProfilesViewModel: inject the IO dispatcher; ProfilesViewModelTest drops
  its static Dispatchers mock (JVM-wide bleed class)
- Tests: WsProfileParams/Interceptor tests use the real prefs-backed state
  instead of mockkObject(AuthManager) (re-mock breaks in suite order after
  real AuthManager init); AuthManagerTest + Issue647ProfileUrlTest cancel
  the init() DataStore scope in tearDown (UncaughtExceptionsBeforeTest
  phantoms); regression test pins the clamp on the old path vs the new state

* fix(profiles): resolve getter/property JVM collision; de-poison slash test

- AuthManager.activeProfileId (StateFlow) and a getActiveProfileId()
  function generated the same JVM getter name — calls silently resolved to
  the property getter at runtime (ReadonlyStateFlow -> String
  ClassCastException, CI unit red 2026-08-06). Function removed; callers
  read activeProfileId.value.
- ChatViewModel: inject ioDispatcher (38 sites) so SlashCommandDispatchRpcTest
  can drop its mockkStatic(Dispatchers) bleed without racing real IO.
- SlashCommandDispatchRpcTest: drop the static Dispatchers mock (JVM-wide
  bleed; CI cross-wired COMMAND_DISPATCH captures in suite order), construct
  the VM with the test dispatcher.

---------

Co-authored-by: M57 <hy4ri@users.noreply.github.com>
This commit is contained in:
M57andM57 authored and GitHub committed 2026-08-06 15:07:35 +03:00
1 parent dd8dabecb0
commit d9f437939a
14 files changed
+225 -73

No files matched your search

@@ -101,6 +101,11 @@ class AuthManagerTest {
@After
fun tearDown() {
// Cancel the init() appScope (DataStore collector) so it does not leak
// into later classes — leaked collectors re-touch deleted/recreated
// server_store.json and surface as UncaughtExceptionsBeforeTest
// phantoms in whichever test class runs next.
AuthManager.resetAuthStateForTest()
val tempDir = java.io.File(System.getProperty("java.io.tmpdir") ?: "/tmp")
val tempFile = java.io.File(tempDir, "server_store.json")
if (tempFile.exists()) {
@@ -465,4 +470,70 @@ class AuthManagerTest {
verify { mockEditor.remove("auth_token") }
verify { mockEditor.putBoolean("legacy_default_migrated", true) }
}
// ── Active Hermes profile (server-side scope) ─────────────────────────
/**
* THE live profile-switch regression (2026-08-06 logcat): the coordinator
* persisted the server profile via setSelectedProfileId, but
* ServerStore.selfHealed() clamps ids that have no local
* ConnectionProfile — "meow" never exists locally, so the scope silently
* fell back to default and the re-dialed socket created the fresh session
* in the WRONG profile. The active profile state is deliberately NOT
* routed through the server store, so no clamp can touch it.
*/
@Test
fun testActiveProfileId_notClampedByLocalConnectionProfiles() {
// The OLD path (server store) clamps ids with no local ConnectionProfile:
// this is the bug the live logcat exposed. Prove the clamp still bites
// there, and that the NEW active-profile state carries the same id.
AuthManager.setSelectedProfileId("meow")
assertNull(AuthManager.getSelectedProfileId())
AuthManager.setActiveProfileId("meow")
assertEquals("meow", AuthManager.activeProfileId.value)
// Connection-level selection is untouched by the scope change — the
// clamp already nulled it, and setActiveProfileId does not revive it.
assertNull(AuthManager.getSelectedProfileId())
}
@Test
fun testActiveProfileId_persistedToPrefs() {
AuthManager.setActiveProfileId("meow")
verify { mockEditor.putString("active_profile_id", "meow") }
}
@Test
fun testActiveProfileId_restoredFromPrefsAfterRestart() {
every { mockPrefs.getString("active_profile_id", null) } returns "meow"
AuthManager.resetAuthStateForTest()
AuthManager.init(testContext)
kotlinx.coroutines.runBlocking {
val field = AuthManager::class.java.getDeclaredField("prefsDeferred")
field.isAccessible = true
(field.get(AuthManager) as? kotlinx.coroutines.Deferred<*>)?.await()
}
assertEquals("meow", AuthManager.activeProfileId.value)
// Cancel the second init's appScope so its DataStore collector does
// not leak into later test classes (leaked scopes re-touch mocked
// prefs/DataStore state and break subsequent mockkObject(AuthManager)
// classes — the "Missing mocked calls" / UncaughtExceptionsBeforeTest
// suite-order failures).
AuthManager.resetAuthStateForTest()
}
@Test
fun testActiveProfileId_blankAndNullClear() {
AuthManager.setActiveProfileId("meow")
AuthManager.setActiveProfileId("")
assertNull(AuthManager.activeProfileId.value)
AuthManager.setActiveProfileId("meow")
AuthManager.setActiveProfileId(null)
assertNull(AuthManager.activeProfileId.value)
}
}
@@ -102,6 +102,11 @@ class Issue647ProfileUrlTest {
@After
fun tearDown() {
// Cancel the init() appScope (DataStore collector) so it does not leak
// into later classes — leaked collectors re-touch deleted/recreated
// server_store.json and surface as UncaughtExceptionsBeforeTest
// phantoms in whichever test class runs next.
AuthManager.resetAuthStateForTest()
val tempDir = java.io.File(System.getProperty("java.io.tmpdir") ?: "/tmp")
val tempFile = java.io.File(tempDir, "server_store.json")
if (tempFile.exists()) tempFile.delete()
@@ -1,9 +1,6 @@
package com.m57.hermescontrol.data.remote
import com.m57.hermescontrol.data.local.AuthManager
import io.mockk.every
import io.mockk.mockkObject
import io.mockk.unmockkAll
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
@@ -20,7 +17,12 @@ class ProfileScopeInterceptorTest {
@Before
fun setUp() {
mockkObject(AuthManager)
// NOTE: deliberately NO mockkObject(AuthManager) — mocking the object
// from a class that runs after real AuthManager init (AuthManagerTest
// re-inits + leaks scopes) fails with "Missing mocked calls inside
// every{}" in suite order. The real prefs-backed setActiveProfileId is
// runCatching-safe pre-init, so tests use the REAL state instead.
AuthManager.resetAuthStateForTest()
server = MockWebServer()
server.start()
}
@@ -28,12 +30,12 @@ class ProfileScopeInterceptorTest {
@After
fun tearDown() {
server.shutdown()
unmockkAll()
AuthManager.resetAuthStateForTest()
}
/** Builds a real client with the interceptor + a stubbed AuthManager profile. */
/** Builds a real client with the interceptor + a real active profile state. */
private fun clientFor(profile: String?): OkHttpClient {
every { AuthManager.getSelectedProfileId() } returns profile
AuthManager.setActiveProfileId(profile)
return OkHttpClient
.Builder()
.addInterceptor(ProfileScopeInterceptor)
@@ -64,7 +66,7 @@ class ProfileScopeInterceptorTest {
@Test
fun explicitProfileParam_wins() {
every { AuthManager.getSelectedProfileId() } returns "work"
AuthManager.setActiveProfileId("work")
val client = OkHttpClient.Builder().addInterceptor(ProfileScopeInterceptor).build()
server.enqueue(MockResponse().setResponseCode(200).setBody("{}"))
val req =
@@ -80,7 +82,7 @@ class ProfileScopeInterceptorTest {
@Test
fun nonScopedEndpoint_untouched() {
// Pairing is machine-global (not profile-scoped on the backend).
every { AuthManager.getSelectedProfileId() } returns "work"
AuthManager.setActiveProfileId("work")
val client = OkHttpClient.Builder().addInterceptor(ProfileScopeInterceptor).build()
server.enqueue(MockResponse().setResponseCode(200).setBody("{}"))
val req = Request.Builder().url(server.url("api/pairing")).build()
@@ -120,7 +122,7 @@ class ProfileScopeInterceptorTest {
fun lookalikePath_notScoped() {
// Sourcery review (PR #540): `startsWith` must not match non-segment
// suffixes like /api/statusXYZ or /api/gatewayExtra.
every { AuthManager.getSelectedProfileId() } returns "work"
AuthManager.setActiveProfileId("work")
val client = OkHttpClient.Builder().addInterceptor(ProfileScopeInterceptor).build()
server.enqueue(MockResponse().setResponseCode(200).setBody("{}"))
val req = Request.Builder().url(server.url("api/statusXYZ")).build()
@@ -134,7 +136,7 @@ class ProfileScopeInterceptorTest {
fun scopedSubPath_isScoped() {
// A scoped prefix with a trailing segment (/api/status/health) MUST
// still receive the profile param.
every { AuthManager.getSelectedProfileId() } returns "work"
AuthManager.setActiveProfileId("work")
val client = OkHttpClient.Builder().addInterceptor(ProfileScopeInterceptor).build()
server.enqueue(MockResponse().setResponseCode(200).setBody("{}"))
val req = Request.Builder().url(server.url("api/status/health")).build()
@@ -51,7 +51,7 @@ class ProfileSwitchCoordinatorTest {
every { ApiClient.hermesApi } returns mockApi
mockkObject(AuthManager)
every { AuthManager.setSelectedProfileId(any()) } returns Unit
every { AuthManager.setActiveProfileId(any()) } returns Unit
mockkObject(HermesWsClient)
every { HermesWsClient.disconnect() } returns Unit
@@ -73,7 +73,7 @@ class ProfileSwitchCoordinatorTest {
assertTrue(result is NetworkResult.Success)
coVerify { mockApi.setActiveProfile(SetActiveProfileRequest("meow")) }
verify(ordering = Ordering.SEQUENCE) {
AuthManager.setSelectedProfileId("meow")
AuthManager.setActiveProfileId("meow")
HermesWsClient.disconnect()
HermesWsClient.connect()
}
@@ -108,6 +108,7 @@ class ProfileSwitchCoordinatorTest {
assertTrue(result is NetworkResult.Failure)
verify(exactly = 0) { AuthManager.setSelectedProfileId(any()) }
verify(exactly = 0) { AuthManager.setActiveProfileId(any()) }
verify(exactly = 0) { HermesWsClient.disconnect() }
verify(exactly = 0) { HermesWsClient.connect() }
}
@@ -1,9 +1,6 @@
package com.m57.hermescontrol.data.ws
import com.m57.hermescontrol.data.local.AuthManager
import io.mockk.every
import io.mockk.mockkObject
import io.mockk.unmockkAll
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
@@ -25,19 +22,22 @@ import org.junit.Test
class WsProfileParamsTest {
@Before
fun setUp() {
mockkObject(AuthManager)
// NOTE: deliberately NO mockkObject(AuthManager) — see
// ProfileScopeInterceptorTest for why; the real prefs-backed state is
// used instead (setActiveProfileId is runCatching-safe pre-init).
AuthManager.resetAuthStateForTest()
}
@After
fun tearDown() {
unmockkAll()
AuthManager.resetAuthStateForTest()
}
// ── Rule 1: scoped method gets profile injected ─────────────────────
@Test
fun `scoped method injects profile when active profile is set`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
AuthManager.setActiveProfileId("meow")
val original = mapOf("session_id" to "abc123")
val result = WsProfileParams.decorate(WsMethods.SESSION_LIST, original)
@@ -48,7 +48,7 @@ class WsProfileParamsTest {
@Test
fun `session_create gets profile injected`() {
every { AuthManager.getSelectedProfileId() } returns "work"
AuthManager.setActiveProfileId("work")
val original = mapOf("cols" to 80)
val result = WsProfileParams.decorate(WsMethods.SESSION_CREATE, original)
@@ -59,7 +59,7 @@ class WsProfileParamsTest {
@Test
fun `session_resume gets profile injected`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
AuthManager.setActiveProfileId("meow")
val original = mapOf("session_id" to "s1")
val result = WsProfileParams.decorate(WsMethods.SESSION_RESUME, original)
@@ -70,7 +70,7 @@ class WsProfileParamsTest {
@Test
fun `session_delete gets profile injected`() {
every { AuthManager.getSelectedProfileId() } returns "work"
AuthManager.setActiveProfileId("work")
val original = mapOf("session_id" to "s2")
val result = WsProfileParams.decorate(WsMethods.SESSION_DELETE, original)
@@ -80,7 +80,7 @@ class WsProfileParamsTest {
@Test
fun `session_status gets profile injected`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
AuthManager.setActiveProfileId("meow")
val original = mapOf("session_id" to "s3")
val result = WsProfileParams.decorate(WsMethods.SESSION_STATUS, original)
@@ -90,7 +90,7 @@ class WsProfileParamsTest {
@Test
fun `profile_scoped decorator method gets profile injected`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
AuthManager.setActiveProfileId("meow")
val original = emptyMap<String, Any>()
val result = WsProfileParams.decorate("verification.status", original)
@@ -100,7 +100,7 @@ class WsProfileParamsTest {
@Test
fun `empty params map gets profile injected for scoped method`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
AuthManager.setActiveProfileId("meow")
val result = WsProfileParams.decorate(WsMethods.SESSION_LIST, emptyMap())
@@ -112,7 +112,7 @@ class WsProfileParamsTest {
@Test
fun `non-scoped method returns same params reference`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
AuthManager.setActiveProfileId("meow")
val original = mapOf("session_id" to "s1", "text" to "hello")
val result = WsProfileParams.decorate(WsMethods.PROMPT_SUBMIT, original)
@@ -123,7 +123,7 @@ class WsProfileParamsTest {
@Test
fun `subscription method is not profile scoped`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
AuthManager.setActiveProfileId("meow")
val original = mapOf("plan" to "pro")
val result = WsProfileParams.decorate(WsMethods.SUBSCRIPTION_STATE, original)
@@ -133,7 +133,7 @@ class WsProfileParamsTest {
@Test
fun `clarify_respond is not profile scoped`() {
every { AuthManager.getSelectedProfileId() } returns "work"
AuthManager.setActiveProfileId("work")
val original = mapOf("answer" to "yes")
val result = WsProfileParams.decorate(WsMethods.CLARIFY_RESPOND, original)
@@ -143,7 +143,7 @@ class WsProfileParamsTest {
@Test
fun `image_attach_bytes is not profile scoped`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
AuthManager.setActiveProfileId("meow")
val original = mapOf("data" to "base64data")
val result = WsProfileParams.decorate(WsMethods.IMAGE_ATTACH_BYTES, original)
@@ -153,7 +153,7 @@ class WsProfileParamsTest {
@Test
fun `commands_catalog is not profile scoped`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
AuthManager.setActiveProfileId("meow")
val original = emptyMap<String, Any>()
val result = WsProfileParams.decorate(WsMethods.COMMANDS_CATALOG, original)
@@ -163,7 +163,7 @@ class WsProfileParamsTest {
@Test
fun `unknown method is not profile scoped`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
AuthManager.setActiveProfileId("meow")
val original = mapOf("foo" to "bar")
val result = WsProfileParams.decorate("setup.wizard", original)
@@ -175,7 +175,7 @@ class WsProfileParamsTest {
@Test
fun `explicit profile in params is never overwritten`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
AuthManager.setActiveProfileId("meow")
val original = mapOf("session_id" to "s1", "profile" to "custom")
val result = WsProfileParams.decorate(WsMethods.SESSION_LIST, original)
@@ -186,7 +186,7 @@ class WsProfileParamsTest {
@Test
fun `explicit empty-string profile is preserved`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
AuthManager.setActiveProfileId("meow")
// Caller explicitly passes profile="" — the containsKey check
// preserves this so the server sees the explicit value.
@@ -201,7 +201,7 @@ class WsProfileParamsTest {
@Test
fun `null selected profile returns same params reference for scoped method`() {
every { AuthManager.getSelectedProfileId() } returns null
AuthManager.setActiveProfileId(null)
val original = mapOf("session_id" to "s1")
val result = WsProfileParams.decorate(WsMethods.SESSION_LIST, original)
@@ -212,7 +212,7 @@ class WsProfileParamsTest {
@Test
fun `null selected profile returns same params for non-scoped method`() {
every { AuthManager.getSelectedProfileId() } returns null
AuthManager.setActiveProfileId(null)
val original = mapOf("text" to "hello")
val result = WsProfileParams.decorate(WsMethods.PROMPT_SUBMIT, original)
@@ -224,7 +224,7 @@ class WsProfileParamsTest {
@Test
fun `all PROFILE_SCOPED_METHODS entries get profile injected`() {
every { AuthManager.getSelectedProfileId() } returns "testprofile"
AuthManager.setActiveProfileId("testprofile")
for (method in WsMethods.PROFILE_SCOPED_METHODS) {
val result = WsProfileParams.decorate(method, emptyMap())
@@ -294,7 +294,7 @@ class WsProfileParamsTest {
@Test
fun `prompt_submit is not in scoped set confirming sendMessage path is correct`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
AuthManager.setActiveProfileId("meow")
val params = mapOf("session_id" to "s1", "text" to "hello world")
val result = WsProfileParams.decorate(WsMethods.PROMPT_SUBMIT, params)
@@ -64,10 +64,11 @@ class SlashCommandDispatchRpcTest {
every { android.util.Log.e(any(), any(), any()) } returns 0
// NOTE: no mockkStatic(Dispatchers) here — a static Dispatchers mock
// bleeds JVM-wide and breaks later classes (CI 2026-08-06: this
// class's own static IO mock cross-wired COMMAND_DISPATCH captures in
// suite order). setMain alone is safe — the slash-dispatch send path
// is synchronous (no IO hop).
// bleeds JVM-wide and breaks later classes (the same poison removed
// from ProfileSwitchCoordinatorTest / ProfilesViewModelTest; CI
// 2026-08-06: this class's own static IO mock cross-wired
// COMMAND_DISPATCH captures in suite order). setMain alone is safe —
// the slash-dispatch send path is synchronous (no IO hop).
mockkObject(AuthManager)
mockkObject(HermesWsClient)
mockkObject(ApiClient)
@@ -414,6 +414,32 @@ class ConnectViewModelTest {
assertEquals("https://127.0.0.1:9119/", state.baseUrl)
}
@Test
fun testLoadSavedValues_restartWithScopedProfile_resolvesTokenViaFallback() {
val meow =
ConnectionProfile(
id = "meow",
name = "meow",
baseUrl = "https://127.0.0.1:9119/",
)
// Restart seam (phase 1): the app was killed while meow was selected;
// only the default profile holds the connection token. The per-server
// token fallback resolves it, so the restart lands on meow WITHOUT a
// login screen — desktop-equivalent "kill + reopen → still meow".
every { AuthManager.getToken() } returns "conn-token"
every { AuthManager.getBaseUrl() } returns "https://127.0.0.1:9119/"
every { AuthManager.getConnectionProfiles() } returns listOf(meow)
every { AuthManager.getSelectedProfileId() } returns "meow"
val viewModel = ConnectViewModel(mockApp)
val state = viewModel.uiState.value
assertEquals("conn-token", state.token)
assertEquals("meow", state.profileName)
assertEquals(meow, state.selectedProfile)
assertEquals("https://127.0.0.1:9119/", state.baseUrl)
}
@Test
fun testSelectProfile_withoutToken_usesEmptyString() {
every { AuthManager.getProfileToken(any()) } returns null
@@ -22,7 +22,6 @@ import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.mockkStatic
import io.mockk.unmockkAll
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -65,12 +64,11 @@ class ProfilesViewModelTest {
@Before
fun setUp() {
// NOTE: no mockkStatic(Dispatchers) here — a static Dispatchers mock
// bleeds into later test classes in the same JVM (see the same comment
// in ProfileSwitchCoordinatorTest). setMain alone is safe: it only
// affects Dispatchers.Main and is undone by resetMain in tearDown.
Dispatchers.setMain(testDispatcher)
val testMainDispatcher = Dispatchers.Main
mockkStatic(Dispatchers::class)
every { Dispatchers.IO } returns testDispatcher
every { Dispatchers.Main } returns testMainDispatcher
mockkObject(AuthManager)
storedPinnedModels = mutableListOf()
@@ -113,7 +111,7 @@ class ProfilesViewModelTest {
}
private fun createViewModel(): ProfilesViewModel {
val vm = ProfilesViewModel()
val vm = ProfilesViewModel(ioDispatcher = testDispatcher)
testDispatcher.scheduler.advanceUntilIdle()
return vm
}