diff --git a/android/app/src/main/java/rs/rhema/phone/MainActivity.kt b/android/app/src/main/java/rs/rhema/phone/MainActivity.kt index cedbb65..70898e5 100644 --- a/android/app/src/main/java/rs/rhema/phone/MainActivity.kt +++ b/android/app/src/main/java/rs/rhema/phone/MainActivity.kt @@ -30,6 +30,7 @@ import rs.rhema.phone.di.AppContainer import rs.rhema.phone.ui.ChatScreen import rs.rhema.phone.ui.RhemaTheme import rs.rhema.phone.ui.TogetherGroundDark +import kotlinx.coroutines.launch import rs.rhema.phone.ui.TogetherGroundLight import rs.rhema.phone.ui.SessionsScreen import rs.rhema.phone.ui.SettingsScreen @@ -112,10 +113,14 @@ private fun AppRoot(container: AppContainer) { showSettings = false } - // The agent's identity (name, avatar) is refreshed once per app open - // and cached in DataStore; the sessions screen's refresh re-fetches it. + // The agent's identity and the human's profile (name, avatar) are + // refreshed once per app open and cached in DataStore; the sessions + // screen's refresh re-fetches both. LaunchedEffect(configured) { - if (configured == true) container.identity.refresh() + if (configured == true) { + launch { container.identity.refresh() } + launch { container.userProfile.refresh() } + } } when { diff --git a/android/app/src/main/java/rs/rhema/phone/chat/ChatController.kt b/android/app/src/main/java/rs/rhema/phone/chat/ChatController.kt index 60f2009..6137854 100644 --- a/android/app/src/main/java/rs/rhema/phone/chat/ChatController.kt +++ b/android/app/src/main/java/rs/rhema/phone/chat/ChatController.kt @@ -44,6 +44,9 @@ class ChatController( private val cache: SessionCache, private val scope: CoroutineScope, 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 { val id: Long @@ -215,7 +218,10 @@ class ChatController( } applied.add(Applied(seq, 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 diff --git a/android/app/src/main/java/rs/rhema/phone/data/UserProfileRepository.kt b/android/app/src/main/java/rs/rhema/phone/data/UserProfileRepository.kt new file mode 100644 index 0000000..578b84e --- /dev/null +++ b/android/app/src/main/java/rs/rhema/phone/data/UserProfileRepository.kt @@ -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, + 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 = store.data.map { prefs -> + val profile = prefs[Keys.profileJson]?.let { raw -> + runCatching { json.decodeFromString(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 + } + } + } +} diff --git a/android/app/src/main/java/rs/rhema/phone/di/AppContainer.kt b/android/app/src/main/java/rs/rhema/phone/di/AppContainer.kt index 78323e3..ddca03b 100644 --- a/android/app/src/main/java/rs/rhema/phone/di/AppContainer.kt +++ b/android/app/src/main/java/rs/rhema/phone/di/AppContainer.kt @@ -6,6 +6,7 @@ import rs.rhema.phone.diagnostics.DiagLog import rs.rhema.phone.data.SessionCache import rs.rhema.phone.data.SettingsRepository import rs.rhema.phone.data.StatusRepository +import rs.rhema.phone.data.UserProfileRepository import rs.rhema.phone.data.rhemaStore import rs.rhema.phone.net.ClawApi import rs.rhema.phone.notif.Notifier @@ -37,6 +38,10 @@ class AppContainer(context: Context) { 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) // The workers' flight recorder: every run logs its outcome here, and diff --git a/android/app/src/main/java/rs/rhema/phone/net/ClawApi.kt b/android/app/src/main/java/rs/rhema/phone/net/ClawApi.kt index 62a2a27..6e81247 100644 --- a/android/app/src/main/java/rs/rhema/phone/net/ClawApi.kt +++ b/android/app/src/main/java/rs/rhema/phone/net/ClawApi.kt @@ -194,6 +194,23 @@ class ClawApi( 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 { + 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 { + val builder = v1("user") ?: return ClawResult.Network("no base URL configured") + return execute(builder.get().build()) { response -> + json.decodeFromString(response.body?.string() ?: "{}") + } + } + private suspend fun rawGet(builder: Request.Builder): ClawResult = withContext(Dispatchers.IO) { try { diff --git a/android/app/src/main/java/rs/rhema/phone/net/Models.kt b/android/app/src/main/java/rs/rhema/phone/net/Models.kt index 4a5ce3f..f223f88 100644 --- a/android/app/src/main/java/rs/rhema/phone/net/Models.kt +++ b/android/app/src/main/java/rs/rhema/phone/net/Models.kt @@ -269,3 +269,12 @@ data class AgentIdentity( val avatar: 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, +) diff --git a/android/app/src/main/java/rs/rhema/phone/ui/ChatScreen.kt b/android/app/src/main/java/rs/rhema/phone/ui/ChatScreen.kt index eafd2dc..03cbe8d 100644 --- a/android/app/src/main/java/rs/rhema/phone/ui/ChatScreen.kt +++ b/android/app/src/main/java/rs/rhema/phone/ui/ChatScreen.kt @@ -82,6 +82,7 @@ import rs.rhema.phone.chat.ChatController import rs.rhema.phone.chat.MAX_IMAGE_BYTES import rs.rhema.phone.chat.MAX_STAGED_IMAGES import rs.rhema.phone.data.AgentIdentityCache +import rs.rhema.phone.data.UserProfileCache import rs.rhema.phone.di.AppContainer import rs.rhema.phone.net.ClawResult import rs.rhema.phone.net.PasteSpan @@ -102,7 +103,13 @@ import android.provider.OpenableColumns @Composable fun ChatScreen(container: AppContainer, sessionKey: String, onBack: () -> Unit) { 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. DisposableEffect(sessionKey) { 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 // turn — the same face the web UI shows. 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()) { ChatHeader(sessionKey, controller.connection, face, onBack) @@ -211,7 +221,7 @@ fun ChatScreen(container: AppContainer, sessionKey: String, onBack: () -> Unit) verticalArrangement = Arrangement.spacedBy(20.dp), ) { 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. if (controller.loadingOlder) { @@ -473,13 +483,20 @@ private fun TurnGroupRow( container: AppContainer, controller: ChatController, face: AgentFace, + userFace: UserFace, ) { // 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 - // matching initial in the round avatar. + // the human's profile name on the conversable keys (their initial and + // 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:") || 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) { 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". 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(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 private fun rememberAgentFace(container: AppContainer): AgentFace { val cache by container.identity.cached.collectAsState(AgentIdentityCache()) diff --git a/android/app/src/main/java/rs/rhema/phone/ui/SessionsScreen.kt b/android/app/src/main/java/rs/rhema/phone/ui/SessionsScreen.kt index 6031d4e..694b6fb 100644 --- a/android/app/src/main/java/rs/rhema/phone/ui/SessionsScreen.kt +++ b/android/app/src/main/java/rs/rhema/phone/ui/SessionsScreen.kt @@ -54,8 +54,10 @@ fun SessionsScreen( loading = true error = null // The agent may have renamed or re-faced itself on another - // surface; this button is the manual path for the cached identity. - container.identity.refresh() + // surface, and so may the human; this button is the manual + // path for both caches. + launch { container.identity.refresh() } + launch { container.userProfile.refresh() } when (val result = container.api.sessions()) { is ClawResult.Ok -> sessions = result.value is ClawResult.HttpError -> error = UiMessage.Http(result.code, result.body)