Preserve bounded background viewer fixes before resumed review

This commit is contained in:
2026-10-18 23:25:16 +01:00
parent d4034c6479
commit 72281716c6
6 changed files with 185 additions and 13 deletions
@@ -6,6 +6,7 @@ import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import java.util.concurrent.ConcurrentHashMap
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
@@ -169,6 +170,7 @@ class AppViewModel(
private val startKeys = ConcurrentHashMap<Long, String>()
private val retryKeys = ConcurrentHashMap<Long, String>()
private val shellOutputJobs = ConcurrentHashMap<String, Job>()
/** The multi-chat screen state (sessions, open conversations, drafts, scroll). */
private val chatStore = ChatStore(
@@ -1009,17 +1011,22 @@ class AppViewModel(
* shown on return.
*/
fun openChatSession(session: ChatSession) {
cancelShellOutputWhenSwitchingTo(session.id)
val needsHistory = chatStore.open(session)
if (needsHistory) loadChatHistory(session.id)
}
/** Switches to an already-open chat, re-syncing it when it is running. */
fun activateChat(sessionId: String) {
cancelShellOutputWhenSwitchingTo(sessionId)
if (chatStore.activate(sessionId)) loadChatHistory(sessionId)
}
/** Shows the session list again while keeping every open conversation. */
fun showChatList() = chatStore.showList()
fun showChatList() {
chatStore.value.activeId?.let(::cancelShellOutput)
chatStore.showList()
}
/**
* Narrows the session list to what matches [query] over each chat's title and
@@ -1029,7 +1036,10 @@ class AppViewModel(
*/
fun setChatSessionQuery(query: String) = chatStore.searchSessions(query)
fun closeChat(sessionId: String) = chatStore.close(sessionId)
fun closeChat(sessionId: String) {
cancelShellOutput(sessionId)
chatStore.close(sessionId)
}
fun updateChatDraft(sessionId: String, text: String) = chatStore.draft(sessionId, text)
@@ -1104,7 +1114,10 @@ class AppViewModel(
* anything — it exposes no delete for an OpenCode session — so the removal is
* local and can be undone from the message that reports it.
*/
fun removeChat(sessionId: String) = chatStore.remove(sessionId)
fun removeChat(sessionId: String) {
cancelShellOutput(sessionId)
chatStore.remove(sessionId)
}
fun undoRemoveChat() = chatStore.undoRemove()
@@ -1121,6 +1134,7 @@ class AppViewModel(
try {
val page = repository.chatMessages(sessionId, CHAT_HISTORY_LIMIT)
chatStore.history(sessionId, page.messages, page.nextCursor, page.hasMore)
loadChatShells(sessionId)
} catch (t: Throwable) {
if (t is CancellationException) throw t
chatStore.failed(sessionId, ErrorMessages.describe(t))
@@ -1128,6 +1142,53 @@ class AppViewModel(
}
}
private fun loadChatShells(sessionId: String) {
viewModelScope.launch {
try {
chatStore.shellsLoaded(sessionId, repository.chatShells(sessionId))
} catch (t: Throwable) {
if (t is CancellationException) throw t
// Shell listing is additive; an older server must not make chat history fail.
}
}
}
fun selectChatShell(sessionId: String, shellId: String?) {
cancelShellOutput(sessionId)
chatStore.selectShell(sessionId, shellId)
if (shellId != null) refreshChatShellOutput(sessionId, shellId)
}
fun refreshChatShellOutput(sessionId: String, shellId: String) {
cancelShellOutput(sessionId)
chatStore.shellOutputLoading(sessionId, shellId)
// Install before starting so a replacement can never be removed by an
// older request that finishes during launch.
val job = viewModelScope.launch(start = CoroutineStart.LAZY) {
try {
// Always reread from zero: the server's bounded page is authoritative,
// and the client never appends unbounded output to an in-memory buffer.
val page = repository.chatShellOutput(sessionId, shellId, cursor = 0)
chatStore.shellOutputLoaded(sessionId, shellId, page)
} catch (t: Throwable) {
if (t is CancellationException) throw t
chatStore.shellOutputFailed(sessionId, shellId, ErrorMessages.describe(t))
} finally {
shellOutputJobs.remove(sessionId, coroutineContext[Job])
}
}
shellOutputJobs[sessionId] = job
job.start()
}
private fun cancelShellOutputWhenSwitchingTo(sessionId: String) {
chatStore.value.activeId?.takeIf { it != sessionId }?.let(::cancelShellOutput)
}
private fun cancelShellOutput(sessionId: String) {
shellOutputJobs.remove(sessionId)?.cancel()
}
/** Fetches the next opaque older-history page without replacing live state. */
fun loadOlderChatHistory(sessionId: String) {
val thread = chatStore.value.thread(sessionId) ?: return
@@ -1325,6 +1386,7 @@ class AppViewModel(
*/
fun closeChatSession(sessionId: String) {
if (sessionId.isBlank()) return
cancelShellOutput(sessionId)
viewModelScope.launch {
try {
val closed = repository.chatClose(sessionId)
@@ -248,7 +248,13 @@ internal fun ChatConversationPane(
}
// The viewer keeps the bounded exit tail only when this client saw it.
if (thread.observedShells.isNotEmpty()) {
BackgroundProcessBar(thread.observedShells)
BackgroundProcessBar(
shells = thread.observedShells,
selectedID = thread.selectedShellId,
output = thread.shellOutput,
onSelect = { vm.selectChatShell(thread.sessionId, it) },
onRefresh = { vm.refreshChatShellOutput(thread.sessionId, it) },
)
}
if (thread.error != null && thread.loaded) {
Text(
@@ -10,6 +10,13 @@ import net.awan.pipelines.data.protocol.ChatPermissionFrame
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.data.protocol.ChatSession
import net.awan.pipelines.data.protocol.ChatShell
import net.awan.pipelines.data.protocol.ChatShellOutputPage
data class ChatShellOutputState(
val loading: Boolean = false,
val error: String? = null,
val page: ChatShellOutputPage? = null,
)
/**
* A saved scroll position inside one conversation. Kept as Android-free
@@ -122,6 +129,8 @@ data class ChatThread(
* claiming historical shell discovery.
*/
val shells: Map<String, ChatShell> = emptyMap(),
val selectedShellId: String? = null,
val shellOutput: ChatShellOutputState? = null,
/** The unsent composer text for this chat. */
val draft: String = "",
/**
@@ -893,6 +902,40 @@ class ChatStore(
fun running(sessionId: String, running: Boolean) = update(sessionId) { setRunning(it, running) }
/** Replaces the running snapshot while retaining only exits observed locally. */
fun shellsLoaded(sessionId: String, running: List<ChatShell>) = update(sessionId) { thread ->
val live = running.filter { it.id.isNotBlank() }.associateBy { it.id }
val observedExits = thread.shells.filterValues { it.status == ChatProtocol.SHELL_EXITED }
thread.copy(shells = (observedExits + live).entries.toList()
.takeLast(OBSERVED_SHELL_LIMIT).associate { it.toPair() })
}
fun selectShell(sessionId: String, shellId: String?) = update(sessionId) { thread ->
if (shellId != null && shellId !in thread.shells) thread
else thread.copy(selectedShellId = shellId, shellOutput = null)
}
fun shellOutputLoading(sessionId: String, shellId: String) = update(sessionId) { thread ->
if (thread.selectedShellId != shellId) thread
else thread.copy(shellOutput = ChatShellOutputState(loading = true))
}
fun shellOutputLoaded(sessionId: String, shellId: String, page: ChatShellOutputPage) = update(sessionId) { thread ->
if (thread.selectedShellId != shellId) thread
else {
val reported = page.shell.takeIf { it.id.isNotBlank() }
val shells = if (reported == null) thread.shells else
(thread.shells + (reported.id to reported.copy(command = reported.command.ifBlank { thread.shells[reported.id]?.command.orEmpty() })))
.entries.toList().takeLast(OBSERVED_SHELL_LIMIT).associate { it.toPair() }
thread.copy(shells = shells, shellOutput = ChatShellOutputState(page = page))
}
}
fun shellOutputFailed(sessionId: String, shellId: String, message: String) = update(sessionId) { thread ->
if (thread.selectedShellId != shellId) thread
else thread.copy(shellOutput = ChatShellOutputState(error = message))
}
/**
* Records that the operator's last prompt was accepted into the session's
* queue (true) or sent immediately (false), so the composer can say "Queued"
@@ -388,8 +388,14 @@ private fun RunningToolLine(part: ChatPart, elapsedMillis: Long) {
/** A read-only, expandable task viewer for verified shells this chat observed. */
@Composable
internal fun BackgroundProcessBar(shells: List<ChatShell>, modifier: Modifier = Modifier) {
var selectedID by rememberSaveable { mutableStateOf<String?>(null) }
internal fun BackgroundProcessBar(
shells: List<ChatShell>,
selectedID: String?,
output: ChatShellOutputState?,
onSelect: (String?) -> Unit,
onRefresh: (String) -> Unit,
modifier: Modifier = Modifier,
) {
val selected = shells.firstOrNull { it.id == selectedID }
Column(
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
@@ -408,12 +414,12 @@ internal fun BackgroundProcessBar(shells: List<ChatShell>, modifier: Modifier =
shells.forEach { shell ->
key(shell.id) {
BackgroundProcessLine(shell, selectedID == shell.id) {
selectedID = if (selectedID == shell.id) null else shell.id
onSelect(if (selectedID == shell.id) null else shell.id)
}
}
}
if (selected != null) {
BackgroundProcessDetail(selected)
BackgroundProcessDetail(selected, output, onRefresh)
}
}
}
@@ -460,7 +466,7 @@ private fun BackgroundProcessLine(shell: ChatShell, selected: Boolean, onSelect:
/** Detail intentionally exposes only state known from verified lifecycle frames. */
@Composable
private fun BackgroundProcessDetail(shell: ChatShell) {
private fun BackgroundProcessDetail(shell: ChatShell, output: ChatShellOutputState?, onRefresh: (String) -> Unit) {
Surface(
color = MaterialTheme.colorScheme.surfaceContainer,
shape = RoundedCornerShape(CHAT_GUTTER),
@@ -483,7 +489,25 @@ private fun BackgroundProcessDetail(shell: ChatShell) {
},
style = MaterialTheme.typography.bodySmall,
)
Text("Output is unavailable until the server provides verified readback.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
when {
output?.loading == true -> CircularProgressIndicator(modifier = Modifier.size(ICON_STATUS_DP))
output?.error != null -> Row(horizontalArrangement = Arrangement.spacedBy(SPACING_XS)) {
Text(output.error, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
Text("Retry", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.primary,
modifier = Modifier.clickable { onRefresh(shell.id) })
}
output?.page?.unavailable == true -> Text("Output unavailable for this task.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
output?.page != null && output.page.output.isEmpty() -> Text("No output yet.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
output?.page != null -> {
Text("Output", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(output.page.output, style = MaterialTheme.typography.bodySmall, fontFamily = FontFamily.Monospace)
if (output.page.truncated) {
Text("Output is bounded to 64 KiB.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Text("Refresh", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.primary,
modifier = Modifier.clickable { onRefresh(shell.id) })
}
}
}
}
}
@@ -5,6 +5,7 @@ import net.awan.pipelines.data.protocol.ChatPart
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.data.protocol.ChatSession
import net.awan.pipelines.data.protocol.ChatShell
import net.awan.pipelines.data.protocol.ChatShellOutputPage
import net.awan.pipelines.data.protocol.ChatStep
import net.awan.pipelines.data.protocol.ChatToolState
import org.junit.Assert.assertEquals
@@ -208,4 +209,39 @@ class ChatInFlightStateTest {
assertEquals(listOf("s"), store.streamResumed())
assertTrue(store.value.thread("s")!!.runningShells.isEmpty())
}
@Test
fun shellSelectionKeepsObservedExitAndDropsStaleOutputOnSwitch() {
val store = ChatStore(now = { 1_000L })
store.open(ChatSession(id = "s", title = "s"))
store.shellsLoaded("s", listOf(ChatShell(id = "sh_1", status = ChatProtocol.SHELL_RUNNING, command = "run")))
store.selectShell("s", "sh_1")
store.shellOutputLoading("s", "sh_1")
store.shellOutputLoaded("s", "sh_1", ChatShellOutputPage(output = "actual", cursor = 6, size = 6))
store.event(shellFrame("s", "sh_1", ChatProtocol.SHELL_EXITED, exit = 0))
val exited = store.value.thread("s")!!
assertEquals(ChatProtocol.SHELL_EXITED, exited.observedShells.single().status)
assertEquals("actual", exited.shellOutput?.page?.output)
store.shellsLoaded("s", listOf(ChatShell(id = "sh_2", status = ChatProtocol.SHELL_RUNNING, command = "other")))
store.selectShell("s", "sh_2")
assertEquals("sh_2", store.value.thread("s")!!.selectedShellId)
assertEquals(null, store.value.thread("s")!!.shellOutput)
}
@Test
fun shellOutputCannotCrossSessionOrSelection() {
val store = ChatStore(now = { 1_000L })
store.open(ChatSession(id = "a", title = "a"))
store.open(ChatSession(id = "b", title = "b"))
store.shellsLoaded("a", listOf(ChatShell(id = "same", status = ChatProtocol.SHELL_RUNNING)))
store.shellsLoaded("b", listOf(ChatShell(id = "same", status = ChatProtocol.SHELL_RUNNING)))
store.selectShell("a", "same")
store.shellOutputLoaded("b", "same", ChatShellOutputPage(output = "foreign"))
assertEquals(null, store.value.thread("a")!!.shellOutput)
assertEquals(null, store.value.thread("b")!!.shellOutput)
store.shellOutputLoaded("a", "same", ChatShellOutputPage(output = "owned"))
assertEquals("owned", store.value.thread("a")!!.shellOutput?.page?.output)
}
}