fix(chat): preserve usage baseline across local aborts

This commit is contained in:
M57 committed 2026-09-16 10:14:48 +03:00
1 parent d16a2ea35c
commit 22b948f671
4 files changed
+80 -13

No files matched your search

@@ -1676,17 +1676,6 @@ class ChatViewModel(
userMessage: ChatMessage? = null,
) {
val dispatchGeneration = sessionGeneration
// Capture before attachment work or prompt submission can advance the
// cumulative counters. The reducer preserves this baseline across
// every assistant segment in a tool loop.
if (!_streamingState.value.turnUsageBaselineCaptured) {
_streamingState.update {
it.copy(
turnUsageBaseline = _uiState.value.sessionUsage,
turnUsageBaselineCaptured = true,
)
}
}
AuthManager.setLastOpenedSessionId(storageSessionId)
val msgToPersist =
userMessage ?: ChatMessage(
@@ -1826,6 +1815,7 @@ class ChatViewModel(
if (dispatchGeneration == sessionGeneration) {
ActiveSessionHolder.set(agentSessionId, storageSessionId)
}
captureTurnUsageBaselineIfNeeded()
if (wasStreaming && attachments.isEmpty()) {
wsClient.sendRedirect(
agentSessionId,
@@ -1859,6 +1849,20 @@ class ChatViewModel(
}
}
private fun captureTurnUsageBaselineIfNeeded() {
if (_streamingState.value.turnUsageBaselineCaptured) return
_streamingState.update {
if (it.turnUsageBaselineCaptured) {
it
} else {
it.copy(
turnUsageBaseline = _uiState.value.sessionUsage,
turnUsageBaselineCaptured = true,
)
}
}
}
/** Snapshot one URI to private cache while enforcing the outbound frame limit. */
private suspend fun prepareAttachment(attachment: Attachment): PrepareAttachmentResult {
var encodedFile: File? = null
@@ -15,6 +15,8 @@ private fun List<ChatMessage>.upsertById(message: ChatMessage): List<ChatMessage
private fun Long.toIntOrNullSafely(): Int? = takeIf { it in Int.MIN_VALUE.toLong()..Int.MAX_VALUE.toLong() }?.toInt()
private fun Double?.validTpsOrNull(): Double? = takeIf { it != null && it.isFinite() && it > 0.0 }
internal fun applyUsageSnapshot(
state: ChatUiState,
snapshot: com.m57.hermescontrol.data.model.UsageSnapshotResponse,
@@ -432,7 +434,7 @@ object ChatWsEventReducer {
streamingState = StreamingState(),
)
}
val tps = (turnUsage?.avgTps ?: usageState.latestTps)?.takeIf { it.isFinite() && it > 0.0 }
val tps = turnUsage?.avgTps.validTpsOrNull() ?: usageState.latestTps.validTpsOrNull()
val tokenCount =
if (turnUsage?.outputTokens != null) {
turnUsage.outputTokens.toIntOrNullSafely()