Merge branch 'main' into chat-hide-notice-timeout

This commit is contained in:
2026-10-18 23:53:46 +01:00
26 changed files with 897 additions and 106 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
@@ -165,6 +166,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(
@@ -995,17 +997,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
@@ -1015,7 +1022,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)
@@ -1090,7 +1100,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 consumeChatRemovalNotice(noticeId: Long) = chatStore.consumeRemovalNotice(noticeId)
@@ -1111,6 +1124,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))
@@ -1118,6 +1132,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
@@ -1315,6 +1376,7 @@ class AppViewModel(
*/
fun closeChatSession(sessionId: String) {
if (sessionId.isBlank()) return
cancelShellOutput(sessionId)
viewModelScope.launch {
try {
val closed = repository.chatClose(sessionId)
@@ -179,6 +179,12 @@ internal fun attentionHeadline(entries: List<AttentionEntry>): String = when {
else -> "${entries.size} runs need you"
}
/**
* Captures the entries shown when the attention sheet opens. Bulk dismissal uses
* this snapshot so entries that arrive while the sheet is open are not removed.
*/
internal fun attentionDismissalSnapshot(entries: List<AttentionEntry>): List<AttentionEntry> = entries.toList()
/**
* Parses the run id from a `pipelines://run/<id>` deep link, or null for
* anything else. Pure and total, so a malformed link simply opens nothing rather
@@ -246,12 +246,15 @@ internal fun ChatConversationPane(
)
}
}
// The background processes still running, shown whether or not a turn
// is: a shell can outlive the turn that started it, so this is a strip
// of its own rather than part of the turn indicator, and it clears the
// moment each shell exits.
if (thread.runningShells.isNotEmpty()) {
BackgroundProcessBar(thread.runningShells)
// The viewer keeps the bounded exit tail only when this client saw it.
if (thread.observedShells.isNotEmpty()) {
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
@@ -115,14 +122,15 @@ data class ChatThread(
*/
val lastDeltaAt: Long = 0,
/**
* The agent's shell commands still running for this session, keyed by the
* shell id the server reported and in the order they started. A background
* process can outlive the tool call (and the turn) that started it, so this is
* thread state of its own rather than part of the turn: it keeps showing after
* the turn's indicator has gone, and a shell leaves the map the moment its
* exited frame arrives. Kept on the thread so it survives a chat switch.
* Verified shell commands observed for this session, keyed by their server
* id and in observation order. Running shells come from the authoritative
* snapshot/event stream. A small exited tail is retained only after this
* client observed its exit, so a selected task can settle honestly without
* 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 = "",
/**
@@ -201,11 +209,14 @@ data class ChatThread(
runningToolElapsedMillis(part, toolStartedAt[part.id] ?: 0L, nowMillis)
/**
* The background processes this session is still running, in start order, so
* a conversation shows what is running even when no turn is.
* The background processes currently running for this session, in start
* order, so a conversation shows what is running even when no turn is.
*/
val runningShells: List<ChatShell> get() = runningBackgroundShells(shells)
/** Bounded observed tasks, including a recently observed exit when present. */
val observedShells: List<ChatShell> get() = shells.values.toList()
/**
* What the in-flight turn is doing at [nowMillis] (see [turnPhase]): its
* running tool calls, and how long ago the last delta arrived. Pure, so the
@@ -929,6 +940,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"
@@ -1087,10 +1132,15 @@ class ChatStore(
val shell = frame.shell ?: return
if (shell.id.isBlank()) return
update(frame.sessionId) { thread ->
val shells = if (shell.status == ChatProtocol.SHELL_EXITED) {
thread.shells - shell.id
val prior = thread.shells[shell.id]
val merged = if (shell.status == ChatProtocol.SHELL_EXITED) {
shell.copy(command = shell.command.ifBlank { prior?.command.orEmpty() })
} else {
thread.shells + (shell.id to shell)
shell.copy(command = shell.command.ifBlank { prior?.command.orEmpty() })
}
val shells = (thread.shells + (shell.id to merged)).let { observed ->
if (observed.size <= OBSERVED_SHELL_LIMIT) observed
else observed.entries.toList().takeLast(OBSERVED_SHELL_LIMIT).associate { it.toPair() }
}
if (shells == thread.shells) thread else thread.copy(shells = shells)
}
@@ -1241,5 +1291,7 @@ class ChatStore(
companion object {
const val LOCAL_MESSAGE_PREFIX = "local-"
const val NOTICE_PREFIX = "notice-"
/** Per-session in-memory observation bound; this is not task history. */
const val OBSERVED_SHELL_LIMIT = 16
}
}
@@ -386,35 +386,54 @@ private fun RunningToolLine(part: ChatPart, elapsedMillis: Long) {
}
}
/**
* The always-visible indicator that the agent has a background process running —
* a dev server, a watching build, a sleep whose tool call has already returned.
* It is deliberately separate from the turn's spinner: a background process can
* outlive the turn, so this is shown whenever a shell is running, whether or not
* a turn is, and each line names the command the way the running-tool line names
* a call. It clears the moment the shell exits, because the exited frame removes
* it from the thread's shells. It survives a chat switch like the other live
* state, since it is read from the thread rather than held here.
*/
/** A read-only, expandable task viewer for verified shells this chat observed. */
@Composable
internal fun BackgroundProcessBar(shells: List<ChatShell>, modifier: Modifier = Modifier) {
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),
modifier = modifier.fillMaxWidth().padding(horizontal = CHAT_GUTTER, vertical = 4.dp),
) {
Text(
text = "Background tasks",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface,
)
Text(
text = "Running now and recently observed exits; not complete task history.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
shells.forEach { shell ->
key(shell.id) { BackgroundProcessLine(shell) }
key(shell.id) {
BackgroundProcessLine(shell, selectedID == shell.id) {
onSelect(if (selectedID == shell.id) null else shell.id)
}
}
}
if (selected != null) {
BackgroundProcessDetail(selected, output, onRefresh)
}
}
}
/** One background process: a distinct glyph, a `Background process` label and its command. */
/** One verified shell task; selection reveals its read-only detail. */
@Composable
private fun BackgroundProcessLine(shell: ChatShell) {
private fun BackgroundProcessLine(shell: ChatShell, selected: Boolean, onSelect: () -> Unit) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
modifier = Modifier.fillMaxWidth(),
modifier = Modifier
.fillMaxWidth()
.minimumInteractiveComponentSize()
.clickable(role = Role.Button, onClick = onSelect),
) {
Icon(
Icons.Default.PlayArrow,
@@ -423,7 +442,7 @@ private fun BackgroundProcessLine(shell: ChatShell) {
modifier = Modifier.size(ICON_STATUS_DP),
)
Text(
text = "Background process",
text = if (shell.status == ChatProtocol.SHELL_EXITED) "Exited" else "Running",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.tertiary,
)
@@ -435,6 +454,62 @@ private fun BackgroundProcessLine(shell: ChatShell) {
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
if (selected) {
Text(
text = "Details",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
/** Detail intentionally exposes only state known from verified lifecycle frames. */
@Composable
private fun BackgroundProcessDetail(shell: ChatShell, output: ChatShellOutputState?, onRefresh: (String) -> Unit) {
Surface(
color = MaterialTheme.colorScheme.surfaceContainer,
shape = RoundedCornerShape(CHAT_GUTTER),
modifier = Modifier.fillMaxWidth(),
) {
SelectionContainer {
Column(
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
modifier = Modifier.padding(CHAT_GUTTER),
) {
Text("Command", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(shell.command.ifBlank { "Unavailable" }, style = MaterialTheme.typography.bodyMedium)
Text("Task identity", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(shell.id, style = MaterialTheme.typography.bodySmall, fontFamily = FontFamily.Monospace)
Text(
text = if (shell.status == ChatProtocol.SHELL_EXITED) {
"Status: exited" + (shell.exit?.let { " (exit $it)" } ?: "; exit status unavailable")
} else {
"Status: running"
},
style = MaterialTheme.typography.bodySmall,
)
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) })
}
}
}
}
}
}
@@ -17,8 +17,10 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
@@ -27,6 +29,7 @@ import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.AttentionEntry
import net.awan.pipelines.ui.AttentionKind
import net.awan.pipelines.ui.attentionHeadline
import net.awan.pipelines.ui.attentionDismissalSnapshot
import net.awan.pipelines.ui.theme.ICON_INLINE_DP
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_M
@@ -105,6 +108,7 @@ fun AttentionSheet(
onDismiss: () -> Unit,
) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val dismissalSnapshot = remember { attentionDismissalSnapshot(entries) }
ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState) {
Column(
modifier = Modifier.fillMaxWidth().padding(bottom = SPACING_L),
@@ -124,6 +128,13 @@ fun AttentionSheet(
)
return@Column
}
TextButton(
onClick = { dismissalSnapshot.forEach(onDismissEntry) },
enabled = dismissalSnapshot.isNotEmpty(),
modifier = Modifier.padding(horizontal = SPACING_L),
) {
Text("Clear all")
}
entries.forEach { entry ->
AttentionRow(
entry = entry,
@@ -194,6 +194,16 @@ class AttentionTest {
assertEquals("A run failed", attentionHeadline(singleFailed))
}
@Test
fun dismissalSnapshotDoesNotIncludeEntriesThatArriveLater() {
val original = attentionEntries(listOf(run(1, "waiting")), AttentionState())
val snapshot = attentionDismissalSnapshot(original)
val current = original + attentionEntries(listOf(run(2, "failed")), AttentionState())
assertEquals(listOf(1L), snapshot.map { it.runId })
assertEquals(listOf(1L, 2L), current.map { it.runId })
}
// --- persistence -----------------------------------------------------------
@Test
@@ -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)
}
}