Merge branch 'main' into pill-run-decision

This commit is contained in:
2026-10-18 15:23:16 +01:00
21 changed files with 1115 additions and 76 deletions
@@ -7,6 +7,7 @@ import kotlinx.coroutines.flow.SharedFlow
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.JsonElement
import net.awan.pipelines.data.protocol.ChatCreateRequest
import net.awan.pipelines.data.protocol.ChatHistoryPage
import net.awan.pipelines.data.protocol.ChatMessage
import net.awan.pipelines.data.protocol.ChatPromptRequest
import net.awan.pipelines.data.protocol.ChatProtocol
@@ -297,12 +298,14 @@ class PipelinesRepository(
?: throw ProtocolException("The server did not return the new chat session.")
}
/** Loads a session's stored turns; the server prefers its retained live state. */
suspend fun chatMessages(sessionId: String, limit: Int = 0): List<ChatMessage> {
/** Loads a bounded chronological page; [cursor] is an opaque older-history continuation. */
suspend fun chatMessages(sessionId: String, limit: Int = 0, cursor: String = ""): ChatHistoryPage {
if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.")
return client.call(
Message(type = Protocol.CHAT_MESSAGES, chatQuery = ChatQuery(sessionId = sessionId, limit = limit)),
).chatMessages ?: emptyList()
val response = client.call(
Message(type = Protocol.CHAT_MESSAGES, chatQuery = ChatQuery(sessionId = sessionId, limit = limit, cursor = cursor)),
)
// Old servers only have chat_messages and therefore honestly expose no continuation.
return response.chatHistory ?: ChatHistoryPage(messages = response.chatMessages ?: emptyList())
}
/**
@@ -66,6 +66,7 @@ data class ChatCreateRequest(
data class ChatQuery(
@SerialName("session_id") val sessionId: String = "",
val limit: Int = 0,
val cursor: String = "",
)
@Serializable
@@ -126,6 +127,15 @@ data class ChatToolState(
val content: List<ChatToolContent> = emptyList(),
val metadata: JsonObject? = null,
val error: ChatError? = null,
// A bounded history preview is not the complete tool result.
val truncated: Boolean = false,
)
@Serializable
data class ChatHistoryPage(
val messages: List<ChatMessage> = emptyList(),
@SerialName("next_cursor") val nextCursor: String = "",
@SerialName("has_more") val hasMore: Boolean = false,
)
@Serializable
@@ -704,6 +704,7 @@ data class Message(
@SerialName("chat_queued") val chatQueued: Boolean = false,
@SerialName("chat_subscribe") val chatSubscribe: ChatQuery? = null,
@SerialName("chat_messages") val chatMessages: List<ChatMessage>? = null,
@SerialName("chat_history") val chatHistory: ChatHistoryPage? = null,
@SerialName("chat_event") val chatEvent: ChatEventFrame? = null,
@SerialName("chat_permission") val chatPermission: ChatPermissionFrame? = null,
@SerialName("chat_reply") val chatReply: ChatReplyRequest? = null,
@@ -1105,14 +1105,36 @@ class AppViewModel(
fun undoRemoveChat() = chatStore.undoRemove()
fun loadChatHistory(sessionId: String) {
if (chatStore.value.thread(sessionId)?.loading == true) return
// Set the gate before launching so repeated taps/events cannot queue two
// reads before the coroutine gets a chance to start.
chatStore.historyLoading(sessionId)
viewModelScope.launch {
// Watch the session's shared stream so frames from any client's turn
// arrive live. Best-effort: an older server answers an error frame,
// which must not stop the history from loading.
runCatching { repository.chatSubscribe(sessionId) }
chatStore.historyLoading(sessionId)
try {
chatStore.history(sessionId, repository.chatMessages(sessionId, CHAT_HISTORY_LIMIT))
val page = repository.chatMessages(sessionId, CHAT_HISTORY_LIMIT)
chatStore.history(sessionId, page.messages, page.nextCursor, page.hasMore)
} catch (t: Throwable) {
if (t is CancellationException) throw t
chatStore.failed(sessionId, ErrorMessages.describe(t))
}
}
}
/** Fetches the next opaque older-history page without replacing live state. */
fun loadOlderChatHistory(sessionId: String) {
val thread = chatStore.value.thread(sessionId) ?: return
if (!thread.hasMore || thread.loading) return
// Capture both the request-start snapshot and cursor before launch; this
// makes the per-thread loading gate effective for repeated requests.
chatStore.historyLoading(sessionId, older = true)
viewModelScope.launch {
try {
val page = repository.chatMessages(sessionId, CHAT_HISTORY_LIMIT, thread.nextCursor)
chatStore.history(sessionId, page.messages, page.nextCursor, page.hasMore)
} catch (t: Throwable) {
if (t is CancellationException) throw t
chatStore.failed(sessionId, ErrorMessages.describe(t))
@@ -12,6 +12,7 @@ import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.PanTool
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
@@ -173,6 +174,13 @@ internal fun ChatConversationPane(
}
},
actions = {
if (thread.hasMore) {
IconButton(
onClick = { vm.loadOlderChatHistory(thread.sessionId) },
) {
Icon(Icons.Default.KeyboardArrowUp, contentDescription = "Load older messages")
}
}
if (awaiting) {
IconButton(
onClick = {
@@ -79,6 +79,12 @@ data class ChatThread(
*/
val closed: Boolean = false,
val messages: List<ChatMessage> = emptyList(),
/** Opaque continuation for older messages returned by the server. */
val nextCursor: String = "",
val hasMore: Boolean = false,
/** Immutable snapshot at request start distinguishes stale cache from new live frames. */
val historyBeforeLoad: List<ChatMessage>? = null,
val historyLoadOlder: Boolean = false,
val loading: Boolean = false,
val loaded: Boolean = false,
val error: String? = null,
@@ -755,27 +761,121 @@ class ChatStore(
fun scroll(sessionId: String, index: Int, offset: Int) =
update(sessionId) { it.copy(scroll = ChatScrollPosition(index, offset)) }
fun historyLoading(sessionId: String) = update(sessionId) { it.copy(loading = true, error = null) }
fun historyLoading(sessionId: String, older: Boolean = false) = update(sessionId) {
it.copy(loading = true, error = null, historyBeforeLoad = it.messages, historyLoadOlder = older)
}
fun failed(sessionId: String, message: String) =
update(sessionId) { it.copy(loading = false, error = message) }
update(sessionId) { it.copy(loading = false, error = message, historyBeforeLoad = null) }
/** Linear-time suffix/prefix overlap: a history snapshot may include part of a live delta. */
private fun appendHistoryDelta(stored: String, delta: String): String {
if (delta.isEmpty()) return stored
val prefix = IntArray(delta.length)
for (index in 1 until delta.length) {
var matched = prefix[index - 1]
while (matched > 0 && delta[index] != delta[matched]) matched = prefix[matched - 1]
if (delta[index] == delta[matched]) matched++
prefix[index] = matched
}
var overlap = 0
for (char in stored) {
while (overlap > 0 && (overlap == delta.length || char != delta[overlap])) overlap = prefix[overlap - 1]
if (overlap < delta.length && char == delta[overlap]) overlap++
}
return stored + delta.substring(overlap)
}
/** Keep the full stored answer when a live-only suffix arrived during its first read. */
private fun mergeHistoryDuringRead(history: ChatMessage, live: ChatMessage, before: ChatMessage?): ChatMessage {
val parts = history.parts.toMutableList()
val partIndices = HashMap<String, Int>(parts.size)
val textIndices = HashMap<String, MutableList<Int>>()
for ((index, part) in parts.withIndex()) {
if (part.id.isNotBlank()) partIndices[part.id] = index
if (part.type == ChatProtocol.PART_TEXT || part.type == ChatProtocol.PART_REASONING) {
textIndices.getOrPut(part.type) { mutableListOf() }.add(index)
}
}
val beforeText = HashMap<String, MutableList<ChatPart>>()
before?.parts?.forEach { part ->
if (part.type == ChatProtocol.PART_TEXT || part.type == ChatProtocol.PART_REASONING) {
beforeText.getOrPut(part.type) { mutableListOf() }.add(part)
}
}
val ordinals = mutableMapOf<String, Int>()
for (part in live.parts) {
val ordinal = ordinals.getOrDefault(part.type, 0)
ordinals[part.type] = ordinal + 1
val textPart = part.type == ChatProtocol.PART_TEXT || part.type == ChatProtocol.PART_REASONING
val byId = partIndices[part.id]
// V2 stored text has no id; deltas have a stable generated ordinal id.
val index = byId ?: if (textPart) textIndices[part.type]?.getOrNull(ordinal) ?: -1 else -1
if (index < 0) {
parts += part
val appendedIndex = parts.lastIndex
if (part.id.isNotBlank()) partIndices[part.id] = appendedIndex
if (textPart) textIndices.getOrPut(part.type) { mutableListOf() }.add(appendedIndex)
} else if (textPart) {
val stored = parts[index].text
val previous = beforeText[part.type]?.getOrNull(ordinal)?.text
val delta = if (previous != null && part.text.startsWith(previous)) part.text.removePrefix(previous) else part.text
val text = when {
part.text.isEmpty() || stored.endsWith(part.text) -> stored
part.text.startsWith(stored) -> part.text
previous != null && !stored.startsWith(previous) -> part.text
delta.isEmpty() || stored.endsWith(delta) -> stored
else -> appendHistoryDelta(stored, delta)
}
parts[index] = part.copy(text = text)
} else {
parts[index] = part
}
}
return history.copy(parts = parts, client = live.client.ifBlank { history.client })
}
/**
* Replaces a thread's conversation with the server's authoritative history.
* Merges an authoritative page with older cached turns and in-flight events.
* The running flag is left as-is: history alone cannot say whether a turn is
* still in flight.
*/
fun history(sessionId: String, messages: List<ChatMessage>) {
fun history(sessionId: String, messages: List<ChatMessage>, nextCursor: String = "", hasMore: Boolean = false) {
update(sessionId) {
val existing = it.messages.associateBy { message -> message.id }
val baseline = it.historyBeforeLoad?.associateBy { message -> message.id }
val pageIds = messages.mapTo(mutableSetOf()) { message -> message.id }
val firstOverlap = it.messages.indexOfFirst { message -> message.id in pageIds }
val olderPrefix = when {
firstOverlap >= 0 -> it.messages.take(firstOverlap)
it.historyBeforeLoad != null && !it.historyLoadOlder -> it.messages
else -> emptyList()
}
val merged = (olderPrefix + messages + it.messages).fold(LinkedHashMap<String, ChatMessage>()) { result, message ->
// A live event may have extended this message while the read was
// in flight. Preserve only that fold, not stale pre-request cache
// which would otherwise hide text missed during a disconnect.
val local = existing[message.id]
val changedDuringRead = local != null && (baseline == null || baseline[message.id] != local)
if (message.id !in result) result[message.id] = when {
changedDuringRead && baseline != null -> mergeHistoryDuringRead(message, local!!, baseline[message.id])
changedDuringRead -> local!!
else -> message
}
result
}.values.toList()
it.copy(
messages = messages,
messages = merged,
nextCursor = nextCursor,
hasMore = hasMore,
loading = false,
loaded = true,
historyBeforeLoad = null,
error = null,
// A running call the history reports (a turn that started before
// this fetch) is stamped now, the best local measurement there is;
// a call that already settled drops its stamp.
toolStartedAt = runningToolStamps(it.toolStartedAt, messages, now()),
toolStartedAt = runningToolStamps(it.toolStartedAt, merged, now()),
)
}
// A conversation on screen is read as its history arrives: its recency
@@ -112,6 +112,71 @@ class MultiChatStateTest {
assertEquals(ChatScrollPosition(1, 0), store.value.thread("b")!!.scroll)
}
@Test
fun olderHistoryPrependsOnceAndKeepsLiveMessage() {
val store = ChatStore()
store.open(session("a"))
store.history("a", listOf(ChatMessage(
id = "new",
sessionId = "",
role = ChatProtocol.ROLE_ASSISTANT,
parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, id = "0", text = "live")),
)), "cursor-1", true)
store.historyLoading("a")
store.event(ChatEventFrame(
sessionId = "a",
messageId = "new",
kind = ChatProtocol.PART_TEXT,
delta = " update",
part = ChatPart(type = ChatProtocol.PART_TEXT, id = "0"),
))
store.history(
"a",
listOf(text("old", ChatProtocol.ROLE_USER, "older"), text("new", ChatProtocol.ROLE_ASSISTANT, "stale")),
"",
false,
)
val messages = store.value.thread("a")!!.messages
assertEquals(listOf("old", "new"), messages.map { it.id })
assertEquals("live update", messages.last().parts.single().text)
assertFalse(store.value.thread("a")!!.hasMore)
}
@Test
fun reconnectHistoryRepairsMissedTextWithoutDroppingOlderPagesOrDuplicatingIds() {
val store = ChatStore()
store.open(session("a"))
store.history("a", listOf(text("old", ChatProtocol.ROLE_USER, "older"), text("new", ChatProtocol.ROLE_ASSISTANT, "partial")))
store.streamResumed()
store.historyLoading("a")
store.history("a", listOf(text("new", ChatProtocol.ROLE_ASSISTANT, "partial and missed final answer")), "older", true)
val messages = store.value.thread("a")!!.messages
assertEquals(listOf("old", "new"), messages.map { it.id })
assertEquals("partial and missed final answer", messages.last().parts.single().text)
}
@Test
fun firstHistoryReadDoesNotReplaceFullAnswerWithLiveOnlySuffix() {
for (snapshot in listOf("full answer", "full answer ta", "full answer tail")) {
val store = ChatStore()
store.open(session("a"))
store.historyLoading("a")
store.event(ChatEventFrame(
sessionId = "a", messageId = "new", kind = ChatProtocol.PART_TEXT,
delta = " tail", part = ChatPart(type = ChatProtocol.PART_TEXT, id = "delta-0"),
))
store.history("a", listOf(ChatMessage(
id = "new", sessionId = "a", role = ChatProtocol.ROLE_ASSISTANT,
parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, text = snapshot)),
)))
val messages = store.value.thread("a")!!.messages
assertEquals(1, messages.size)
assertEquals("full answer tail", messages.single().parts.single().text)
}
}
@Test
fun busySessionStaysWritable() {
val store = ChatStore()