From 6c63c53bf077f35697c7efd440ba002f2c173ffb Mon Sep 17 00:00:00 2001 From: CjiW Date: Wed, 21 Oct 2026 08:25:16 +0000 Subject: [PATCH 1/8] feat(composer): compact input row and show the context budget The input row was ~72dp tall on its own: Material3's OutlinedTextField pins its decoration box to TextFieldDefaults.MinHeight (56dp), and the icons kept their 48dp touch size. Every pixel there is a pixel the transcript loses. Render the field with BasicTextField plus our own rounded background so the row is ~36dp, and shrink the icon buttons to 36dp with 20dp glyphs. The freed space pays for a context-budget indicator: a 14dp arc plus the percentage, sitting left of the send button and turning amber at 60% and red at 85%, with a tap-through dialog showing prompt tokens, the context cap and the model. The data comes from POST /api/session/status, which the client never called: TokenUsage now carries available/max_context_tokens/usage_percent/model, and ChatReducer.withContextBudget keeps the server's percentage authoritative while hiding the indicator entirely until the server has real token counts (available=false on a fresh session, so no misleading 0%). Progress events only carry prompt_tokens, so withLiveTokenUsage estimates against the cap from the last status call and leaves the value alone when the cap is unknown. --- .../java/dev/xbot/android/chat/ChatModels.kt | 19 ++ .../java/dev/xbot/android/chat/ChatReducer.kt | 56 ++++++ .../dev/xbot/android/chat/ChatViewModel.kt | 23 +++ .../main/java/dev/xbot/android/data/Models.kt | 5 + .../java/dev/xbot/android/data/XbotApi.kt | 15 ++ .../java/dev/xbot/android/ui/ChatScreen.kt | 1 + .../xbot/android/ui/components/Composer.kt | 161 +++++++++++++---- .../ui/components/ContextBudgetIndicator.kt | 168 ++++++++++++++++++ .../dev/xbot/android/chat/ChatReducerTest.kt | 104 +++++++++++ 9 files changed, 516 insertions(+), 36 deletions(-) create mode 100644 app/src/main/java/dev/xbot/android/ui/components/ContextBudgetIndicator.kt diff --git a/app/src/main/java/dev/xbot/android/chat/ChatModels.kt b/app/src/main/java/dev/xbot/android/chat/ChatModels.kt index 5114b94..93076b4 100644 --- a/app/src/main/java/dev/xbot/android/chat/ChatModels.kt +++ b/app/src/main/java/dev/xbot/android/chat/ChatModels.kt @@ -3,6 +3,7 @@ package dev.xbot.android.chat import dev.xbot.android.data.AskUserQuestion import dev.xbot.android.data.QueueItem import dev.xbot.android.data.TodoItem +import kotlin.math.roundToInt data class ToolUi( val key: String, @@ -43,6 +44,22 @@ data class AskUserUi( val questions: List, ) +/** + * 上下文预算:服务端 token 用量在 UI 侧的投影。 + * + * [percent] 已归一化到 0..1;[exact] 为 true 表示来自服务端 `usage_percent`, + * false 表示用 `prompt_tokens / max_context_tokens` 自己估的(回合进行中的实时值)。 + */ +data class ContextBudgetUi( + val promptTokens: Long = 0L, + val maxContextTokens: Long = 0L, + val percent: Float = 0f, + val model: String = "", + val exact: Boolean = false, +) { + val usedPercent: Int get() = (percent * 100f).roundToInt().coerceIn(0, 100) +} + data class ChatUiState( val chatId: String = "", val channel: String = "web", @@ -63,6 +80,8 @@ data class ChatUiState( val loadMoreError: String? = null, val needsReload: Boolean = false, val pendingUserText: String? = null, + /** null = 服务端还没有真实 token 数据(新会话 / 未发起过 LLM 调用)。 */ + val contextBudget: ContextBudgetUi? = null, ) { val isEmpty: Boolean get() = turns.isEmpty() && pendingUserText == null } diff --git a/app/src/main/java/dev/xbot/android/chat/ChatReducer.kt b/app/src/main/java/dev/xbot/android/chat/ChatReducer.kt index d40597f..99d117b 100644 --- a/app/src/main/java/dev/xbot/android/chat/ChatReducer.kt +++ b/app/src/main/java/dev/xbot/android/chat/ChatReducer.kt @@ -5,6 +5,7 @@ import dev.xbot.android.data.HistoryIteration import dev.xbot.android.data.HistoryMessage import dev.xbot.android.data.HistoryResponse import dev.xbot.android.data.ProgressEvent +import dev.xbot.android.data.TokenUsage import dev.xbot.android.data.ToolProgress import dev.xbot.android.data.WsMessage import kotlinx.serialization.decodeFromString @@ -25,6 +26,59 @@ object ChatReducer { fun empty(chatId: String, channel: String, title: String = ""): ChatUiState = ChatUiState(chatId = chatId, channel = channel, title = title, loading = true) + /** + * 应用 `/api/session/status` 返回的 `token_usage`。 + * + * 服务端只在拿到真实 API token 数之后才置 `available`;新会话(还没跑过 LLM) + * 会返回 available=false 且没有 usage_percent —— 这时清掉指示器,而不是画一个 0%。 + */ + fun withContextBudget(state: ChatUiState, usage: TokenUsage?): ChatUiState { + if (usage == null) return state.copy(contextBudget = null) + + val serverPercent = usage.usagePercent?.takeIf { it > 0.0 || usage.available } + val max = usage.maxContextTokens.takeIf { it > 0L } + val hasData = usage.available || serverPercent != null || usage.promptTokens > 0L + if (!hasData) return state.copy(contextBudget = null) + + val percent = when { + serverPercent != null -> (serverPercent / 100.0).toFloat() + max != null && usage.promptTokens > 0L -> usage.promptTokens.toFloat() / max + else -> 0f + } + return state.copy( + contextBudget = ContextBudgetUi( + promptTokens = usage.promptTokens, + maxContextTokens = max ?: 0L, + percent = percent.coerceIn(0f, 1f), + model = usage.model, + exact = serverPercent != null, + ), + ) + } + + /** + * 回合进行中 progress 事件只带 `prompt_tokens`(没有 max_context), + * 用上一次 status 拿到的上限做分母,让指示器随回合推进实时变化。 + * 不知道上限时保持原样——宁可不动,也不要显示一个凭空的百分比。 + */ + private fun ChatUiState.withLiveTokenUsage(usage: TokenUsage): ChatUiState { + val prompt = usage.promptTokens + if (prompt <= 0L) return this + val current = contextBudget + val max = current?.maxContextTokens?.takeIf { it > 0L } + ?: usage.maxContextTokens.takeIf { it > 0L } + ?: return this + return copy( + contextBudget = ContextBudgetUi( + promptTokens = prompt, + maxContextTokens = max, + percent = (prompt.toFloat() / max).coerceIn(0f, 1f), + model = usage.model.ifBlank { current?.model.orEmpty() }, + exact = false, + ), + ) + } + fun withHistory(state: ChatUiState, response: HistoryResponse): ChatUiState { val turns = LinkedHashMap() response.messages.forEach { message -> mergeHistoryMessage(turns, message) } @@ -152,6 +206,8 @@ object ChatReducer { fun applyProgress(state: ChatUiState, progress: ProgressEvent): ChatUiState { var next = state + // 回合进行中的 token 用量先落到预算指示器上,再处理 turn/iteration。 + progress.tokenUsage?.let { usage -> next = next.withLiveTokenUsage(usage) } var turnId = progress.turnId.takeIf { it > 0L } ?: state.liveTurnId progress.turnStart?.let { start -> diff --git a/app/src/main/java/dev/xbot/android/chat/ChatViewModel.kt b/app/src/main/java/dev/xbot/android/chat/ChatViewModel.kt index dfe799a..88e2163 100644 --- a/app/src/main/java/dev/xbot/android/chat/ChatViewModel.kt +++ b/app/src/main/java/dev/xbot/android/chat/ChatViewModel.kt @@ -28,6 +28,7 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) { private var eventsJob: Job? = null private var sseStateJob: Job? = null private var loadJob: Job? = null + private var budgetJob: Job? = null private var chatId = "" private var channel = "web" @@ -64,6 +65,7 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) { } } restorePendingAskUser() + refreshContextBudget() } catch (e: UnauthorizedException) { _state.update { it.copy(loading = false, error = "登录已失效,请重新登录") } } catch (e: Exception) { @@ -74,6 +76,22 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) { } } + /** + * 拉一次 `/api/session/status` 刷新上下文预算。 + * 失败静默:指示器只是辅助信息,不该因为它弹错误条。 + */ + fun refreshContextBudget() { + if (chatId.isBlank()) return + budgetJob?.cancel() + budgetJob = viewModelScope.launch { + runCatching { + withAuthRetry { api.sessionStatus(chatId, channel) } + }.onSuccess { status -> + _state.update { ChatReducer.withContextBudget(it, status.tokenUsage) } + } + } + } + fun loadMore() { val current = _state.value if (!current.hasMore || @@ -190,7 +208,11 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) { sse = client eventsJob = viewModelScope.launch { client.events.collect { message -> + val wasBusy = _state.value.busy _state.update { ChatReducer.applyEvent(it, message) } + // 回合结束(busy 由 true 转 false)时服务端才拿到最终 token 数, + // 这时刷新一次上下文预算,指示器才不会停在回合中途的估值上。 + if (wasBusy && !_state.value.busy) refreshContextBudget() if (_state.value.needsReload) { acknowledgeReload() reload() @@ -235,6 +257,7 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) { } private fun closeStream() { + budgetJob?.cancel() eventsJob?.cancel() sseStateJob?.cancel() eventsJob = null diff --git a/app/src/main/java/dev/xbot/android/data/Models.kt b/app/src/main/java/dev/xbot/android/data/Models.kt index 93f26a0..63471c2 100644 --- a/app/src/main/java/dev/xbot/android/data/Models.kt +++ b/app/src/main/java/dev/xbot/android/data/Models.kt @@ -115,12 +115,17 @@ data class GoalInfo( @Serializable data class TokenUsage( + @SerialName("available") val available: Boolean = false, @SerialName("prompt_tokens") val promptTokens: Long = 0L, @SerialName("completion_tokens") val completionTokens: Long = 0L, @SerialName("total_tokens") val totalTokens: Long = 0L, @SerialName("cache_hit_tokens") val cacheHitTokens: Long = 0L, @SerialName("max_output_tokens") val maxOutputTokens: Long = 0L, + @SerialName("max_context_tokens") val maxContextTokens: Long = 0L, + /** 0..100,null 表示服务端还没有真实 token 数据(尚未发起过 LLM 调用)。 */ + @SerialName("usage_percent") val usagePercent: Double? = null, @SerialName("context_usage_percent") val contextUsagePercent: Double = 0.0, + val model: String = "", ) @Serializable diff --git a/app/src/main/java/dev/xbot/android/data/XbotApi.kt b/app/src/main/java/dev/xbot/android/data/XbotApi.kt index c571ef8..205223f 100644 --- a/app/src/main/java/dev/xbot/android/data/XbotApi.kt +++ b/app/src/main/java/dev/xbot/android/data/XbotApi.kt @@ -257,6 +257,21 @@ class XbotApi(private val prefs: AppPrefs) { }.getOrNull() } + /** + * 轻量会话状态:只返回 token 用量与 cwd。 + * 上下文预算指示器就靠它的 `token_usage.max_context_tokens / usage_percent`。 + */ + suspend fun sessionStatus( + chatId: String, + channel: String = "web", + ): SessionStatusResponse { + val body = buildJsonObject { + put("chat_id", chatId) + put("channel", channel) + }.toString() + return decodeEnvelope(execute(post("/api/session/status", body))) + } + // ------------------------------------------------------------------ // Models & user settings // ------------------------------------------------------------------ diff --git a/app/src/main/java/dev/xbot/android/ui/ChatScreen.kt b/app/src/main/java/dev/xbot/android/ui/ChatScreen.kt index e5f721c..69ac023 100644 --- a/app/src/main/java/dev/xbot/android/ui/ChatScreen.kt +++ b/app/src/main/java/dev/xbot/android/ui/ChatScreen.kt @@ -464,6 +464,7 @@ fun ChatScreen( onSend = { submit() }, onCancel = vm::cancel, sending = sending, + contextBudget = state.contextBudget, ) }, snackbarHost = { SnackbarHost(snackbar) }, diff --git a/app/src/main/java/dev/xbot/android/ui/components/Composer.kt b/app/src/main/java/dev/xbot/android/ui/components/Composer.kt index 148e7c9..25ed7fb 100644 --- a/app/src/main/java/dev/xbot/android/ui/components/Composer.kt +++ b/app/src/main/java/dev/xbot/android/ui/components/Composer.kt @@ -1,16 +1,18 @@ package dev.xbot.android.ui.components +import androidx.compose.foundation.background +import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.BasicTextField import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.Send import androidx.compose.material.icons.filled.Close @@ -20,14 +22,28 @@ import androidx.compose.material3.AssistChip import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.dp +import dev.xbot.android.chat.ContextBudgetUi +/** + * 底部输入区。 + * + * 高度按「一行文字」压缩过:`OutlinedTextField` 自带 56dp 的最小高度(装饰盒内固定), + * 换成了 `BasicTextField` + 自己的圆角背景,行高约 36dp,整条输入区比原来矮 20dp 左右。 + */ @Composable fun Composer( text: String, @@ -39,7 +55,10 @@ fun Composer( onSend: () -> Unit, onCancel: () -> Unit, sending: Boolean = false, + contextBudget: ContextBudgetUi? = null, ) { + var showBudget by remember { mutableStateOf(false) } + Surface( tonalElevation = 3.dp, shadowElevation = 8.dp, @@ -50,7 +69,7 @@ fun Composer( .fillMaxWidth() .imePadding() .navigationBarsPadding() - .padding(horizontal = 10.dp, vertical = 8.dp), + .padding(horizontal = 8.dp, vertical = 6.dp), ) { if (attachmentName != null) { Row( @@ -59,16 +78,22 @@ fun Composer( ) { AssistChip( onClick = {}, - label = { Text(attachmentName, maxLines = 1) }, + label = { + Text( + attachmentName, + style = MaterialTheme.typography.labelMedium, + maxLines = 1, + ) + }, trailingIcon = { IconButton( onClick = onClearAttachment, - modifier = Modifier.size(22.dp), + modifier = Modifier.size(20.dp), ) { Icon( Icons.Filled.Close, contentDescription = "移除附件", - modifier = Modifier.size(15.dp), + modifier = Modifier.size(14.dp), ) } }, @@ -77,44 +102,108 @@ fun Composer( } Row( modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.Bottom, - horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(2.dp), ) { - IconButton(onClick = onPickAttachment) { - Icon(Icons.Outlined.AttachFile, contentDescription = "添加附件") - } - OutlinedTextField( + CompactIconButton( + icon = Icons.Outlined.AttachFile, + description = "添加附件", + onClick = onPickAttachment, + ) + CompactInput( value = text, onValueChange = onTextChange, - minLines = 1, - maxLines = 6, - shape = RoundedCornerShape(20.dp), modifier = Modifier.weight(1f), ) + ContextBudgetIndicator( + budget = contextBudget, + onClick = { showBudget = true }, + ) if (busy) { - IconButton(onClick = onCancel) { - Icon( - Icons.Filled.Stop, - contentDescription = "停止生成", - tint = MaterialTheme.colorScheme.error, - ) - } - } - IconButton( - onClick = onSend, - enabled = text.isNotBlank() && !sending, - ) { - Icon( - Icons.AutoMirrored.Filled.Send, - contentDescription = "发送", - tint = if (text.isNotBlank()) { - MaterialTheme.colorScheme.primary - } else { - MaterialTheme.colorScheme.outline - }, + CompactIconButton( + icon = Icons.Filled.Stop, + description = "停止生成", + tint = MaterialTheme.colorScheme.error, + onClick = onCancel, ) } + CompactIconButton( + icon = Icons.AutoMirrored.Filled.Send, + description = "发送", + enabled = text.isNotBlank() && !sending, + tint = if (text.isNotBlank()) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.outline + }, + onClick = onSend, + ) } } } + + if (showBudget) { + contextBudget?.let { budget -> + ContextBudgetDialog(budget = budget, onDismiss = { showBudget = false }) + } + } +} + +/** 单行起、最多 6 行自增长;最小高度约 36dp(原 `OutlinedTextField` 是 56dp)。 */ +@Composable +private fun CompactInput( + value: String, + onValueChange: (String) -> Unit, + modifier: Modifier = Modifier, +) { + val shape = RoundedCornerShape(18.dp) + Box( + modifier = modifier + .clip(shape) + .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f)) + .border(1.dp, MaterialTheme.colorScheme.outline.copy(alpha = 0.45f), shape) + .padding(horizontal = 12.dp, vertical = 8.dp), + contentAlignment = Alignment.CenterStart, + ) { + if (value.isEmpty()) { + Text( + text = "发消息…", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f), + maxLines = 1, + ) + } + BasicTextField( + value = value, + onValueChange = onValueChange, + textStyle = MaterialTheme.typography.bodyMedium.copy( + color = MaterialTheme.colorScheme.onSurface, + ), + cursorBrush = SolidColor(MaterialTheme.colorScheme.primary), + maxLines = 6, + modifier = Modifier.fillMaxWidth(), + ) + } +} + +@Composable +private fun CompactIconButton( + icon: ImageVector, + description: String, + onClick: () -> Unit, + enabled: Boolean = true, + tint: Color = MaterialTheme.colorScheme.onSurfaceVariant, +) { + IconButton( + onClick = onClick, + enabled = enabled, + modifier = Modifier.size(36.dp), + ) { + Icon( + imageVector = icon, + contentDescription = description, + modifier = Modifier.size(20.dp), + tint = tint, + ) + } } diff --git a/app/src/main/java/dev/xbot/android/ui/components/ContextBudgetIndicator.kt b/app/src/main/java/dev/xbot/android/ui/components/ContextBudgetIndicator.kt new file mode 100644 index 0000000..53c422f --- /dev/null +++ b/app/src/main/java/dev/xbot/android/ui/components/ContextBudgetIndicator.kt @@ -0,0 +1,168 @@ +package dev.xbot.android.ui.components + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import dev.xbot.android.chat.ContextBudgetUi +import java.util.Locale + +/** 上下文占用的告警线:>=60% 变黄,>=85% 变红。 */ +private const val WARN_FRACTION = 0.6f +private const val DANGER_FRACTION = 0.85f + +private val WarnColor = Color(0xFFF59E0B) + +@Composable +fun budgetColor(percent: Float): Color = when { + percent >= DANGER_FRACTION -> MaterialTheme.colorScheme.error + percent >= WARN_FRACTION -> WarnColor + else -> MaterialTheme.colorScheme.primary +} + +/** + * 输入框右侧的上下文预算指示器:一个小圆环 + 百分比,点击看明细。 + * `budget == null`(服务端还没有真实 token 数据)时不占位。 + */ +@Composable +fun ContextBudgetIndicator( + budget: ContextBudgetUi?, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + if (budget == null) return + + val fraction = budget.percent.coerceIn(0f, 1f) + val color = budgetColor(fraction) + val track = MaterialTheme.colorScheme.outline.copy(alpha = 0.45f) + + Row( + modifier = modifier + .clip(RoundedCornerShape(10.dp)) + .clickable(onClick = onClick) + .padding(horizontal = 3.dp, vertical = 4.dp) + .semantics { + contentDescription = "上下文占用 ${budget.usedPercent}%,点按查看明细" + }, + verticalAlignment = Alignment.CenterVertically, + ) { + Canvas(Modifier.size(14.dp)) { + val strokeWidth = 2.dp.toPx() + drawArc( + color = track, + startAngle = 0f, + sweepAngle = 360f, + useCenter = false, + style = Stroke(width = strokeWidth), + ) + if (fraction > 0f) { + drawArc( + color = color, + startAngle = -90f, + sweepAngle = 360f * fraction, + useCenter = false, + style = Stroke(width = strokeWidth, cap = StrokeCap.Round), + ) + } + } + Spacer(Modifier.width(4.dp)) + Text( + text = "${budget.usedPercent}%", + style = MaterialTheme.typography.labelSmall, + fontSize = 10.sp, + color = color, + maxLines = 1, + softWrap = false, + ) + } +} + +/** 点指示器弹出的明细。 */ +@Composable +fun ContextBudgetDialog(budget: ContextBudgetUi, onDismiss: () -> Unit) { + AlertDialog( + onDismissRequest = onDismiss, + confirmButton = { + TextButton(onClick = onDismiss) { Text("知道了") } + }, + title = { Text("上下文预算") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + BudgetRow("已用输入", formatTokens(budget.promptTokens)) + BudgetRow( + "上下文上限", + if (budget.maxContextTokens > 0L) { + formatTokens(budget.maxContextTokens) + } else { + "未知" + }, + ) + BudgetRow( + "当前占用", + if (budget.exact) { + "${budget.usedPercent}%" + } else { + "${budget.usedPercent}%(回合进行中估算)" + }, + ) + if (budget.model.isNotBlank()) { + BudgetRow("模型", budget.model) + } + Text( + "接近上限时服务端会压缩历史,回复可能变慢或丢失早期细节。", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + }, + ) +} + +@Composable +private fun BudgetRow(label: String, value: String) { + Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Text( + text = label, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.width(12.dp)) + Text( + text = value, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.weight(1f, fill = false), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } +} + +private fun formatTokens(value: Long): String = when { + value >= 1_000_000L -> String.format(Locale.US, "%.1fM", value / 1_000_000.0) + value >= 1_000L -> String.format(Locale.US, "%.1fk", value / 1_000.0) + else -> value.toString() +} diff --git a/app/src/test/java/dev/xbot/android/chat/ChatReducerTest.kt b/app/src/test/java/dev/xbot/android/chat/ChatReducerTest.kt index 89f67e9..da3aa11 100644 --- a/app/src/test/java/dev/xbot/android/chat/ChatReducerTest.kt +++ b/app/src/test/java/dev/xbot/android/chat/ChatReducerTest.kt @@ -5,6 +5,7 @@ import dev.xbot.android.data.HistoryMessage import dev.xbot.android.data.HistoryResponse import dev.xbot.android.data.ProgressEvent import dev.xbot.android.data.SessionEvent +import dev.xbot.android.data.TokenUsage import dev.xbot.android.data.WsMessage import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse @@ -354,4 +355,107 @@ class ChatReducerTest { assertFalse(state.busy) } + + // ------------------------------------------------------------------ + // 上下文预算指示器 + // ------------------------------------------------------------------ + + @Test + fun `context budget prefers the server usage percent`() { + val state = ChatReducer.withContextBudget( + ChatReducer.empty("chat_1", "web"), + TokenUsage( + available = true, + promptTokens = 85_000, + maxContextTokens = 200_000, + usagePercent = 42.5, + model = "gpt-4o", + ), + ) + + val budget = state.contextBudget + assertNotNull(budget) + assertEquals(0.425f, budget!!.percent, 0.001f) + assertEquals(43, budget.usedPercent) + assertEquals(200_000L, budget.maxContextTokens) + assertEquals("gpt-4o", budget.model) + assertTrue(budget.exact) + } + + @Test + fun `context budget falls back to prompt over max context`() { + val budget = ChatReducer.withContextBudget( + ChatReducer.empty("chat_1", "web"), + TokenUsage(available = true, promptTokens = 30_000, maxContextTokens = 120_000), + ).contextBudget!! + + assertEquals(0.25f, budget.percent, 0.001f) + assertFalse(budget.exact) + } + + @Test + fun `context budget is hidden until the server has real token data`() { + val state = ChatReducer.withContextBudget( + ChatReducer.empty("chat_1", "web").copy( + contextBudget = ContextBudgetUi(promptTokens = 1, percent = 0.5f), + ), + TokenUsage(available = false, usagePercent = null, promptTokens = 0), + ) + + assertNull(state.contextBudget) + } + + @Test + fun `context budget clamps a percent above one hundred`() { + val budget = ChatReducer.withContextBudget( + ChatReducer.empty("chat_1", "web"), + TokenUsage( + available = true, + promptTokens = 300_000, + maxContextTokens = 200_000, + usagePercent = 150.0, + ), + ).contextBudget!! + + assertEquals(1f, budget.percent, 0.0001f) + assertEquals(100, budget.usedPercent) + } + + @Test + fun `progress token usage updates the budget while the turn runs`() { + val state = ChatReducer.applyProgress( + ChatReducer.empty("chat_1", "web").copy( + contextBudget = ContextBudgetUi( + maxContextTokens = 1_000, + percent = 0.1f, + exact = true, + ), + ), + ProgressEvent( + turnId = 3, + iteration = 1, + phase = "running", + tokenUsage = TokenUsage(promptTokens = 250), + ), + ) + + val budget = state.contextBudget!! + assertEquals(250L, budget.promptTokens) + assertEquals(0.25f, budget.percent, 0.001f) + assertFalse(budget.exact) + } + + @Test + fun `progress token usage without a known context cap leaves the budget alone`() { + val state = ChatReducer.applyProgress( + ChatReducer.empty("chat_1", "web"), + ProgressEvent( + iteration = 1, + phase = "running", + tokenUsage = TokenUsage(promptTokens = 250), + ), + ) + + assertNull(state.contextBudget) + } } From 67acb3e34bdc79ae1918e3e13c67e8824de573a5 Mon Sep 17 00:00:00 2001 From: CjiW Date: Wed, 21 Oct 2026 08:25:20 +0000 Subject: [PATCH 2/8] docs: record the composer/context-budget contract Two traps worth not rediscovering: Material3's OutlinedTextField pins a 56dp minimum inside its decoration box so height has to come from BasicTextField, and the only real context-budget source is /api/session/status (progress events carry prompt tokens but no cap). --- docs/agent/ui-composer.md | 49 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 docs/agent/ui-composer.md diff --git a/docs/agent/ui-composer.md b/docs/agent/ui-composer.md new file mode 100644 index 0000000..5e606fd --- /dev/null +++ b/docs/agent/ui-composer.md @@ -0,0 +1,49 @@ +# 输入区(Composer)与上下文预算指示器 + +`ui/components/Composer.kt` 是底部输入区(Scaffold 的 `bottomBar`); +`ui/components/ContextBudgetIndicator.kt` 是输入框右侧的上下文占用圆环 + 明细弹窗。 + +## 高度为什么用 BasicTextField 而不是 OutlinedTextField + +Material3 的 `OutlinedTextField` / `TextField` 在**装饰盒内部**写死了 `TextFieldDefaults.MinHeight` +(56dp)和 `ContainerHeight`,从外面套 `Modifier.height(40.dp)` 或 `defaultMinSize` 都压不下去, +只会裁切内容。想真正压缩高度必须改用 `BasicTextField` + 自己做背景/边框/占位符: + +- 单行时高度 ≈ `bodyMedium` 行高(20sp)+ 上下 8dp padding ≈ 36dp,比 56dp 省 20dp。 +- 占位符放在 `Box` 里、`BasicTextField` 之前,`value.isEmpty()` 时显示;`Box` 高度取两者的最大值。 +- 圆角/边框用 `clip(RoundedCornerShape(18.dp)) + background(surfaceVariant α0.55) + border(1.dp outline α0.45)`。 +- `maxLines = 6` 保留多行自增长;`cursorBrush = SolidColor(primary)` 否则光标不可见。 + +图标按钮同理由默认 48dp 压到 36dp(`Modifier.size(36.dp)` + `Icon` 20dp),行内 `spacedBy(2.dp)`, +整条输入区(含 `imePadding` / `navigationBarsPadding` 之外的 6dp 内边距)在单行时约 48dp。 + +## 上下文预算的数据来源 + +只有一条真实数据源:`POST /api/session/status`(服务端 `channel/web/web_rest.go: handleSessionStatus`)。 + +``` +{ "token_usage": { "available": bool, "prompt_tokens": n, "completion_tokens": n, + "max_context_tokens": n, "usage_percent": 0..100|null, + "model": "...", "subscription_name": "..." }, + "cwd": "...", "todos": [...] } +``` + +要点: + +- **`available == false` 表示服务端还没拿到真实 API token 数**(新会话、或从没跑过 LLM)。 + 这时不要画 0%,直接不显示指示器(`ChatReducer.withContextBudget` 返回 `contextBudget = null`)。 +- `usage_percent` 是指针,可能是 `null`;`0.0` 且 `available == true` 是合法值(刚清空上下文)。 +- 服务端 `protocol.TokenUsage`(progress 事件里的那个)**没有 max_context**, + 只有 `prompt_tokens / max_output_tokens`。所以回合进行中只能用 + 「上一次 status 拿到的 `max_context_tokens` 做分母」估算 —— + `ChatReducer.withLiveTokenUsage`,拿不到上限就保持原值不动。 +- 刷新时机(`ChatViewModel`):`reload()` 成功之后、SSE 里 `busy` 由 true 转 false 时。 + 失败静默 —— 指示器只是辅助信息,不该因为它弹错误条。 + +## 状态与 UI 的契约 + +- `ContextBudgetUi`(`chat/ChatModels.kt`):`promptTokens / maxContextTokens / percent(0..1) / model / exact`。 + `exact = false` 表示是自己估的,弹窗里会标注「回合进行中估算」。 +- 配色阈值:`< 60%` primary,`60%~85%` 琥珀 `0xFFF59E0B`,`>= 85%` error。 +- 指示器可点:弹出「上下文预算」对话框,显示已用输入 / 上限 / 占用 / 模型。 + 没有数据时(`contextBudget == null`)整个指示器不占位,所以输入区宽度不会跳。 From 14de4cae35951c72707b832eeeeca9319ae443dd Mon Sep 17 00:00:00 2001 From: CjiW Date: Wed, 21 Oct 2026 08:28:33 +0000 Subject: [PATCH 3/8] chore(release): 0.3.4 versionCode 17 is above the 0.3.3 (16) build that is already installed on the test device, so the composer work can be sideloaded and picked up by the in-app updater. The 0.3.4 entry also covers the indicator's data contract: no percentage until the server has real token counts. --- AGENTS.md | 1 + CHANGELOG.md | 11 +++++++++++ version.properties | 4 ++-- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7551206..6f45f64 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -48,6 +48,7 @@ iteration 按序号合并,checkpoint 替换 / delta 追加,收到 turn 结 ## 知识文件 - `docs/agent/ui.md` — Compose 界面约定、TopAppBar 布局陷阱、聊天页结构 +- `docs/agent/ui-composer.md` — 输入区高度(为什么必须 `BasicTextField`)、上下文预算指示器的数据来源与三种口径 ## 约定 diff --git a/CHANGELOG.md b/CHANGELOG.md index 44595b7..1f9eb79 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,17 @@ 写进更新清单的 `changelog` 字段,最终显示在 app 的更新卡片上。小节标题请严格保持 `## [版本号]` 的形式,最新版本放最上面。 +## [0.3.4] + +输入区变矮,并给出上下文预算。 + +### 新增 +- 输入框右侧的上下文预算指示器:小圆环 + 百分比,60% 转黄、85% 转红,点开可看已用输入 / 上下文上限 / 当前占用 / 模型。 +- 数据来自 `/api/session/status`:服务端还没有真实 token 数(新会话)时不显示指示器;回合进行中用上一次的上限估算并标注。 + +### 变更 +- 输入区高度从约 72dp 压到约 48dp:文本框改用 `BasicTextField`(`OutlinedTextField` 在装饰盒内固定 56dp 最小高度,压不下去),图标按钮 48dp → 36dp。 + ## [0.3.3] 自动更新增加**开发版**分发通道,稳定版与开发版各有一份清单。 diff --git a/version.properties b/version.properties index 1badf8e..268b170 100644 --- a/version.properties +++ b/version.properties @@ -1,2 +1,2 @@ -versionCode=16 -versionName=0.3.3 +versionCode=17 +versionName=0.3.4 From 2fcdd4314d19a906aac704f5ac69873988963516 Mon Sep 17 00:00:00 2001 From: CjiW Date: Wed, 21 Oct 2026 08:39:37 +0000 Subject: [PATCH 4/8] ui(composer): show the context budget as text above the input A ring plus a percentage inside the input row cost ~45dp of horizontal space and still made the reader do the division. Print the ratio instead, right-aligned on its own line above the field: 85K/200K. It only exists when the server has real token counts, so an empty session keeps the composer at its compact height. versionCode 18: the 17 build of 0.3.4 is already on the test device, and Android refuses a downgrade. --- CHANGELOG.md | 2 +- .../xbot/android/ui/components/Composer.kt | 9 ++- .../ui/components/ContextBudgetIndicator.kt | 75 ++++++------------- docs/agent/ui-composer.md | 8 +- version.properties | 2 +- 5 files changed, 34 insertions(+), 62 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f9eb79..87e2be7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ 输入区变矮,并给出上下文预算。 ### 新增 -- 输入框右侧的上下文预算指示器:小圆环 + 百分比,60% 转黄、85% 转红,点开可看已用输入 / 上下文上限 / 当前占用 / 模型。 +- 输入框上方新增上下文占用文字(形如 `85K/200K`),60% 转黄、85% 转红,点开可看已用输入 / 上下文上限 / 当前占用 / 模型。 - 数据来自 `/api/session/status`:服务端还没有真实 token 数(新会话)时不显示指示器;回合进行中用上一次的上限估算并标注。 ### 变更 diff --git a/app/src/main/java/dev/xbot/android/ui/components/Composer.kt b/app/src/main/java/dev/xbot/android/ui/components/Composer.kt index 25ed7fb..3f84f1b 100644 --- a/app/src/main/java/dev/xbot/android/ui/components/Composer.kt +++ b/app/src/main/java/dev/xbot/android/ui/components/Composer.kt @@ -100,6 +100,11 @@ fun Composer( ) } } + ContextBudgetLabel( + budget = contextBudget, + onClick = { showBudget = true }, + modifier = Modifier.align(Alignment.End), + ) Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, @@ -115,10 +120,6 @@ fun Composer( onValueChange = onTextChange, modifier = Modifier.weight(1f), ) - ContextBudgetIndicator( - budget = contextBudget, - onClick = { showBudget = true }, - ) if (busy) { CompactIconButton( icon = Icons.Filled.Stop, diff --git a/app/src/main/java/dev/xbot/android/ui/components/ContextBudgetIndicator.kt b/app/src/main/java/dev/xbot/android/ui/components/ContextBudgetIndicator.kt index 53c422f..65bb737 100644 --- a/app/src/main/java/dev/xbot/android/ui/components/ContextBudgetIndicator.kt +++ b/app/src/main/java/dev/xbot/android/ui/components/ContextBudgetIndicator.kt @@ -1,14 +1,12 @@ package dev.xbot.android.ui.components -import androidx.compose.foundation.Canvas import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AlertDialog @@ -20,8 +18,6 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.StrokeCap -import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextOverflow @@ -37,70 +33,42 @@ private const val DANGER_FRACTION = 0.85f private val WarnColor = Color(0xFFF59E0B) @Composable -fun budgetColor(percent: Float): Color = when { +private fun budgetColor(percent: Float): Color = when { percent >= DANGER_FRACTION -> MaterialTheme.colorScheme.error percent >= WARN_FRACTION -> WarnColor - else -> MaterialTheme.colorScheme.primary + else -> MaterialTheme.colorScheme.onSurfaceVariant } /** - * 输入框右侧的上下文预算指示器:一个小圆环 + 百分比,点击看明细。 - * `budget == null`(服务端还没有真实 token 数据)时不占位。 + * 输入框上方的上下文占用文字,形如 `85K/200K`(已用输入 / 上下文上限)。 + * `budget == null`(服务端还没有真实 token 数据)时不占位 —— 连那一行高度也不留。 */ @Composable -fun ContextBudgetIndicator( +fun ContextBudgetLabel( budget: ContextBudgetUi?, onClick: () -> Unit, modifier: Modifier = Modifier, ) { if (budget == null) return - val fraction = budget.percent.coerceIn(0f, 1f) - val color = budgetColor(fraction) - val track = MaterialTheme.colorScheme.outline.copy(alpha = 0.45f) - - Row( + val used = formatTokens(budget.promptTokens) + val cap = if (budget.maxContextTokens > 0L) formatTokens(budget.maxContextTokens) else "—" + Text( + text = "$used/$cap", + style = MaterialTheme.typography.labelSmall, + fontSize = 10.sp, + color = budgetColor(budget.percent.coerceIn(0f, 1f)), + maxLines = 1, + softWrap = false, modifier = modifier - .clip(RoundedCornerShape(10.dp)) + .clip(RoundedCornerShape(4.dp)) .clickable(onClick = onClick) - .padding(horizontal = 3.dp, vertical = 4.dp) - .semantics { - contentDescription = "上下文占用 ${budget.usedPercent}%,点按查看明细" - }, - verticalAlignment = Alignment.CenterVertically, - ) { - Canvas(Modifier.size(14.dp)) { - val strokeWidth = 2.dp.toPx() - drawArc( - color = track, - startAngle = 0f, - sweepAngle = 360f, - useCenter = false, - style = Stroke(width = strokeWidth), - ) - if (fraction > 0f) { - drawArc( - color = color, - startAngle = -90f, - sweepAngle = 360f * fraction, - useCenter = false, - style = Stroke(width = strokeWidth, cap = StrokeCap.Round), - ) - } - } - Spacer(Modifier.width(4.dp)) - Text( - text = "${budget.usedPercent}%", - style = MaterialTheme.typography.labelSmall, - fontSize = 10.sp, - color = color, - maxLines = 1, - softWrap = false, - ) - } + .padding(horizontal = 2.dp, vertical = 1.dp) + .semantics { contentDescription = "上下文占用 $used / $cap,点按查看明细" }, + ) } -/** 点指示器弹出的明细。 */ +/** 点文字弹出的明细。 */ @Composable fun ContextBudgetDialog(budget: ContextBudgetUi, onDismiss: () -> Unit) { AlertDialog( @@ -161,8 +129,9 @@ private fun BudgetRow(label: String, value: String) { } } +/** 12345 -> `12.3k`,1250000 -> `1.3M`。 */ private fun formatTokens(value: Long): String = when { value >= 1_000_000L -> String.format(Locale.US, "%.1fM", value / 1_000_000.0) - value >= 1_000L -> String.format(Locale.US, "%.1fk", value / 1_000.0) + value >= 1_000L -> String.format(Locale.US, "%.1fK", value / 1_000.0) else -> value.toString() } diff --git a/docs/agent/ui-composer.md b/docs/agent/ui-composer.md index 5e606fd..de6743d 100644 --- a/docs/agent/ui-composer.md +++ b/docs/agent/ui-composer.md @@ -1,7 +1,7 @@ # 输入区(Composer)与上下文预算指示器 `ui/components/Composer.kt` 是底部输入区(Scaffold 的 `bottomBar`); -`ui/components/ContextBudgetIndicator.kt` 是输入框右侧的上下文占用圆环 + 明细弹窗。 +`ui/components/ContextBudgetIndicator.kt` 是输入框**上方**那行上下文占用文字(`85K/200K`)+ 明细弹窗。 ## 高度为什么用 BasicTextField 而不是 OutlinedTextField @@ -45,5 +45,7 @@ Material3 的 `OutlinedTextField` / `TextField` 在**装饰盒内部**写死了 - `ContextBudgetUi`(`chat/ChatModels.kt`):`promptTokens / maxContextTokens / percent(0..1) / model / exact`。 `exact = false` 表示是自己估的,弹窗里会标注「回合进行中估算」。 - 配色阈值:`< 60%` primary,`60%~85%` 琥珀 `0xFFF59E0B`,`>= 85%` error。 -- 指示器可点:弹出「上下文预算」对话框,显示已用输入 / 上限 / 占用 / 模型。 - 没有数据时(`contextBudget == null`)整个指示器不占位,所以输入区宽度不会跳。 +- 显示形式:输入框上方右对齐的一行小字 `已用输入/上下文上限`(如 `85K/200K`), + 按 `formatTokens` 压缩成 K/M;上限未知时右半显示 `—`。 +- 文字可点:弹出「上下文预算」对话框,显示已用输入 / 上限 / 占用 / 模型。 + 没有数据时(`contextBudget == null`)**整行都不存在**,输入区高度与宽度都不会跳。 diff --git a/version.properties b/version.properties index 268b170..5f6878b 100644 --- a/version.properties +++ b/version.properties @@ -1,2 +1,2 @@ -versionCode=17 +versionCode=18 versionName=0.3.4 From a8923f70cfad4478c55464fd3d433d3f486be95d Mon Sep 17 00:00:00 2001 From: CjiW Date: Wed, 21 Oct 2026 08:51:59 +0000 Subject: [PATCH 5/8] ui(composer): centre the context budget label Right-aligning it put the number in the corner furthest from the text being typed; centred it reads as a caption for the whole input row. versionCode 19: 18 is already on the test device. --- app/src/main/java/dev/xbot/android/ui/components/Composer.kt | 2 +- version.properties | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/dev/xbot/android/ui/components/Composer.kt b/app/src/main/java/dev/xbot/android/ui/components/Composer.kt index 3f84f1b..3ea5119 100644 --- a/app/src/main/java/dev/xbot/android/ui/components/Composer.kt +++ b/app/src/main/java/dev/xbot/android/ui/components/Composer.kt @@ -103,7 +103,7 @@ fun Composer( ContextBudgetLabel( budget = contextBudget, onClick = { showBudget = true }, - modifier = Modifier.align(Alignment.End), + modifier = Modifier.align(Alignment.CenterHorizontally), ) Row( modifier = Modifier.fillMaxWidth(), diff --git a/version.properties b/version.properties index 5f6878b..61411ce 100644 --- a/version.properties +++ b/version.properties @@ -1,2 +1,2 @@ -versionCode=18 +versionCode=19 versionName=0.3.4 From c10e392ed29151baacf8138e03d771b03806aaf5 Mon Sep 17 00:00:00 2001 From: CjiW Date: Wed, 21 Oct 2026 10:34:05 +0000 Subject: [PATCH 6/8] feat(sessions): show the working directory of each chat The server already sends work_dir on every chat and cwd in session status, but neither reached the UI, so two chats on the same server looked identical until you opened them. Session rows put the path on the time line (weight 1f + ellipsis, so the card never grows); the chat screen prints it next to the context budget above the composer. Both use PathText, which keeps the tail of the path installed of the head: right-truncation would cut the leaf directory that actually identifies the workspace. ChatUiState.cwd is fed from session status (blank keeps the previous value) and from progress events, which can carry a new cwd mid-turn. versionCode 20. --- CHANGELOG.md | 1 + .../java/dev/xbot/android/chat/ChatModels.kt | 2 + .../java/dev/xbot/android/chat/ChatReducer.kt | 13 +++- .../dev/xbot/android/chat/ChatViewModel.kt | 2 +- .../xbot/android/sessions/SessionsScreen.kt | 18 ++++-- .../java/dev/xbot/android/ui/ChatScreen.kt | 1 + .../xbot/android/ui/components/Composer.kt | 33 ++++++++-- .../xbot/android/ui/components/PathText.kt | 64 +++++++++++++++++++ .../dev/xbot/android/chat/ChatReducerTest.kt | 40 ++++++++++++ docs/agent/ui-composer.md | 12 ++++ version.properties | 2 +- 11 files changed, 175 insertions(+), 13 deletions(-) create mode 100644 app/src/main/java/dev/xbot/android/ui/components/PathText.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 87e2be7..ffab639 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ ### 新增 - 输入框上方新增上下文占用文字(形如 `85K/200K`),60% 转黄、85% 转红,点开可看已用输入 / 上下文上限 / 当前占用 / 模型。 +- 会话项显示工作目录(`work_dir`,路径按段左截断保留尾部);聊天页把它显示在输入框上方那行上下文占用的旁边。 - 数据来自 `/api/session/status`:服务端还没有真实 token 数(新会话)时不显示指示器;回合进行中用上一次的上限估算并标注。 ### 变更 diff --git a/app/src/main/java/dev/xbot/android/chat/ChatModels.kt b/app/src/main/java/dev/xbot/android/chat/ChatModels.kt index 93076b4..62953ee 100644 --- a/app/src/main/java/dev/xbot/android/chat/ChatModels.kt +++ b/app/src/main/java/dev/xbot/android/chat/ChatModels.kt @@ -64,6 +64,8 @@ data class ChatUiState( val chatId: String = "", val channel: String = "web", val title: String = "", + /** 该会话的工作目录(服务端 work_dir / session status 的 cwd)。 */ + val cwd: String = "", val loading: Boolean = false, val error: String? = null, val connected: Boolean = false, diff --git a/app/src/main/java/dev/xbot/android/chat/ChatReducer.kt b/app/src/main/java/dev/xbot/android/chat/ChatReducer.kt index 99d117b..0c196f9 100644 --- a/app/src/main/java/dev/xbot/android/chat/ChatReducer.kt +++ b/app/src/main/java/dev/xbot/android/chat/ChatReducer.kt @@ -5,6 +5,7 @@ import dev.xbot.android.data.HistoryIteration import dev.xbot.android.data.HistoryMessage import dev.xbot.android.data.HistoryResponse import dev.xbot.android.data.ProgressEvent +import dev.xbot.android.data.SessionStatusResponse import dev.xbot.android.data.TokenUsage import dev.xbot.android.data.ToolProgress import dev.xbot.android.data.WsMessage @@ -26,6 +27,15 @@ object ChatReducer { fun empty(chatId: String, channel: String, title: String = ""): ChatUiState = ChatUiState(chatId = chatId, channel = channel, title = title, loading = true) + /** + * 应用 `/api/session/status`:工作目录 + 上下文预算一次带回来。 + * cwd 为空时保留原值(老服务端可能不返回)。 + */ + fun withSessionStatus(state: ChatUiState, status: SessionStatusResponse): ChatUiState { + val next = if (status.cwd.isNotBlank()) state.copy(cwd = status.cwd) else state + return withContextBudget(next, status.tokenUsage) + } + /** * 应用 `/api/session/status` 返回的 `token_usage`。 * @@ -206,8 +216,9 @@ object ChatReducer { fun applyProgress(state: ChatUiState, progress: ProgressEvent): ChatUiState { var next = state - // 回合进行中的 token 用量先落到预算指示器上,再处理 turn/iteration。 + // 回合进行中的 token 用量 / cwd 先落到界面上,再处理 turn/iteration。 progress.tokenUsage?.let { usage -> next = next.withLiveTokenUsage(usage) } + if (progress.cwd.isNotBlank()) next = next.copy(cwd = progress.cwd) var turnId = progress.turnId.takeIf { it > 0L } ?: state.liveTurnId progress.turnStart?.let { start -> diff --git a/app/src/main/java/dev/xbot/android/chat/ChatViewModel.kt b/app/src/main/java/dev/xbot/android/chat/ChatViewModel.kt index 88e2163..df7a17f 100644 --- a/app/src/main/java/dev/xbot/android/chat/ChatViewModel.kt +++ b/app/src/main/java/dev/xbot/android/chat/ChatViewModel.kt @@ -87,7 +87,7 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) { runCatching { withAuthRetry { api.sessionStatus(chatId, channel) } }.onSuccess { status -> - _state.update { ChatReducer.withContextBudget(it, status.tokenUsage) } + _state.update { ChatReducer.withSessionStatus(it, status) } } } } diff --git a/app/src/main/java/dev/xbot/android/sessions/SessionsScreen.kt b/app/src/main/java/dev/xbot/android/sessions/SessionsScreen.kt index 42ea726..db93da9 100644 --- a/app/src/main/java/dev/xbot/android/sessions/SessionsScreen.kt +++ b/app/src/main/java/dev/xbot/android/sessions/SessionsScreen.kt @@ -56,6 +56,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.repeatOnLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import dev.xbot.android.data.UserChat +import dev.xbot.android.ui.components.PathText import dev.xbot.android.update.UpdateViewModel import java.time.Instant @@ -505,11 +506,18 @@ private fun SessionRow( overflow = TextOverflow.Ellipsis, ) } - Text( - relativeTime(chat.lastActive), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) + Row(verticalAlignment = Alignment.CenterVertically) { + PathText( + path = chat.workDir, + modifier = Modifier.weight(1f, fill = false), + ) + if (chat.workDir.isNotBlank()) Spacer(Modifier.width(8.dp)) + Text( + relativeTime(chat.lastActive), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } } Box { IconButton(onClick = { menu = true }) { diff --git a/app/src/main/java/dev/xbot/android/ui/ChatScreen.kt b/app/src/main/java/dev/xbot/android/ui/ChatScreen.kt index 69ac023..cb87f4e 100644 --- a/app/src/main/java/dev/xbot/android/ui/ChatScreen.kt +++ b/app/src/main/java/dev/xbot/android/ui/ChatScreen.kt @@ -465,6 +465,7 @@ fun ChatScreen( onCancel = vm::cancel, sending = sending, contextBudget = state.contextBudget, + cwd = state.cwd, ) }, snackbarHost = { SnackbarHost(snackbar) }, diff --git a/app/src/main/java/dev/xbot/android/ui/components/Composer.kt b/app/src/main/java/dev/xbot/android/ui/components/Composer.kt index 3ea5119..fcf9814 100644 --- a/app/src/main/java/dev/xbot/android/ui/components/Composer.kt +++ b/app/src/main/java/dev/xbot/android/ui/components/Composer.kt @@ -11,6 +11,7 @@ import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.material.icons.Icons @@ -56,6 +57,7 @@ fun Composer( onCancel: () -> Unit, sending: Boolean = false, contextBudget: ContextBudgetUi? = null, + cwd: String = "", ) { var showBudget by remember { mutableStateOf(false) } @@ -100,11 +102,32 @@ fun Composer( ) } } - ContextBudgetLabel( - budget = contextBudget, - onClick = { showBudget = true }, - modifier = Modifier.align(Alignment.CenterHorizontally), - ) + // 工作目录与上下文占用同处一行、整体居中:两者都没有时这一行不存在。 + if (cwd.isNotBlank() || contextBudget != null) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.Center, + verticalAlignment = Alignment.CenterVertically, + ) { + PathText( + path = cwd, + modifier = Modifier.widthIn(max = 150.dp), + ) + if (cwd.isNotBlank() && contextBudget != null) { + Text( + text = " · ", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + softWrap = false, + ) + } + ContextBudgetLabel( + budget = contextBudget, + onClick = { showBudget = true }, + ) + } + } Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, diff --git a/app/src/main/java/dev/xbot/android/ui/components/PathText.kt b/app/src/main/java/dev/xbot/android/ui/components/PathText.kt new file mode 100644 index 0000000..e5c09c3 --- /dev/null +++ b/app/src/main/java/dev/xbot/android/ui/components/PathText.kt @@ -0,0 +1,64 @@ +package dev.xbot.android.ui.components + +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Folder +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp + +/** `/home/cjw/xbot-android` / `/Users/x/…` 之外的常见前缀,换成 `~/`。 */ +private val HOME_PREFIX = Regex("^/(?:home|Users|root)/?[^/]*/") + +/** + * 路径尾巴最重要,所以按段左截断:`/home/cjw/xbot-android/app` → `…/xbot-android/app`。 + * 段数不多、或本来就以 `~` 开头时原样返回(去掉尾部斜杠)。 + */ +fun shortenPath(raw: String, keepSegments: Int = 2): String { + val path = raw.trim() + if (path.isEmpty()) return "" + val expanded = HOME_PREFIX.replace(path, "~/") + val segments = expanded.trimEnd('/').split('/').filter { it.isNotEmpty() } + if (segments.size <= keepSegments + 1) return expanded.trimEnd('/') + return "…/" + segments.takeLast(keepSegments).joinToString("/") +} + +/** 工作目录:小文件夹图标 + 截断后的路径。路径为空时整体不占位。 */ +@Composable +fun PathText( + path: String, + modifier: Modifier = Modifier, + color: Color = MaterialTheme.colorScheme.onSurfaceVariant, + style: TextStyle = MaterialTheme.typography.labelSmall, +) { + if (path.isBlank()) return + + Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) { + Icon( + imageVector = Icons.Outlined.Folder, + contentDescription = null, + modifier = Modifier.size(11.dp), + tint = color, + ) + Spacer(Modifier.width(3.dp)) + Text( + text = shortenPath(path), + style = style, + color = color, + maxLines = 1, + softWrap = false, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f, fill = false), + ) + } +} diff --git a/app/src/test/java/dev/xbot/android/chat/ChatReducerTest.kt b/app/src/test/java/dev/xbot/android/chat/ChatReducerTest.kt index da3aa11..30eb6d0 100644 --- a/app/src/test/java/dev/xbot/android/chat/ChatReducerTest.kt +++ b/app/src/test/java/dev/xbot/android/chat/ChatReducerTest.kt @@ -5,6 +5,7 @@ import dev.xbot.android.data.HistoryMessage import dev.xbot.android.data.HistoryResponse import dev.xbot.android.data.ProgressEvent import dev.xbot.android.data.SessionEvent +import dev.xbot.android.data.SessionStatusResponse import dev.xbot.android.data.TokenUsage import dev.xbot.android.data.WsMessage import org.junit.Assert.assertEquals @@ -458,4 +459,43 @@ class ChatReducerTest { assertNull(state.contextBudget) } + + @Test + fun `session status stores the working directory and the budget`() { + val state = ChatReducer.withSessionStatus( + ChatReducer.empty("chat_1", "web"), + SessionStatusResponse( + cwd = "/home/cjw/xbot-android", + tokenUsage = TokenUsage( + available = true, + promptTokens = 20_000, + maxContextTokens = 200_000, + ), + ), + ) + + assertEquals("/home/cjw/xbot-android", state.cwd) + assertEquals(0.1f, state.contextBudget!!.percent, 0.001f) + } + + @Test + fun `blank cwd from the server keeps the previous working directory`() { + val state = ChatReducer.withSessionStatus( + ChatReducer.empty("chat_1", "web").copy(cwd = "/keep/me"), + SessionStatusResponse(cwd = "", tokenUsage = null), + ) + + assertEquals("/keep/me", state.cwd) + assertNull(state.contextBudget) + } + + @Test + fun `progress carries the working directory`() { + val state = ChatReducer.applyProgress( + ChatReducer.empty("chat_1", "web"), + ProgressEvent(turnId = 1, iteration = 1, phase = "running", cwd = "/tmp/work"), + ) + + assertEquals("/tmp/work", state.cwd) + } } diff --git a/docs/agent/ui-composer.md b/docs/agent/ui-composer.md index de6743d..4b11b93 100644 --- a/docs/agent/ui-composer.md +++ b/docs/agent/ui-composer.md @@ -49,3 +49,15 @@ Material3 的 `OutlinedTextField` / `TextField` 在**装饰盒内部**写死了 按 `formatTokens` 压缩成 K/M;上限未知时右半显示 `—`。 - 文字可点:弹出「上下文预算」对话框,显示已用输入 / 上限 / 占用 / 模型。 没有数据时(`contextBudget == null`)**整行都不存在**,输入区高度与宽度都不会跳。 + +## 工作目录(cwd)从哪来、显示在哪 + +- **会话列表**:直接用聊天列表项里的 `UserChat.workDir`(服务端 `work_dir`,`omitempty`,可能为空), + 显示在会话项的时间行左侧,`Modifier.weight(1f, fill = false)` + 省略号,路径不换行、不撑高卡片。 +- **聊天页**:`ChatUiState.cwd`,与上下文占用同一行、整体居中。 + - 来源一:`/api/session/status` 的 `cwd`(`ChatReducer.withSessionStatus`,空值保留旧值); + - 来源二:progress 事件里的 `cwd`(回合进行中可能变,`applyProgress` 直接覆盖)。 +- 两处都用 `ui/components/PathText.kt`:`Icons.Outlined.Folder` 11dp + `shortenPath()`。 + `shortenPath` 把 `^/(home|Users|root)//` 换成 `~/`,段数超过 `keepSegments + 1` 时只留最后两段 + 并加 `…/` 前缀 —— 路径尾巴比开头有用,右截断(Compose 的默认 Ellipsis)会把最关键的目录名切掉。 + diff --git a/version.properties b/version.properties index 61411ce..af158b9 100644 --- a/version.properties +++ b/version.properties @@ -1,2 +1,2 @@ -versionCode=19 +versionCode=20 versionName=0.3.4 From 6a6c7a866d86849a295ad73a164b8249d0cb237c Mon Sep 17 00:00:00 2001 From: CjiW Date: Wed, 21 Oct 2026 10:44:34 +0000 Subject: [PATCH 7/8] fix(rewind): decode history_rewound/files_rewound as booleans MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The server's protocol.HistoryRewindResult declares both flags as bool, but RewindResponse typed them as Int. kotlinx.serialization therefore threw "Unexpected symbol 't' in numeric literal at path: $.data.files_rewound" on a rewind that had already succeeded server-side -- the user saw a JSON parse error and no rewind dialog feedback at all. Type them as Boolean and report the two outcomes separately: history not truncated is a real failure, while files_rewound=false with a non-blank checkpoint_error means the history moved but the file snapshot did not. The full "已回退" message used to hide that difference. Adds RewindResponseTest with the exact payload captured on device, plus a failed-rewind case. A sweep of every bool json tag in protocol/ against the client models found no other bool-as-Int mismatches. versionCode 21. --- AGENTS.md | 2 + CHANGELOG.md | 4 ++ .../dev/xbot/android/data/SessionActions.kt | 7 ++- .../java/dev/xbot/android/ui/ChatScreen.kt | 23 ++++++++- .../xbot/android/data/RewindResponseTest.kt | 49 +++++++++++++++++++ version.properties | 2 +- 6 files changed, 83 insertions(+), 4 deletions(-) create mode 100644 app/src/test/java/dev/xbot/android/data/RewindResponseTest.kt diff --git a/AGENTS.md b/AGENTS.md index 6f45f64..8295e22 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,6 +40,8 @@ iteration 按序号合并,checkpoint 替换 / delta 追加,收到 turn 结 往 `actions` 里塞长文本会把标题挤成单字。详见 `docs/agent/ui.md`。 - **发版 APK 用 `keystore/xbot-release.jks` 签名**;同 versionCode 可覆盖安装,降级会被 Android 拒绝, 所以更新清单里的 `versionCode` 必须**大于**已安装版本,否则 app 内检查更新不会提示。 +- **REST/RPC 响应字段类型必须和服务端 `protocol` 结构体对齐**:把 `bool` 写成 `Int` 会在反序列化阶段抛 + `Unexpected symbol 't' in numeric literal`,而这时服务端其实已经执行成功了(Rewind 就栽在这上面)。 - **`release.yml` 会把 `CHANGELOG.md` 全文当作更新说明**(文件不存在时退化成 `Release x.y.z`); 该文件按版本分段维护,改动时保持 `## [x.y.z]` 小节标题格式。 - **MinIO 用 `xbotlan` 别名**(`127.0.0.1:9000`)写 `uploads/share/android/`,公网前缀是 diff --git a/CHANGELOG.md b/CHANGELOG.md index ffab639..a2d0fb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,10 @@ - 会话项显示工作目录(`work_dir`,路径按段左截断保留尾部);聊天页把它显示在输入框上方那行上下文占用的旁边。 - 数据来自 `/api/session/status`:服务端还没有真实 token 数(新会话)时不显示指示器;回合进行中用上一次的上限估算并标注。 +### 修复 +- Rewind(回退)在服务端其实已成功,客户端却报 `Unexpected symbol 't' in numeric literal at path: $.data.files_rewound`:`history_rewound` / `files_rewound` 是布尔值,模型误声明成整数。 +- 回退结果文案区分「历史已截断」与「文件快照是否恢复」,文件没恢复时不再被一句「已回退」掩盖。 + ### 变更 - 输入区高度从约 72dp 压到约 48dp:文本框改用 `BasicTextField`(`OutlinedTextField` 在装饰盒内固定 56dp 最小高度,压不下去),图标按钮 48dp → 36dp。 diff --git a/app/src/main/java/dev/xbot/android/data/SessionActions.kt b/app/src/main/java/dev/xbot/android/data/SessionActions.kt index c59709d..c831d7d 100644 --- a/app/src/main/java/dev/xbot/android/data/SessionActions.kt +++ b/app/src/main/java/dev/xbot/android/data/SessionActions.kt @@ -14,7 +14,10 @@ data class RewindResponse( val ok: Boolean = false, @SerialName("target_history_id") val targetHistoryId: Long = 0L, val draft: String = "", - @SerialName("history_rewound") val historyRewound: Int = 0, - @SerialName("files_rewound") val filesRewound: Int = 0, + // 服务端 protocol.HistoryRewindResult 里这两个字段都是 bool。 + // 曾误声明为 Int,导致回退成功、响应却在解析阶段抛 + // "Unexpected symbol 't' in numeric literal at path: $.data.files_rewound"。 + @SerialName("history_rewound") val historyRewound: Boolean = false, + @SerialName("files_rewound") val filesRewound: Boolean = false, @SerialName("checkpoint_error") val checkpointError: String = "", ) diff --git a/app/src/main/java/dev/xbot/android/ui/ChatScreen.kt b/app/src/main/java/dev/xbot/android/ui/ChatScreen.kt index cb87f4e..c5bf06e 100644 --- a/app/src/main/java/dev/xbot/android/ui/ChatScreen.kt +++ b/app/src/main/java/dev/xbot/android/ui/ChatScreen.kt @@ -76,6 +76,7 @@ import dev.xbot.android.chat.ChatViewModel import dev.xbot.android.chat.IterationUi import dev.xbot.android.chat.TurnUi import dev.xbot.android.data.ModelEntry +import dev.xbot.android.data.RewindResponse import dev.xbot.android.data.SessionModel import dev.xbot.android.ui.components.AskUserDialog import dev.xbot.android.ui.components.AutoLinkText @@ -653,7 +654,7 @@ fun ChatScreen( }.onSuccess { response -> if (response.draft.isNotBlank()) input = response.draft vm.reload() - snackbar.showSnackbar("已回退,原消息已放回输入框") + snackbar.showSnackbar(rewindMessage(response)) }.onFailure { snackbar.showSnackbar(it.message ?: "回退失败") } @@ -826,3 +827,23 @@ private fun ThinkingRow() { ) } } + +/** + * 回退结果文案。历史与文件快照是两件独立的事: + * `history_rewound` 为 false 表示历史没截断(回退实际没生效), + * `files_rewound` 为 false 但 `checkpoint_error` 非空表示历史回退了、文件没恢复。 + * 这两件事都不能用一句"已回退"盖掉。 + */ +private fun rewindMessage(response: RewindResponse): String { + if (!response.historyRewound) { + val reason = response.checkpointError.ifBlank { "服务端未截断历史" } + return "回退未生效:$reason" + } + val draftNote = if (response.draft.isNotBlank()) ",原消息已放回输入框" else "" + return when { + response.filesRewound -> "已回退,文件改动已一并恢复$draftNote" + response.checkpointError.isNotBlank() -> + "已回退$draftNote(文件未回退:${response.checkpointError})" + else -> "已回退$draftNote" + } +} diff --git a/app/src/test/java/dev/xbot/android/data/RewindResponseTest.kt b/app/src/test/java/dev/xbot/android/data/RewindResponseTest.kt new file mode 100644 index 0000000..e0f80ca --- /dev/null +++ b/app/src/test/java/dev/xbot/android/data/RewindResponseTest.kt @@ -0,0 +1,49 @@ +package dev.xbot.android.data + +import kotlinx.serialization.decodeFromString +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * 回归测试:`/api/history/rewind` 的响应里 `history_rewound` / `files_rewound` 是 **bool** + * (服务端 `protocol.HistoryRewindResult`),客户端曾把两者声明成 `Int`, + * 导致回退其实成功了、却在解析阶段炸: + * `Unexpected symbol 't' in numeric literal at path: $.data.files_rewound`。 + */ +class RewindResponseTest { + + // 真机上抓到的原始响应(少数字段省略)。 + private val payload = """ + {"ok":true,"data":{"checkpoint_error":"","draft":"合并了,你打 Tag 测试一下。 ", + "files_rewound":true,"history_rewound":true,"rewind_result":null,"target_history_id":37157}, + "error":null} + """.trimIndent() + + @Test + fun `boolean rewind flags decode from the server payload`() { + val envelope = XbotJson.decodeFromString>(payload) + + val data = envelope.data + assertTrue(envelope.ok) + assertTrue(data!!.historyRewound) + assertTrue(data.filesRewound) + assertEquals(37157L, data.targetHistoryId) + assertEquals("合并了,你打 Tag 测试一下。 ", data.draft) + assertEquals("", data.checkpointError) + } + + @Test + fun `failed rewind decodes to false flags instead of throwing`() { + val envelope = XbotJson.decodeFromString>( + """{"ok":true,"data":{"history_rewound":false,"files_rewound":false, + "checkpoint_error":"checkpoint unavailable","target_history_id":7},"error":null}""", + ) + + val data = envelope.data!! + assertFalse(data.historyRewound) + assertFalse(data.filesRewound) + assertEquals("checkpoint unavailable", data.checkpointError) + } +} diff --git a/version.properties b/version.properties index af158b9..f134a60 100644 --- a/version.properties +++ b/version.properties @@ -1,2 +1,2 @@ -versionCode=20 +versionCode=21 versionName=0.3.4 From 44bea69dfd0be1eb00bc01916b00ed3411f8f648 Mon Sep 17 00:00:00 2001 From: CjiW Date: Wed, 21 Oct 2026 11:41:03 +0000 Subject: [PATCH 8/8] fix(rewind): drop rewound turns immediately reload() merged the newest page into the existing turns whenever the chat already had history, and mergeLatestHistory only ever adds: turns the server no longer returns survive. After a rewind the truncated messages therefore stayed on screen until the chat was reopened, because open() resets the state and takes the replacing path. Add reload(replaceTurns): the rewind success handler and the server's history_rewound session event now ask for a replacing reload, while ordinary reloads (reconnect, resync) keep merging so pages loaded by scrolling up are preserved. The flag travels through ChatUiState.reloadReplacesHistory because needsReload alone is also used by resync_required, which must merge. Tests pin both behaviours: withHistory drops the removed turn, mergeLatestHistory keeps it (the old bug), and the session event sets both flags. versionCode 22, plus docs/agent/chat.md on the two history paths. --- AGENTS.md | 1 + CHANGELOG.md | 1 + .../java/dev/xbot/android/chat/ChatModels.kt | 2 + .../java/dev/xbot/android/chat/ChatReducer.kt | 8 +++ .../dev/xbot/android/chat/ChatViewModel.kt | 18 +++-- .../java/dev/xbot/android/ui/ChatScreen.kt | 3 +- .../dev/xbot/android/chat/ChatReducerTest.kt | 67 +++++++++++++++++++ docs/agent/chat.md | 45 +++++++++++++ version.properties | 2 +- 9 files changed, 141 insertions(+), 6 deletions(-) create mode 100644 docs/agent/chat.md diff --git a/AGENTS.md b/AGENTS.md index 8295e22..075063c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,6 +49,7 @@ iteration 按序号合并,checkpoint 替换 / delta 追加,收到 turn 结 ## 知识文件 +- `docs/agent/chat.md` — 历史装载的两条路径(替换 vs 合并)、Rewind 后为什么必须整体重载 - `docs/agent/ui.md` — Compose 界面约定、TopAppBar 布局陷阱、聊天页结构 - `docs/agent/ui-composer.md` — 输入区高度(为什么必须 `BasicTextField`)、上下文预算指示器的数据来源与三种口径 diff --git a/CHANGELOG.md b/CHANGELOG.md index a2d0fb6..c55258b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ ### 修复 - Rewind(回退)在服务端其实已成功,客户端却报 `Unexpected symbol 't' in numeric literal at path: $.data.files_rewound`:`history_rewound` / `files_rewound` 是布尔值,模型误声明成整数。 +- 回退成功后聊天页不刷新:`reload()` 一直走「合并」路径,把服务端已删除的 turn 留在屏幕上,必须退出会话重进才消失;现在回退与 `history_rewound` 事件都走整体替换。 - 回退结果文案区分「历史已截断」与「文件快照是否恢复」,文件没恢复时不再被一句「已回退」掩盖。 ### 变更 diff --git a/app/src/main/java/dev/xbot/android/chat/ChatModels.kt b/app/src/main/java/dev/xbot/android/chat/ChatModels.kt index 62953ee..e2b4fdd 100644 --- a/app/src/main/java/dev/xbot/android/chat/ChatModels.kt +++ b/app/src/main/java/dev/xbot/android/chat/ChatModels.kt @@ -81,6 +81,8 @@ data class ChatUiState( val loadingMore: Boolean = false, val loadMoreError: String? = null, val needsReload: Boolean = false, + /** needsReload 的语义补充:历史被截断(回退),重载必须整体替换而不是合并。 */ + val reloadReplacesHistory: Boolean = false, val pendingUserText: String? = null, /** null = 服务端还没有真实 token 数据(新会话 / 未发起过 LLM 调用)。 */ val contextBudget: ContextBudgetUi? = null, diff --git a/app/src/main/java/dev/xbot/android/chat/ChatReducer.kt b/app/src/main/java/dev/xbot/android/chat/ChatReducer.kt index 0c196f9..138b405 100644 --- a/app/src/main/java/dev/xbot/android/chat/ChatReducer.kt +++ b/app/src/main/java/dev/xbot/android/chat/ChatReducer.kt @@ -110,6 +110,7 @@ object ChatReducer { loadingMore = false, loadMoreError = null, needsReload = false, + reloadReplacesHistory = false, pendingUserText = null, ) if (active != null && (active.turnId > 0L || activeRunning)) { @@ -146,6 +147,7 @@ object ChatReducer { loadingMore = false, loadMoreError = null, needsReload = false, + reloadReplacesHistory = false, pendingUserText = null, ) if (active != null && (active.turnId > 0L || activeRunning)) { @@ -380,6 +382,12 @@ object ChatReducer { liveIteration = 0, ) "deleted" -> state.copy(busy = false) + // 服务端在历史被截断后广播这个动作(可能是另一端发起的回退)。 + // 必须标成「整体替换」:合并式重载会把已删除的 turn 留在屏幕上。 + "history_rewound" -> state.copy( + needsReload = true, + reloadReplacesHistory = true, + ) else -> state } } diff --git a/app/src/main/java/dev/xbot/android/chat/ChatViewModel.kt b/app/src/main/java/dev/xbot/android/chat/ChatViewModel.kt index df7a17f..528c63d 100644 --- a/app/src/main/java/dev/xbot/android/chat/ChatViewModel.kt +++ b/app/src/main/java/dev/xbot/android/chat/ChatViewModel.kt @@ -48,7 +48,16 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) { reload() } - fun reload() { + /** + * Reload the newest page of history. + * + * [replaceTurns] must be true whenever the server may have **removed** turns + * (rewind, or any truncation): merging keeps turns that no longer exist + * server-side, which is exactly why a rewound message used to stay on screen + * until the chat was reopened. Normal reloads keep the merge so pages loaded + * by scrolling up are not thrown away. + */ + fun reload(replaceTurns: Boolean = false) { if (chatId.isBlank() || reloading) return reloading = true loadJob?.cancel() @@ -58,7 +67,7 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) { api.history(chatId, channel, historyLimit, 0) } _state.update { current -> - if (current.turns.isNotEmpty() && current.oldestId > 0L) { + if (!replaceTurns && current.turns.isNotEmpty() && current.oldestId > 0L) { ChatReducer.mergeLatestHistory(current, response) } else { ChatReducer.withHistory(current, response) @@ -200,7 +209,7 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) { } fun acknowledgeReload() { - _state.update { it.copy(needsReload = false) } + _state.update { it.copy(needsReload = false, reloadReplacesHistory = false) } } private fun startStream() { @@ -214,8 +223,9 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) { // 这时刷新一次上下文预算,指示器才不会停在回合中途的估值上。 if (wasBusy && !_state.value.busy) refreshContextBudget() if (_state.value.needsReload) { + val replace = _state.value.reloadReplacesHistory acknowledgeReload() - reload() + reload(replaceTurns = replace) } } } diff --git a/app/src/main/java/dev/xbot/android/ui/ChatScreen.kt b/app/src/main/java/dev/xbot/android/ui/ChatScreen.kt index c5bf06e..9e446fb 100644 --- a/app/src/main/java/dev/xbot/android/ui/ChatScreen.kt +++ b/app/src/main/java/dev/xbot/android/ui/ChatScreen.kt @@ -653,7 +653,8 @@ fun ChatScreen( app.container.api.rewindHistory(chatId, channel, historyId) }.onSuccess { response -> if (response.draft.isNotBlank()) input = response.draft - vm.reload() + // 回退是「删掉」历史,必须整体替换,合并会把已回退的 turn 留在屏幕上。 + vm.reload(replaceTurns = true) snackbar.showSnackbar(rewindMessage(response)) }.onFailure { snackbar.showSnackbar(it.message ?: "回退失败") diff --git a/app/src/test/java/dev/xbot/android/chat/ChatReducerTest.kt b/app/src/test/java/dev/xbot/android/chat/ChatReducerTest.kt index 30eb6d0..f122cbe 100644 --- a/app/src/test/java/dev/xbot/android/chat/ChatReducerTest.kt +++ b/app/src/test/java/dev/xbot/android/chat/ChatReducerTest.kt @@ -498,4 +498,71 @@ class ChatReducerTest { assertEquals("/tmp/work", state.cwd) } + + @Test + fun `history rewound session event asks for a replacing reload`() { + val state = ChatReducer.applyEvent( + ChatReducer.empty("chat_1", "web"), + WsMessage( + type = "session", + session = SessionEvent(action = "history_rewound", chatId = "chat_1"), + ), + ) + + assertTrue(state.needsReload) + assertTrue(state.reloadReplacesHistory) + } + + @Test + fun `applying a fresh history clears the replacing-reload flag`() { + val state = ChatReducer.withHistory( + ChatReducer.empty("chat_1", "web").copy( + needsReload = true, + reloadReplacesHistory = true, + ), + HistoryResponse(ok = true, messages = emptyList()), + ) + + assertFalse(state.needsReload) + assertFalse(state.reloadReplacesHistory) + } + + @Test + fun `replace reload drops turns the server no longer returns`() { + // 回退后服务端只剩 turn 1;合并式重载会保留 turn 2(旧 bug),整体替换才清掉。 + val before = ChatReducer.withHistory( + ChatReducer.empty("chat_1", "web"), + HistoryResponse( + ok = true, + messages = listOf( + HistoryMessage(id = 1, role = "user", content = "keep me", turnId = 1), + HistoryMessage(id = 2, role = "user", content = "rewound", turnId = 2), + ), + ), + ) + assertEquals(2, before.turns.size) + + val replaced = ChatReducer.withHistory( + before, + HistoryResponse( + ok = true, + messages = listOf( + HistoryMessage(id = 1, role = "user", content = "keep me", turnId = 1), + ), + ), + ) + assertEquals(listOf(1L), replaced.turns.map { it.turnId }) + + // 同一份响应走合并路径时旧 turn 会留下 —— 这正是之前必须退出会话才生效的原因。 + val merged = ChatReducer.mergeLatestHistory( + before, + HistoryResponse( + ok = true, + messages = listOf( + HistoryMessage(id = 1, role = "user", content = "keep me", turnId = 1), + ), + ), + ) + assertEquals(listOf(1L, 2L), merged.turns.map { it.turnId }) + } } diff --git a/docs/agent/chat.md b/docs/agent/chat.md new file mode 100644 index 0000000..4eaedbc --- /dev/null +++ b/docs/agent/chat.md @@ -0,0 +1,45 @@ +# 聊天状态机(chat/)——历史装载的两条路径 + +`ChatReducer` 是纯函数状态机,`ChatViewModel` 只负责拉数据、派发事件。历史装载有两条**语义不同**的路径, +混用会产生「界面上留着服务端已经没有的消息」这类 bug。 + +## withHistory:替换 + +`ChatReducer.withHistory(state, response)` 用响应**重建** `turns`(`response.messages` 全量映射), +同时重置 `hasMore / oldestId`。何时必须用它: + +- 首次进入会话(`ChatViewModel.open()` 里 `_state = ChatReducer.empty(...)` 之后); +- **服务端可能删掉了 turn 的任何情况**:Rewind 回退、历史压缩截断。 + +## mergeLatestHistory:合并 + +`ChatReducer.mergeLatestHistory(state, response)` 从 `state.turns` 出发,把响应里出现的 turn 覆盖上去, +并保留更早的分页游标(`oldestId`)。它是为「无缝补页」服务的:用户上滑加载过多页之后, +SSE 重连 / `resync_required` 触发的重载不能把这些页丢掉,否则会陷入 reload/loadMore 循环。 + +**它只增不减**:服务端不再返回的 turn 会被原样保留。所以拿它处理「删除类」事件,界面就会永远滞后。 + +## 什么时候用哪个 + +| 触发 | 用哪个 | 说明 | +|---|---|---| +| `open()` 首次载入 | `withHistory` | state 是空的 | +| 普通 `reload()`(重连、resync、下拉刷新) | `mergeLatestHistory` | 保住已加载的旧页 | +| **Rewind 成功后** | `withHistory` | 回退删掉了 turn,合并会让它继续显示 | +| SSE `session.action == "history_rewound"` | `withHistory` | 可能是另一端发起的回退 | + +实现上由 `ChatViewModel.reload(replaceTurns: Boolean = false)` 统一入口: + +- `reload(replaceTurns = true)` → `withHistory`(整体替换); +- 默认 → `mergeLatestHistory`(合并)。 + +SSE 侧由 reducer 标记 `ChatUiState.needsReload` + `reloadReplacesHistory`(`applySession` 处理 +`history_rewound`),ViewModel 消费时把后者传给 `reload(replaceTurns = ...)`。 +**不要只用 `needsReload` 一个布尔量**:`resync_required` 也用它,而那条路径必须是合并语义。 + +## 踩过的症状 + +Rewind 在服务端已成功、客户端也解析对了响应,但屏幕上的消息不消失,**必须退出会话再重新进来**才正常。 +原因是 `reload()` 当时无条件走合并分支(会话已加载时 `turns.isNotEmpty() && oldestId > 0` 恒成立), +而 `open()` 会重置 state,才「看起来好了」。新增用例 +`replace reload drops turns the server no longer returns` 同时钉住了两条路径的差异。 diff --git a/version.properties b/version.properties index f134a60..f6d9e19 100644 --- a/version.properties +++ b/version.properties @@ -1,2 +1,2 @@ -versionCode=21 +versionCode=22 versionName=0.3.4