Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,18 @@ 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/`,公网前缀是
`https://minio.cjiw.site/uploads/share/android/`;`local` 别名签名已失效,别用。

## 知识文件

- `docs/agent/chat.md` — 历史装载的两条路径(替换 vs 合并)、Rewind 后为什么必须整体重载
- `docs/agent/ui.md` — Compose 界面约定、TopAppBar 布局陷阱、聊天页结构
- `docs/agent/ui-composer.md` — 输入区高度(为什么必须 `BasicTextField`)、上下文预算指示器的数据来源与三种口径

## 约定

Expand Down
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,23 @@
写进更新清单的 `changelog` 字段,最终显示在 app 的更新卡片上。小节标题请严格保持
`## [版本号]` 的形式,最新版本放最上面。

## [0.3.4]

输入区变矮,并给出上下文预算。

### 新增
- 输入框上方新增上下文占用文字(形如 `85K/200K`),60% 转黄、85% 转红,点开可看已用输入 / 上下文上限 / 当前占用 / 模型。
- 会话项显示工作目录(`work_dir`,路径按段左截断保留尾部);聊天页把它显示在输入框上方那行上下文占用的旁边。
- 数据来自 `/api/session/status`:服务端还没有真实 token 数(新会话)时不显示指示器;回合进行中用上一次的上限估算并标注。

### 修复
- Rewind(回退)在服务端其实已成功,客户端却报 `Unexpected symbol 't' in numeric literal at path: $.data.files_rewound`:`history_rewound` / `files_rewound` 是布尔值,模型误声明成整数。
- 回退成功后聊天页不刷新:`reload()` 一直走「合并」路径,把服务端已删除的 turn 留在屏幕上,必须退出会话重进才消失;现在回退与 `history_rewound` 事件都走整体替换。
- 回退结果文案区分「历史已截断」与「文件快照是否恢复」,文件没恢复时不再被一句「已回退」掩盖。

### 变更
- 输入区高度从约 72dp 压到约 48dp:文本框改用 `BasicTextField`(`OutlinedTextField` 在装饰盒内固定 56dp 最小高度,压不下去),图标按钮 48dp → 36dp。

## [0.3.3]

自动更新增加**开发版**分发通道,稳定版与开发版各有一份清单。
Expand Down
23 changes: 23 additions & 0 deletions app/src/main/java/dev/xbot/android/chat/ChatModels.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -43,10 +44,28 @@ data class AskUserUi(
val questions: List<AskUserQuestion>,
)

/**
* 上下文预算:服务端 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",
val title: String = "",
/** 该会话的工作目录(服务端 work_dir / session status 的 cwd)。 */
val cwd: String = "",
val loading: Boolean = false,
val error: String? = null,
val connected: Boolean = false,
Expand All @@ -62,7 +81,11 @@ 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,
) {
val isEmpty: Boolean get() = turns.isEmpty() && pendingUserText == null
}
75 changes: 75 additions & 0 deletions app/src/main/java/dev/xbot/android/chat/ChatReducer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ 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
import kotlinx.serialization.decodeFromString
Expand All @@ -25,6 +27,68 @@ 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`。
*
* 服务端只在拿到真实 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<Long, TurnUi>()
response.messages.forEach { message -> mergeHistoryMessage(turns, message) }
Expand All @@ -46,6 +110,7 @@ object ChatReducer {
loadingMore = false,
loadMoreError = null,
needsReload = false,
reloadReplacesHistory = false,
pendingUserText = null,
)
if (active != null && (active.turnId > 0L || activeRunning)) {
Expand Down Expand Up @@ -82,6 +147,7 @@ object ChatReducer {
loadingMore = false,
loadMoreError = null,
needsReload = false,
reloadReplacesHistory = false,
pendingUserText = null,
)
if (active != null && (active.turnId > 0L || activeRunning)) {
Expand Down Expand Up @@ -152,6 +218,9 @@ object ChatReducer {

fun applyProgress(state: ChatUiState, progress: ProgressEvent): ChatUiState {
var next = state
// 回合进行中的 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 ->
Expand Down Expand Up @@ -313,6 +382,12 @@ object ChatReducer {
liveIteration = 0,
)
"deleted" -> state.copy(busy = false)
// 服务端在历史被截断后广播这个动作(可能是另一端发起的回退)。
// 必须标成「整体替换」:合并式重载会把已删除的 turn 留在屏幕上。
"history_rewound" -> state.copy(
needsReload = true,
reloadReplacesHistory = true,
)
else -> state
}
}
Expand Down
41 changes: 37 additions & 4 deletions app/src/main/java/dev/xbot/android/chat/ChatViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -47,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()
Expand All @@ -57,13 +67,14 @@ 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)
}
}
restorePendingAskUser()
refreshContextBudget()
} catch (e: UnauthorizedException) {
_state.update { it.copy(loading = false, error = "登录已失效,请重新登录") }
} catch (e: Exception) {
Expand All @@ -74,6 +85,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.withSessionStatus(it, status) }
}
}
}

fun loadMore() {
val current = _state.value
if (!current.hasMore ||
Expand Down Expand Up @@ -182,18 +209,23 @@ 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() {
val client = XbotSseClient(api, prefs, viewModelScope)
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) {
val replace = _state.value.reloadReplacesHistory
acknowledgeReload()
reload()
reload(replaceTurns = replace)
}
}
}
Expand Down Expand Up @@ -235,6 +267,7 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
}

private fun closeStream() {
budgetJob?.cancel()
eventsJob?.cancel()
sseStateJob?.cancel()
eventsJob = null
Expand Down
5 changes: 5 additions & 0 deletions app/src/main/java/dev/xbot/android/data/Models.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 5 additions & 2 deletions app/src/main/java/dev/xbot/android/data/SessionActions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "",
)
15 changes: 15 additions & 0 deletions app/src/main/java/dev/xbot/android/data/XbotApi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
// ------------------------------------------------------------------
Expand Down
18 changes: 13 additions & 5 deletions app/src/main/java/dev/xbot/android/sessions/SessionsScreen.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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 }) {
Expand Down
Loading
Loading