From 79ff9ee1fcad713fcb8944a40c61651ebec9bb2d Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Mon, 14 Sep 2026 20:10:13 +0200 Subject: [PATCH] fix(chat): the detail pane's view models are the selected room's, not the first one's In an expanded window the transcript beside the room list showed the first room opened and stayed there: pick another room and the list moved on while the pane did not. HomeScreen wraps the pane in key(chatRoomId), which rebuilds the composition when the selection changes, but viewModel() does not read composition keys. It scopes to the nearest ViewModelStoreOwner, and in the pane that is the home destination's one back stack entry for every room, so the second room's viewModel(factory = ...) got the first room's ChatRoomMessagingViewModel and ChatMessageListViewModel back with its factory ignored. A phone never showed it because a pushed room is its own entry with its own store. The pane now provides LocalViewModelStoreOwner with rememberViewModelStoreOwner() under the room key: a store per room, cleared when the selection moves on, and parked in the home entry's store so that it survives a rotation. Keying the two viewModel() calls on the room would have unstuck the pane too, at the price of keeping every room ever opened -- four DB collectors each -- in the home entry's store for as long as the home screen lives. ChatPaneSelectionJvmTest opens two rooms and comes back to the first, told apart by what was said in them since a name is on the row as well as the bar; its third case checks the room left behind stops collecting, which is the case the keyed alternative fails. The conformance doc's account of the hand-built pair records the trap. Co-Authored-By: Claude Opus 5 --- .../compose/ui/composable/HomeScreen.kt | 65 +++-- .../ui/composable/ChatPaneSelectionJvmTest.kt | 223 ++++++++++++++++++ docs/material-design-conformance.md | 11 + 3 files changed, 279 insertions(+), 20 deletions(-) create mode 100644 composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/ChatPaneSelectionJvmTest.kt diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/HomeScreen.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/HomeScreen.kt index a00c7105..6aca34e8 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/HomeScreen.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/HomeScreen.kt @@ -28,6 +28,7 @@ import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.key import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -39,6 +40,8 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp +import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner +import androidx.lifecycle.viewmodel.compose.rememberViewModelStoreOwner import androidx.lifecycle.viewmodel.compose.viewModel import to.curare.compose.database.model.NostrEvent import to.curare.compose.database.model.Profile @@ -310,27 +313,49 @@ fun HomeScreen( message = stringResource(Res.string.pick_a_conversation_to_read_it_here) ) } else { - // Keyed on the room, so switching rooms rebuilds the - // screen's view models rather than feeding a new id to - // ones already subscribed to another room's relay. + // Keyed on the room, and given a view model store of its + // own under that key. `viewModel()` scopes to the nearest + // owner, which on a phone is the room's own back stack + // entry: every push gets a fresh store, and the screen + // never has to think about it. The pane is not pushed. + // Every room it shows shares the home destination's + // entry, where the first room's view models sat under + // the unkeyed slot and each later `viewModel(factory = + // …)` got them back with its factory ignored -- the + // transcript stayed on the first room opened, whatever + // the list said. `key` alone rebuilds the composition, + // not the store. Keying the `viewModel()` calls on the + // room would unstick it at the price of keeping every + // room ever opened, DB observers and all, in the home + // entry's store for as long as the home screen lives. + // This is what a back stack entry gives a phone, given + // to the pane: a store cleared when the room changes, + // and parked in the home entry's so that it survives a + // rotation. ChatPaneSelectionJvmTest holds it to both. key(chatRoomId) { - ChatRoomMessagingScreen( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = selectedRelayHint, - nostrRepository = nostrRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - dkgRepository = dkgRepository, - // "Replace what is on screen" is a route push on a - // phone and a change of selection here. It fires when - // a conversation that did not exist yet has just been - // created and has an id at last. - onNavigateToRouteAndPopUpInclusive = onOpenChatRoom, - onNavigateToRoute = onNavigateToRoute, - // The list is beside it; there is nothing to pop. - onNavigateBack = null, - ) + CompositionLocalProvider( + LocalViewModelStoreOwner provides rememberViewModelStoreOwner() + ) { + ChatRoomMessagingScreen( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = selectedRelayHint, + nostrRepository = nostrRepository, + chatRepository = chatRepository, + frostSigningRepository = frostSigningRepository, + dkgRepository = dkgRepository, + // "Replace what is on screen" is a route push + // on a phone and a change of selection here. + // It fires when a conversation that did not + // exist yet has just been created and has an + // id at last. + onNavigateToRouteAndPopUpInclusive = onOpenChatRoom, + onNavigateToRoute = onNavigateToRoute, + // The list is beside it; there is nothing to + // pop. + onNavigateBack = null, + ) + } } } } diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/ChatPaneSelectionJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/ChatPaneSelectionJvmTest.kt new file mode 100644 index 00000000..543b2ded --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/ChatPaneSelectionJvmTest.kt @@ -0,0 +1,223 @@ +package to.curare.compose.ui.composable + +import androidx.compose.runtime.Composable +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.hasClickAction +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.runDesktopComposeUiTest +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.onCompletion +import to.curare.compose.database.model.ChatMessage +import to.curare.compose.database.model.ChatRoom +import to.curare.compose.database.model.NostrEvent +import to.curare.compose.database.model.Profile +import to.curare.compose.database.model.intermdiate.LocalChatMessage +import to.curare.compose.database.model.intermdiate.LocalChatRoom +import to.curare.compose.database.model.intermdiate.LocalProfileWithFollowing +import to.curare.compose.repository.ChatRepository +import to.curare.compose.repository.DkgRepository +import to.curare.compose.repository.FrostSigningRepository +import to.curare.compose.repository.NostrRepository +import to.curare.compose.ui.composable.widgets.ProvideSnackbarHost +import to.curare.compose.ui.theme.CurareTheme +import to.curare.compose.ui.view.state.HomeScreenUIState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import java.util.concurrent.ConcurrentHashMap +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * The detail pane follows the selection. + * + * On a phone a room is a route, and every push is a back stack entry with a + * `ViewModelStore` of its own: `viewModel()` in the room screen finds nothing under its + * key and builds from the factory it was handed. In an expanded window the pane is not + * pushed. Every room it shows is composed under the home destination's one entry, and + * `viewModel()` there found the *first* room's view models and handed them back with the + * factory unread -- so the transcript stayed on the first room opened while the list + * went on to another. Keying the composition on the room did not help; it is the store + * that has to be keyed, and [ChatPaneLayoutJvmTest] cannot see that because it never + * opens a room. + * + * The rooms are told apart by what was said in them rather than by their names, because + * a name is on the list row as well as the transcript's bar, and the row was the one + * thing that was right. + * + * The third test is about the fix rather than the bug. Keying the `viewModel()` calls + * on the room would pass the first two, and keep every room ever opened -- observers and + * all -- in the home entry's store for as long as the home screen lives. A store per + * room is cleared when the pane moves on, and the way to see that from outside is that + * the room left behind stops collecting its messages. + */ +@OptIn(ExperimentalTestApi::class) +class ChatPaneSelectionJvmTest { + + private val publicKey = "de1a1e64d1c4e0d6bd97b0e73d4dfd0e1ec1cdd1e6d8d0e2b9a7f3c5d0e1a2b3" + + @Test + fun `opening a second room shows the second room, not the first`() = + runDesktopComposeUiTest(1000, 900) { + setContent { Home() } + + open("Alpha") + awaitLine("Hello from Alpha") + + open("Beta") + awaitLine("Hello from Beta") + onNodeWithText("Hello from Alpha").assertDoesNotExist() + } + + @Test + fun `and coming back to the first shows the first again`() = + runDesktopComposeUiTest(1000, 900) { + setContent { Home() } + + open("Alpha") + awaitLine("Hello from Alpha") + open("Beta") + awaitLine("Hello from Beta") + + open("Alpha") + awaitLine("Hello from Alpha") + onNodeWithText("Hello from Beta").assertDoesNotExist() + } + + @Test + fun `the room left behind stops listening`() = runDesktopComposeUiTest(1000, 900) { + setContent { Home() } + + open("Alpha") + awaitLine("Hello from Alpha") + assertEquals(setOf(alpha.chatRoom.id), listening) + + open("Beta") + awaitLine("Hello from Beta") + // The old view model's scope is cancelled when its store is cleared; the + // collector notices on its own thread, so this is a wait rather than a read. + waitUntil(timeoutMillis = 5_000) { listening == setOf(beta.chatRoom.id) } + } + + /** Taps the room's row. The row is the node with its name that can be clicked. */ + private fun ComposeUiTest.open(subject: String) = + onNode(hasText(subject) and hasClickAction()).performClick() + + /** Waits for the transcript to say something, which it does from an IO thread. */ + private fun ComposeUiTest.awaitLine(text: String) { + waitUntil(timeoutMillis = 5_000) { + onAllNodesWithText(text).fetchSemanticsNodes().isNotEmpty() + } + onNodeWithText(text).assertIsDisplayed() + } + + @Composable + private fun Home() { + CurareTheme { + ProvideSnackbarHost { + HomeScreen( + activeUserPublicKey = publicKey, + initialHomeScreenUIState = HomeScreenUIState.Loaded(profileWithFollowing = profile), + onNavigateToRoute = {}, + onNavigateToDirectMessageDetail = {}, + onNavigateToChatRoomCreation = {}, + nostrRepository = FixedProfile, + chatRepository = TwoRooms, + frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, + dkgRepository = DkgRepository.NO_OP_DKG_REPOSITORY, + ) + } + } + } + + private val profile = LocalProfileWithFollowing( + nostrEvent = NostrEvent( + id = "aa11bb22cc33dd44ee55ff6600778899aabbccddeeff00112233445566778899", + pubKey = publicKey, + content = "", + tags = emptyArray(), + sig = "", + kind = TextNoteEvent.KIND, + ), + profile = Profile( + publicKey = publicKey, + displayName = "Reader", + nostrEventId = "aa11bb22cc33dd44ee55ff6600778899aabbccddeeff00112233445566778899", + ), + following = emptyList(), + ) + + private fun room(id: HexKey, subject: String) = LocalChatRoom( + chatRoom = ChatRoom( + id = id, + userPublicKey = publicKey, + subject = subject, + description = null, + initialGiftWrapPayloadId = null, + mlsGroupState = null, + ), + ) + + private fun line(id: Long, room: LocalChatRoom, content: String) = LocalChatMessage( + chatMessage = ChatMessage( + id = id, + senderPublicKey = publicKey, + isUserMessage = true, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = room.chatRoom.id, + content = content, + ), + profile = profile.profile, + ) + + private val alpha = room("a".repeat(64), "Alpha") + private val beta = room("b".repeat(64), "Beta") + + /** The no-op repository, plus the one read the home screen makes of it. */ + private val FixedProfile = object : NostrRepository by NostrRepository.NO_OP_NOSTR_REPOSITORY { + override suspend fun observeProfileWithFollowing( + publicKey: String, + ): Flow = flowOf(profile) + } + + /** The rooms whose message flow somebody is collecting right now. */ + private val listening: MutableSet = ConcurrentHashMap.newKeySet() + + /** + * The no-op repository, plus the three reads a list beside a transcript makes of it: + * the rooms, the room that was tapped, and what was said in it. The last of those + * never completes, the way a database observation never completes, so that its + * cancellation is something the test can see. + */ + private val TwoRooms = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { + override suspend fun observeChatRoomListByPublicKey( + publicKey: String, + ): Flow> = flowOf(listOf(alpha, beta)) + + override suspend fun getChatRoomByIdentifier(id: HexKey): LocalChatRoom? = + listOf(alpha, beta).firstOrNull { it.chatRoom.id == id } + + override suspend fun observeChatMessageListByChatRoomId( + chatRoomId: String, + ): Flow> = flow { + listening += chatRoomId + emit( + when (chatRoomId) { + alpha.chatRoom.id -> listOf(line(1, alpha, "Hello from Alpha")) + beta.chatRoom.id -> listOf(line(2, beta, "Hello from Beta")) + else -> emptyList() + } + ) + awaitCancellation() + }.onCompletion { listening -= chatRoomId } + } +} diff --git a/docs/material-design-conformance.md b/docs/material-design-conformance.md index e59adf82..4fd43ad0 100644 --- a/docs/material-design-conformance.md +++ b/docs/material-design-conformance.md @@ -831,6 +831,17 @@ panes last because both were product decisions. the `Scaffold`'s slot is the bottom-right of the window, which with two panes is on top of the transcript's send button. + One thing a route gets for free that a pane has to be given: a `ViewModelStore`. + `viewModel()` scopes to the nearest owner, and for a pushed conversation that is + its own back stack entry. In the pane every conversation is composed under the + home destination's one entry, so the second room opened got the first room's view + models back with its factory ignored, and the transcript stayed where it was + while the list moved on. `key(chatRoomId)` rebuilds the composition, not the + store. The pane now provides `rememberViewModelStoreOwner()` under that key — + cleared when the room changes, which keying the `viewModel()` calls instead would + not have done, and parked in the home entry's store so that it survives a + rotation. `ChatPaneSelectionJvmTest` opens two rooms and checks both halves. + 7. **The desktop window opens at 1100×800** — inside the expanded breakpoint, the narrowest window M3 recommends two panes in — with a 400×600 minimum it never had. The comment apologising for the old 480dp size is gone because it has