fix(android): name the human on their own chat rows
ci / checks (push) Canceled after 0s
ci / test (push) Canceled after 0s
ci / chart (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / web (push) Canceled after 0s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Canceled after 0s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Canceled after 0s
ci / publish-edge-chart (push) Canceled after 0s
android / debug (push) Canceled after 0s
android / release (push) Canceled after 0s

The transcript said "you" under a bare initial on the reader's rows
while their name sat unused in GET /v1/user: the phone never fetched
the profile, so a name and picture set on the web survived only there.

UserProfile and UserProfileRepository cache the document and the
avatar bytes in DataStore beside the agent's identity, refreshed on app
open, on the sessions screen's refresh, and when a turn settles —
onboarding sets the profile mid-conversation. The bytes are fetched
only while the cache has none, so a turn-end refresh does not re-download
the picture; the profile carries presence, not a version, and the web
client makes the same trade.

ChatScreen reads that cache: the name takes the author slot and the
picture fills the 24 dp circle, with "you" only until a name is set. A
dispatch row keeps its own label and initial.

compileDebugKotlin passes.
This commit is contained in:
vhaudiquet committed 2026-12-02 11:38:05 +01:00
1 parent 68f1a6be89
commit 6f68ec6a22
8 files changed
+182 -11

No files matched your search

@@ -30,6 +30,7 @@ import rs.rhema.phone.di.AppContainer
import rs.rhema.phone.ui.ChatScreen import rs.rhema.phone.ui.ChatScreen
import rs.rhema.phone.ui.RhemaTheme import rs.rhema.phone.ui.RhemaTheme
import rs.rhema.phone.ui.TogetherGroundDark import rs.rhema.phone.ui.TogetherGroundDark
import kotlinx.coroutines.launch
import rs.rhema.phone.ui.TogetherGroundLight import rs.rhema.phone.ui.TogetherGroundLight
import rs.rhema.phone.ui.SessionsScreen import rs.rhema.phone.ui.SessionsScreen
import rs.rhema.phone.ui.SettingsScreen import rs.rhema.phone.ui.SettingsScreen
@@ -112,10 +113,14 @@ private fun AppRoot(container: AppContainer) {
showSettings = false showSettings = false
} }
// The agent's identity (name, avatar) is refreshed once per app open // The agent's identity and the human's profile (name, avatar) are
// and cached in DataStore; the sessions screen's refresh re-fetches it. // refreshed once per app open and cached in DataStore; the sessions
// screen's refresh re-fetches both.
LaunchedEffect(configured) { LaunchedEffect(configured) {
if (configured == true) container.identity.refresh() if (configured == true) {
launch { container.identity.refresh() }
launch { container.userProfile.refresh() }
}
} }
when { when {
@@ -44,6 +44,9 @@ class ChatController(
private val cache: SessionCache, private val cache: SessionCache,
private val scope: CoroutineScope, private val scope: CoroutineScope,
val sessionKey: String, val sessionKey: String,
// Runs when a turn settles. The claw may have set the human's profile
// during it (onboarding does), and the rows read that cache.
private val onTurnDone: () -> Unit = {},
) { ) {
sealed interface Item { sealed interface Item {
val id: Long val id: Long
@@ -215,7 +218,10 @@ class ChatController(
} }
applied.add(Applied(seq, event)) applied.add(Applied(seq, event))
items = applyEvent(items, event) items = applyEvent(items, event)
if (event is ClawEvent.TurnDone) persist() if (event is ClawEvent.TurnDone) {
persist()
onTurnDone()
}
} }
// The claw no longer holds what this screen's cursor named: the // The claw no longer holds what this screen's cursor named: the
@@ -0,0 +1,89 @@
package rs.rhema.phone.data
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.byteArrayPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import rs.rhema.phone.net.ClawApi
import rs.rhema.phone.net.ClawResult
import rs.rhema.phone.net.UserProfile
// The human's name and picture as the phone last saw them: the profile
// document plus the avatar bytes, cached in DataStore beside the agent's
// identity. The chat's own rows read this, so a refresh that fails never
// drops the reader's face back to a bare initial.
class UserProfileCache(
val profile: UserProfile? = null,
val avatar: ByteArray? = null,
)
class UserProfileRepository(
private val store: DataStore<Preferences>,
private val api: ClawApi,
private val json: Json,
) {
private object Keys {
val profileJson = stringPreferencesKey("user_profile_json")
val avatarBytes = byteArrayPreferencesKey("user_avatar_bytes")
}
private val refreshMutex = Mutex()
val cached: Flow<UserProfileCache> = store.data.map { prefs ->
val profile = prefs[Keys.profileJson]?.let { raw ->
runCatching { json.decodeFromString<UserProfile>(raw) }.getOrNull()
}
UserProfileCache(profile, prefs[Keys.avatarBytes])
}
// Fetches the profile and, when a picture is set, its bytes. Every
// failure keeps the cache as it was: presentation state owes the
// reader nothing but the last known face.
suspend fun refresh() = refreshMutex.withLock {
val profile = when (val result = api.user()) {
is ClawResult.Ok -> result.value
else -> return@withLock
}
val current = store.data.first()
val cachedAvatar = current[Keys.avatarBytes]
// A turn-end refresh must not re-download the same picture: the
// bytes are fetched only while the cache has none. The profile
// document carries presence, not a version, so a picture
// replaced behind an unchanged flag keeps the cached bytes until
// the flag clears. The web client makes the same trade.
val avatar = when {
!profile.avatar -> null
cachedAvatar != null -> cachedAvatar
else -> when (val result = api.userAvatar()) {
is ClawResult.Ok -> result.value.takeIf { it.isNotEmpty() }
else -> null
}
}
val encoded = json.encodeToString(profile)
store.edit { prefs ->
if (prefs[Keys.profileJson] != encoded) prefs[Keys.profileJson] = encoded
val currentBytes = prefs[Keys.avatarBytes]
when {
// Rewrite only on change: the picture can weigh megabytes
// and each refresh would otherwise write it again.
profile.avatar && avatar != null ->
if (currentBytes?.contentEquals(avatar) != true) {
prefs[Keys.avatarBytes] = avatar
}
profile.avatar == false && currentBytes != null ->
prefs.remove(Keys.avatarBytes)
// The profile says a picture exists but the fetch failed:
// the cached bytes stay until a fetch succeeds.
else -> Unit
}
}
}
}
@@ -6,6 +6,7 @@ import rs.rhema.phone.diagnostics.DiagLog
import rs.rhema.phone.data.SessionCache import rs.rhema.phone.data.SessionCache
import rs.rhema.phone.data.SettingsRepository import rs.rhema.phone.data.SettingsRepository
import rs.rhema.phone.data.StatusRepository import rs.rhema.phone.data.StatusRepository
import rs.rhema.phone.data.UserProfileRepository
import rs.rhema.phone.data.rhemaStore import rs.rhema.phone.data.rhemaStore
import rs.rhema.phone.net.ClawApi import rs.rhema.phone.net.ClawApi
import rs.rhema.phone.notif.Notifier import rs.rhema.phone.notif.Notifier
@@ -37,6 +38,10 @@ class AppContainer(context: Context) {
val identity = AgentIdentityRepository(appContext.rhemaStore, api, json) val identity = AgentIdentityRepository(appContext.rhemaStore, api, json)
// The human's side of the chat: the name and picture their own rows
// carry, cached beside the agent's identity.
val userProfile = UserProfileRepository(appContext.rhemaStore, api, json)
val notifier = Notifier(appContext) val notifier = Notifier(appContext)
// The workers' flight recorder: every run logs its outcome here, and // The workers' flight recorder: every run logs its outcome here, and
@@ -194,6 +194,23 @@ class ClawApi(
return rawGet(builder) return rawGet(builder)
} }
// The human's picture behind GET /v1/user; the profile document's
// `avatar` flag says whether the fetch can succeed.
suspend fun userAvatar(): ClawResult<ByteArray> {
val builder = v1("user", "avatar")
?: return ClawResult.Network("no base URL configured")
return rawGet(builder)
}
// GET /v1/user: the human's profile — the display name and whether
// the picture is set.
suspend fun user(): ClawResult<UserProfile> {
val builder = v1("user") ?: return ClawResult.Network("no base URL configured")
return execute(builder.get().build()) { response ->
json.decodeFromString<UserProfile>(response.body?.string() ?: "{}")
}
}
private suspend fun rawGet(builder: Request.Builder): ClawResult<ByteArray> = private suspend fun rawGet(builder: Request.Builder): ClawResult<ByteArray> =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
try { try {
@@ -269,3 +269,12 @@ data class AgentIdentity(
val avatar: Boolean = false, val avatar: Boolean = false,
val logo: Boolean = false, val logo: Boolean = false,
) )
// GET /v1/user — the human's profile, shared with the web interface: the
// display name their own chat rows carry and whether a picture is set.
// The bytes live at GET /v1/user/avatar.
@Serializable
data class UserProfile(
val name: String? = null,
val avatar: Boolean = false,
)
@@ -82,6 +82,7 @@ import rs.rhema.phone.chat.ChatController
import rs.rhema.phone.chat.MAX_IMAGE_BYTES import rs.rhema.phone.chat.MAX_IMAGE_BYTES
import rs.rhema.phone.chat.MAX_STAGED_IMAGES import rs.rhema.phone.chat.MAX_STAGED_IMAGES
import rs.rhema.phone.data.AgentIdentityCache import rs.rhema.phone.data.AgentIdentityCache
import rs.rhema.phone.data.UserProfileCache
import rs.rhema.phone.di.AppContainer import rs.rhema.phone.di.AppContainer
import rs.rhema.phone.net.ClawResult import rs.rhema.phone.net.ClawResult
import rs.rhema.phone.net.PasteSpan import rs.rhema.phone.net.PasteSpan
@@ -102,7 +103,13 @@ import android.provider.OpenableColumns
@Composable @Composable
fun ChatScreen(container: AppContainer, sessionKey: String, onBack: () -> Unit) { fun ChatScreen(container: AppContainer, sessionKey: String, onBack: () -> Unit) {
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
val controller = remember(sessionKey) { ChatController(container.api, container.sessionCache, scope, sessionKey) } val controller = remember(sessionKey) {
ChatController(container.api, container.sessionCache, scope, sessionKey) {
// The turn may have set the human's name or picture; the rows
// read the cache it writes.
scope.launch { container.userProfile.refresh() }
}
}
// The SSE connection lives exactly as long as this screen is composed. // The SSE connection lives exactly as long as this screen is composed.
DisposableEffect(sessionKey) { DisposableEffect(sessionKey) {
controller.start() controller.start()
@@ -175,6 +182,9 @@ fun ChatScreen(container: AppContainer, sessionKey: String, onBack: () -> Unit)
// set), the initials glyph otherwise, and the agent's name on every // set), the initials glyph otherwise, and the agent's name on every
// turn — the same face the web UI shows. // turn — the same face the web UI shows.
val face = rememberAgentFace(container) val face = rememberAgentFace(container)
// The human's name and picture, the same cache the sessions screen
// refreshes: their own rows carry them instead of a bare "you".
val userFace = rememberUserFace(container)
Column(modifier = Modifier.fillMaxSize()) { Column(modifier = Modifier.fillMaxSize()) {
ChatHeader(sessionKey, controller.connection, face, onBack) ChatHeader(sessionKey, controller.connection, face, onBack)
@@ -211,7 +221,7 @@ fun ChatScreen(container: AppContainer, sessionKey: String, onBack: () -> Unit)
verticalArrangement = Arrangement.spacedBy(20.dp), verticalArrangement = Arrangement.spacedBy(20.dp),
) { ) {
items(turnGroups(controller.items).asReversed(), key = { it.key }) { group -> items(turnGroups(controller.items).asReversed(), key = { it.key }) { group ->
TurnGroupRow(group, container, controller, face) TurnGroupRow(group, container, controller, face, userFace)
} }
// The last declared item sits at the top of a reversed list. // The last declared item sits at the top of a reversed list.
if (controller.loadingOlder) { if (controller.loadingOlder) {
@@ -473,13 +483,20 @@ private fun TurnGroupRow(
container: AppContainer, container: AppContainer,
controller: ChatController, controller: ChatController,
face: AgentFace, face: AgentFace,
userFace: UserFace,
) { ) {
// The reader's rows say who they are the way the web surface does: // The reader's rows say who they are the way the web surface does:
// "you" on the conversable keys, "dispatch" on the others, and the // the human's profile name on the conversable keys (their initial and
// matching initial in the round avatar. // picture nest to it), the generic "you" while no name is set, and
// "dispatch" on the others — a trigger's row is not the human's.
val you = controller.sessionKey.startsWith("interactive:") || val you = controller.sessionKey.startsWith("interactive:") ||
controller.sessionKey.startsWith("phone:") controller.sessionKey.startsWith("phone:")
val author = stringResource(if (you) R.string.chat_user_you else R.string.chat_user_dispatch) val author = if (you) {
userFace.name ?: stringResource(R.string.chat_user_you)
} else {
stringResource(R.string.chat_user_dispatch)
}
val avatar = if (you) userFace.image else null
when (group) { when (group) {
is TurnGroup.User -> Row( is TurnGroup.User -> Row(
@@ -1345,6 +1362,27 @@ private fun ConsentCard(item: ChatController.Consent, controller: ChatController
// `initials`, else the name's first letter, else "R". // `initials`, else the name's first letter, else "R".
private data class AgentFace(val name: String?, val glyph: String, val image: ImageBitmap?) private data class AgentFace(val name: String?, val glyph: String, val image: ImageBitmap?)
// The human's face as this screen renders it: their profile name and
// their picture, when one is set. Null name keeps the `you` fallback.
private data class UserFace(val name: String?, val image: ImageBitmap?)
@Composable
private fun rememberUserFace(container: AppContainer): UserFace {
val cache by container.userProfile.cached.collectAsState(UserProfileCache())
var image by remember { mutableStateOf<ImageBitmap?>(null) }
// Decoding off the main thread: a picture can weigh the claw's full
// 2 MB image cap, the same budget the agent's avatar carries.
LaunchedEffect(cache.avatar) {
image = cache.avatar?.let { bytes ->
withContext(Dispatchers.Default) {
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)?.asImageBitmap()
}
}
}
val name = cache.profile?.name?.trim()?.takeIf { it.isNotEmpty() }
return UserFace(name, image)
}
@Composable @Composable
private fun rememberAgentFace(container: AppContainer): AgentFace { private fun rememberAgentFace(container: AppContainer): AgentFace {
val cache by container.identity.cached.collectAsState(AgentIdentityCache()) val cache by container.identity.cached.collectAsState(AgentIdentityCache())
@@ -54,8 +54,10 @@ fun SessionsScreen(
loading = true loading = true
error = null error = null
// The agent may have renamed or re-faced itself on another // The agent may have renamed or re-faced itself on another
// surface; this button is the manual path for the cached identity. // surface, and so may the human; this button is the manual
container.identity.refresh() // path for both caches.
launch { container.identity.refresh() }
launch { container.userProfile.refresh() }
when (val result = container.api.sessions()) { when (val result = container.api.sessions()) {
is ClawResult.Ok -> sessions = result.value is ClawResult.Ok -> sessions = result.value
is ClawResult.HttpError -> error = UiMessage.Http(result.code, result.body) is ClawResult.HttpError -> error = UiMessage.Http(result.code, result.body)