feat(profiles): first-class profile switching — phase 0 baseline port (#820)

* feat(profiles): make profile switching actually scope the app (issue #781 follow-up)

* fix(profiles): inherit connection token when switching to same-dashboard profile (issue #781 follow-up)

* fix(chat): reset open session on profile switch + prefill login profile (desktop parity)

* fix(ws): inject profile into profile-scoped RPC params so chat follows the selected profile

* test(chat): de-poison SlashCommandDispatchRpcTest (drop static Dispatchers mock)

mockkStatic(Dispatchers::class) + a stubbed Dispatchers.IO bleeds JVM-wide and
breaks later classes in suite order (CI 2026-08-06: COMMAND_DISPATCH captures
cross-wired → ComparisonFailure on lower stack PRs). ChatViewModel gains an
injected ioDispatcher (38 sites); the slash test constructs the VM with the
test dispatcher so the IO stub is unnecessary.

---------

Co-authored-by: M57 <hy4ri@users.noreply.github.com>
This commit is contained in:
M57andM57 authored and GitHub committed 2026-08-06 15:06:28 +03:00
1 parent e56d4c9bfa
commit 75ac0c4790
14 files changed
+579 -56

No files matched your search

@@ -79,14 +79,31 @@ class ProfileScopeInterceptorTest {
@Test
fun nonScopedEndpoint_untouched() {
// Pairing is machine-global (not profile-scoped on the backend).
every { AuthManager.getSelectedProfileId() } returns "work"
val client = OkHttpClient.Builder().addInterceptor(ProfileScopeInterceptor).build()
server.enqueue(MockResponse().setResponseCode(200).setBody("{}"))
val req = Request.Builder().url(server.url("api/cron/jobs")).build()
val req = Request.Builder().url(server.url("api/pairing")).build()
client.newCall(req).execute().close()
val url = server.takeRequest().requestUrl!!
assertNull(url.queryParameter("profile"))
assertEquals("/api/cron/jobs", url.encodedPath)
assertEquals("/api/pairing", url.encodedPath)
}
@Test
fun cronSessionsPluginsEndpoints_areScoped() {
// Issue #781 follow-up: cron, sessions and plugin REST are all
// profile-scoped on the backend — switching profiles must switch
// what these screens show, so the interceptor rewrites them too.
val client = clientFor("work")
for (path in listOf("api/cron/jobs", "api/sessions", "api/plugins/hermes-achievements/achievements")) {
server.enqueue(MockResponse().setResponseCode(200).setBody("{}"))
val req = Request.Builder().url(server.url(path)).build()
client.newCall(req).execute().close()
val url = server.takeRequest().requestUrl!!
assertEquals("work", url.queryParameter("profile"))
assertEquals("/$path", url.encodedPath)
}
}
@Test
@@ -0,0 +1,266 @@
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
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
/**
* Tests for [WsProfileParams] — the WS-layer analog of
* [com.m57.hermescontrol.data.remote.ProfileScopeInterceptor].
*
* Covers the three injection rules:
* 1. Scoped method + active profile → `"profile"` injected.
* 2. Non-scoped method → params unchanged (same reference).
* 3. Explicit `"profile"` in params → preserved, never overwritten.
* 4. Null selected profile → params unchanged (same reference).
*/
class WsProfileParamsTest {
@Before
fun setUp() {
mockkObject(AuthManager)
}
@After
fun tearDown() {
unmockkAll()
}
// ── Rule 1: scoped method gets profile injected ─────────────────────
@Test
fun `scoped method injects profile when active profile is set`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
val original = mapOf("session_id" to "abc123")
val result = WsProfileParams.decorate(WsMethods.SESSION_LIST, original)
assertEquals("meow", result["profile"])
assertEquals("abc123", result["session_id"])
}
@Test
fun `session_create gets profile injected`() {
every { AuthManager.getSelectedProfileId() } returns "work"
val original = mapOf("cols" to 80)
val result = WsProfileParams.decorate(WsMethods.SESSION_CREATE, original)
assertEquals("work", result["profile"])
assertEquals(80, result["cols"])
}
@Test
fun `session_resume gets profile injected`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
val original = mapOf("session_id" to "s1")
val result = WsProfileParams.decorate(WsMethods.SESSION_RESUME, original)
assertEquals("meow", result["profile"])
assertEquals("s1", result["session_id"])
}
@Test
fun `session_delete gets profile injected`() {
every { AuthManager.getSelectedProfileId() } returns "work"
val original = mapOf("session_id" to "s2")
val result = WsProfileParams.decorate(WsMethods.SESSION_DELETE, original)
assertEquals("work", result["profile"])
}
@Test
fun `session_status gets profile injected`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
val original = mapOf("session_id" to "s3")
val result = WsProfileParams.decorate(WsMethods.SESSION_STATUS, original)
assertEquals("meow", result["profile"])
}
@Test
fun `profile_scoped decorator method gets profile injected`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
val original = emptyMap<String, Any>()
val result = WsProfileParams.decorate("verification.status", original)
assertEquals("meow", result["profile"])
}
@Test
fun `empty params map gets profile injected for scoped method`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
val result = WsProfileParams.decorate(WsMethods.SESSION_LIST, emptyMap())
assertEquals(1, result.size)
assertEquals("meow", result["profile"])
}
// ── Rule 2: non-scoped method left untouched ────────────────────────
@Test
fun `non-scoped method returns same params reference`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
val original = mapOf("session_id" to "s1", "text" to "hello")
val result = WsProfileParams.decorate(WsMethods.PROMPT_SUBMIT, original)
assertSame(original, result)
assertNull(result["profile"])
}
@Test
fun `subscription method is not profile scoped`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
val original = mapOf("plan" to "pro")
val result = WsProfileParams.decorate(WsMethods.SUBSCRIPTION_STATE, original)
assertSame(original, result)
}
@Test
fun `clarify_respond is not profile scoped`() {
every { AuthManager.getSelectedProfileId() } returns "work"
val original = mapOf("answer" to "yes")
val result = WsProfileParams.decorate(WsMethods.CLARIFY_RESPOND, original)
assertSame(original, result)
}
@Test
fun `image_attach_bytes is not profile scoped`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
val original = mapOf("data" to "base64data")
val result = WsProfileParams.decorate(WsMethods.IMAGE_ATTACH_BYTES, original)
assertSame(original, result)
}
@Test
fun `commands_catalog is not profile scoped`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
val original = emptyMap<String, Any>()
val result = WsProfileParams.decorate(WsMethods.COMMANDS_CATALOG, original)
assertSame(original, result)
}
@Test
fun `unknown method is not profile scoped`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
val original = mapOf("foo" to "bar")
val result = WsProfileParams.decorate("setup.wizard", original)
assertSame(original, result)
}
// ── Rule 3: explicit profile param wins ─────────────────────────────
@Test
fun `explicit profile in params is never overwritten`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
val original = mapOf("session_id" to "s1", "profile" to "custom")
val result = WsProfileParams.decorate(WsMethods.SESSION_LIST, original)
assertSame(original, result)
assertEquals("custom", result["profile"])
}
@Test
fun `explicit empty-string profile is preserved`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
// Caller explicitly passes profile="" — the containsKey check
// preserves this so the server sees the explicit value.
val original = mapOf("session_id" to "s1", "profile" to "")
val result = WsProfileParams.decorate(WsMethods.SESSION_LIST, original)
assertSame(original, result)
assertEquals("", result["profile"])
}
// ── Rule 4: null selected profile → pass-through ────────────────────
@Test
fun `null selected profile returns same params reference for scoped method`() {
every { AuthManager.getSelectedProfileId() } returns null
val original = mapOf("session_id" to "s1")
val result = WsProfileParams.decorate(WsMethods.SESSION_LIST, original)
assertSame(original, result)
assertNull(result["profile"])
}
@Test
fun `null selected profile returns same params for non-scoped method`() {
every { AuthManager.getSelectedProfileId() } returns null
val original = mapOf("text" to "hello")
val result = WsProfileParams.decorate(WsMethods.PROMPT_SUBMIT, original)
assertSame(original, result)
}
// ── Coverage: all scoped methods in the set ─────────────────────────
@Test
fun `all PROFILE_SCOPED_METHODS entries get profile injected`() {
every { AuthManager.getSelectedProfileId() } returns "testprofile"
for (method in WsMethods.PROFILE_SCOPED_METHODS) {
val result = WsProfileParams.decorate(method, emptyMap())
assertEquals(
"Expected profile injection for method $method",
"testprofile",
result["profile"],
)
}
}
@Test
fun `PROFILE_SCOPED_METHODS set is non-empty and contains expected core methods`() {
assertTrue(WsMethods.PROFILE_SCOPED_METHODS.isNotEmpty())
assertTrue(WsMethods.SESSION_LIST in WsMethods.PROFILE_SCOPED_METHODS)
assertTrue(WsMethods.SESSION_CREATE in WsMethods.PROFILE_SCOPED_METHODS)
assertTrue(WsMethods.SESSION_RESUME in WsMethods.PROFILE_SCOPED_METHODS)
assertTrue(WsMethods.SESSION_DELETE in WsMethods.PROFILE_SCOPED_METHODS)
assertTrue(WsMethods.SESSION_STATUS in WsMethods.PROFILE_SCOPED_METHODS)
assertTrue("verification.status" in WsMethods.PROFILE_SCOPED_METHODS)
}
// ── Interaction: sendMessage() flows through send() ─────────────────
// sendMessage() calls send(PROMPT_SUBMIT, ...) — PROMPT_SUBMIT is NOT
// in the scoped set, so profile is correctly NOT injected. The server
// resolves prompt.submit against the already-resumed session, which
// carries its own profile_home.
@Test
fun `prompt_submit is not in scoped set confirming sendMessage path is correct`() {
every { AuthManager.getSelectedProfileId() } returns "meow"
val params = mapOf("session_id" to "s1", "text" to "hello world")
val result = WsProfileParams.decorate(WsMethods.PROMPT_SUBMIT, params)
// prompt.submit is session-bound, not profile-scoped.
assertSame(params, result)
}
}
@@ -63,6 +63,7 @@ class ChatViewModelTest {
private val testDispatcher = StandardTestDispatcher()
private val mockEventsFlow = MutableSharedFlow<WsEvent>(extraBufferCapacity = 64)
private val mockConnectionStatus = MutableStateFlow(ConnectionStatus.DISCONNECTED)
private val mockSelectedProfileFlow = MutableStateFlow<String?>(null)
private lateinit var app: Application
private lateinit var fakeRepo: FakeChatPersistenceRepository
@@ -110,6 +111,7 @@ class ChatViewModelTest {
every { AuthManager.getToken() } returns "test-token"
every { AuthManager.getBaseUrl() } returns "http://test.local/"
every { AuthManager.getSelectedProfileId() } returns null
every { AuthManager.selectedProfileFlow } returns mockSelectedProfileFlow
every { AuthManager.isTypingEffectEnabled() } returns true
every { AuthManager.getTypingEffectDelayMs() } returns 30
every { AuthManager.isAutoReconnect() } returns false
@@ -241,6 +243,24 @@ class ChatViewModelTest {
verify(atLeast = 1) { HermesWsClient.send(WsMethods.SESSION_CREATE, any(), any()) }
}
@Test
fun profileSwitch_resetsOpenSessionAndReloadsSessionList() =
runTest {
val (viewModel, sessionId) = createViewModelWithSession()
assertEquals(sessionId, viewModel.uiState.value.currentSessionId)
// Selected profile changes (switch in ProfilesScreen) → chat must
// wipe the stale conversation and reload the session list
// (desktop's requestFreshSession parity — the gateway re-homes
// on profile switch and the old session id is no longer valid).
mockSelectedProfileFlow.value = "meow"
advanceUntilIdle()
assertNull(viewModel.uiState.value.currentSessionId)
assertEquals("Hermes", viewModel.uiState.value.chatTitle)
verify(atLeast = 1) { HermesWsClient.send(WsMethods.SESSION_LIST, any(), any()) }
}
@Test
fun testSlashCommand_fork_sendsSessionBranch() =
runTest {
@@ -55,7 +55,6 @@ class SlashCommandDispatchRpcTest {
@Before
fun setUp() {
Dispatchers.setMain(testDispatcher)
val testMainDispatcher = Dispatchers.Main
reqCount = 0
mockkStatic(android.util.Log::class)
@@ -64,10 +63,11 @@ class SlashCommandDispatchRpcTest {
every { android.util.Log.w(any(), any<String>()) } returns 0
every { android.util.Log.e(any(), any(), any()) } returns 0
mockkStatic(Dispatchers::class)
every { Dispatchers.IO } returns testDispatcher
every { Dispatchers.Main } returns testMainDispatcher
// 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).
mockkObject(AuthManager)
mockkObject(HermesWsClient)
mockkObject(ApiClient)
@@ -110,7 +110,7 @@ class SlashCommandDispatchRpcTest {
}
private suspend fun TestScope.createViewModelWithSession(): Pair<ChatViewModel, String> {
val vm = ChatViewModel(app, false, fakeRepo)
val vm = ChatViewModel(app, false, fakeRepo, ioDispatcher = testDispatcher)
advanceUntilIdle()
mockConnectionStatus.value = ConnectionStatus.CONNECTED
mockEventsFlow.emit(WsEvent.GatewayReady(null))
@@ -392,7 +392,7 @@ class ConnectViewModelTest {
}
@Test
fun testLoadSavedValues_withStaleSelectedId_fallsBackToDefaults() {
fun testLoadSavedValues_withStaleSelectedId_prefillsSelectedId() {
val profile =
ConnectionProfile(
id = "prof-1",
@@ -407,7 +407,10 @@ class ConnectViewModelTest {
val state = viewModel.uiState.value
assertNull(state.selectedProfile)
assertEquals("", state.profileName)
// Profile name prefills the selected id so a re-login after switching
// to a profile created in-app (no saved connection yet) stays on that
// profile instead of silently landing back on default.
assertEquals("nonexistent-id", state.profileName)
assertEquals("https://127.0.0.1:9119/", state.baseUrl)
}
@@ -13,6 +13,7 @@ import com.m57.hermescontrol.data.model.ProfilesResponse
import com.m57.hermescontrol.data.model.RenameProfileRequest
import com.m57.hermescontrol.data.remote.ApiClient
import com.m57.hermescontrol.data.remote.HermesApiService
import com.m57.hermescontrol.data.ws.HermesWsClient
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
@@ -20,6 +21,7 @@ import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.mockkStatic
import io.mockk.unmockkAll
import io.mockk.verify
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
@@ -50,6 +52,8 @@ class ProfilesViewModelTest {
private val testDispatcher = StandardTestDispatcher()
private lateinit var mockApi: HermesApiService
private var storedPinnedModels: MutableList<PinnedModel> = mutableListOf()
private var storedSelectedProfile: String? = null
private var storedProfileToken: String? = null
private fun stubProfilesLoad() {
coEvery { mockApi.getProfiles() } returns
@@ -68,10 +72,25 @@ class ProfilesViewModelTest {
mockkObject(AuthManager)
storedPinnedModels = mutableListOf()
storedSelectedProfile = null
storedProfileToken = null
every { AuthManager.getPinnedModels() } answers { storedPinnedModels.toList() }
every { AuthManager.savePinnedModels(any()) } answers {
storedPinnedModels = firstArg<List<PinnedModel>>().toMutableList()
}
every { AuthManager.getSelectedProfileId() } answers { storedSelectedProfile }
every { AuthManager.setSelectedProfileId(any()) } answers {
storedSelectedProfile = firstArg<String?>()
}
every { AuthManager.getToken() } answers { "tok-abc" }
every { AuthManager.getProfileToken(any()) } answers { storedProfileToken }
every { AuthManager.setProfileToken(any(), any()) } answers {
storedProfileToken = secondArg<String?>()
}
mockkObject(HermesWsClient)
every { HermesWsClient.disconnect() } returns Unit
every { HermesWsClient.connect() } returns Unit
mockkObject(ApiClient)
mockApi = mockk(relaxed = true)
@@ -262,4 +281,55 @@ class ProfilesViewModelTest {
assertTrue(vm.uiState.value.modelPickerPinned.isEmpty())
assertTrue(storedPinnedModels.isEmpty())
}
@Test
fun `selectActiveProfile success persists selection and rehomes websocket`() {
coEvery { mockApi.setActiveProfile(any()) } returns Response.success(Unit)
val vm = createViewModel()
vm.selectActiveProfile("work")
testDispatcher.scheduler.advanceUntilIdle()
// Local selection persisted → ProfileScopeInterceptor now scopes all
// management REST calls (?profile=work) to the new profile.
assertEquals("work", storedSelectedProfile)
// Token inherited from the current connection so switching to a
// same-dashboard profile doesn't force a re-login (token_<profile>
// is keyed per profile and a freshly-created profile has none).
assertEquals("tok-abc", storedProfileToken)
// WebSocket re-homed so the live gateway follows the new profile.
verify { HermesWsClient.disconnect() }
verify { HermesWsClient.connect() }
assertTrue(vm.uiState.value.toastMessage!!.contains("Switched to profile work"))
coVerify { mockApi.getProfiles() }
}
@Test
fun `selectActiveProfile keeps existing token for the target profile`() {
storedProfileToken = "tok-meow"
coEvery { mockApi.setActiveProfile(any()) } returns Response.success(Unit)
val vm = createViewModel()
vm.selectActiveProfile("meow")
testDispatcher.scheduler.advanceUntilIdle()
// A profile that already has its own token (e.g. connected elsewhere)
// must NOT be clobbered by inheritance.
assertEquals("tok-meow", storedProfileToken)
assertEquals("meow", storedSelectedProfile)
}
@Test
fun `selectActiveProfile failure rolls back and keeps local selection`() {
coEvery { mockApi.setActiveProfile(any()) } returns errorResponse(500)
val vm = createViewModel()
vm.selectActiveProfile("work")
testDispatcher.scheduler.advanceUntilIdle()
assertNull(storedSelectedProfile)
assertNull(storedProfileToken)
assertNull(vm.uiState.value.activeProfileName)
assertTrue(vm.uiState.value.toastMessage!!.contains("Failed to switch profile"))
}
}