Merge branch 'main' into manager-honest-diffs

This commit is contained in:
2026-10-19 00:36:15 +01:00
31 changed files with 502 additions and 127 deletions
@@ -349,11 +349,11 @@ class PipelinesRepository(
* prompt the operator actually sent — never on their own. Returns true when the * prompt the operator actually sent — never on their own. Returns true when the
* server queued the prompt behind an in-flight turn. * server queued the prompt behind an in-flight turn.
*/ */
suspend fun chatPrompt(sessionId: String, text: String, files: List<String> = emptyList()): Boolean { suspend fun chatPrompt(sessionId: String, text: String, files: List<String> = emptyList(), operationId: String = newRequestKey()): Boolean {
if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.") if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.")
val trimmed = text.trim() val trimmed = text.trim()
if (trimmed.isEmpty()) throw ProtocolException("Enter a message before sending.") if (trimmed.isEmpty()) throw ProtocolException("Enter a message before sending.")
return client.call(ChatProtocol.promptRequest(sessionId, trimmed, files, clientLabel)).chatQueued return client.call(ChatProtocol.promptRequest(sessionId, trimmed, files, clientLabel, operationId, nativeMessageId(operationId))).chatQueued
} }
suspend fun chatInterrupt(sessionId: String) { suspend fun chatInterrupt(sessionId: String) {
@@ -408,5 +408,12 @@ class PipelinesRepository(
/** A durable key for one chat-create intent; retain it when retrying. */ /** A durable key for one chat-create intent; retain it when retrying. */
fun newChatCreateOperationId(): String = "android-chat-" + UUID.randomUUID().toString() fun newChatCreateOperationId(): String = "android-chat-" + UUID.randomUUID().toString()
/** OpenCode's optional caller id is the canonical bridge to history. */
fun nativeMessageId(operationId: String): String =
operationId.filter { character -> character.isLetterOrDigit() }.take(120)
.takeIf { it.isNotEmpty() }
?.let { "msg_" + it }
.orEmpty()
} }
} }
@@ -83,6 +83,8 @@ data class ChatPromptRequest(
// client can attribute the message; the server sanitises it and falls back to // client can attribute the message; the server sanitises it and falls back to
// a generic label when it is blank. // a generic label when it is blank.
val client: String = "", val client: String = "",
@SerialName("operation_id") val operationId: String = "",
@SerialName("native_message_id") val nativeMessageId: String = "",
) )
/** One stored turn: a user turn is a single text part, an assistant turn holds text/reasoning/tool parts. */ /** One stored turn: a user turn is a single text part, an assistant turn holds text/reasoning/tool parts. */
@@ -97,6 +99,7 @@ data class ChatMessage(
// The sending device's label on a user turn the server echoed, so a resumed // The sending device's label on a user turn the server echoed, so a resumed
// transcript still says who sent the message. Empty on an assistant turn. // transcript still says who sent the message. Empty on an assistant turn.
val client: String = "", val client: String = "",
@SerialName("operation_id") val operationId: String = "",
val parts: List<ChatPart> = emptyList(), val parts: List<ChatPart> = emptyList(),
) )
@@ -185,6 +188,7 @@ data class ChatEventFrame(
// The sending device's label on a `user` frame (another client's prompt), so // The sending device's label on a `user` frame (another client's prompt), so
// the transcript can say who sent it. Empty on the agent's own frames. // the transcript can say who sent it. Empty on the agent's own frames.
val client: String = "", val client: String = "",
@SerialName("operation_id") val operationId: String = "",
) )
/** /**
@@ -358,10 +362,10 @@ object ChatProtocol {
* shape a text-only prompt has always sent). Built here (not inline in the * shape a text-only prompt has always sent). Built here (not inline in the
* repository) so production and its unit test share the one wire shape. * repository) so production and its unit test share the one wire shape.
*/ */
fun promptRequest(sessionId: String, text: String, files: List<String> = emptyList(), client: String = ""): Message = fun promptRequest(sessionId: String, text: String, files: List<String> = emptyList(), client: String = "", operationId: String = "", nativeMessageId: String = ""): Message =
Message( Message(
type = Protocol.CHAT_PROMPT, type = Protocol.CHAT_PROMPT,
chatPrompt = ChatPromptRequest(sessionId = sessionId, text = text, files = files, client = client), chatPrompt = ChatPromptRequest(sessionId = sessionId, text = text, files = files, client = client, operationId = operationId, nativeMessageId = nativeMessageId),
) )
/** /**
@@ -1224,11 +1224,12 @@ class AppViewModel(
private fun postChatPrompt(sessionId: String, text: String, attachments: List<ChatAttachment>) { private fun postChatPrompt(sessionId: String, text: String, attachments: List<ChatAttachment>) {
val body = text.trim() val body = text.trim()
if (body.isEmpty()) return if (body.isEmpty()) return
val localId = chatStore.appendLocalUserMessage(sessionId, body, attachments) ?: return val operationId = PipelinesRepository.newRequestKey()
val localId = chatStore.appendLocalUserMessage(sessionId, body, attachments, operationId) ?: return
chatStore.running(sessionId, true) chatStore.running(sessionId, true)
viewModelScope.launch { viewModelScope.launch {
try { try {
val queued = repository.chatPrompt(sessionId, body, attachmentFiles(attachments)) val queued = repository.chatPrompt(sessionId, body, attachmentFiles(attachments), operationId)
// The server accepted the prompt (queued or sent); a queued prompt // The server accepted the prompt (queued or sent); a queued prompt
// is one waiting behind an in-flight turn, and the composer says so // is one waiting behind an in-flight turn, and the composer says so
// instead of blocking input. // instead of blocking input.
@@ -31,6 +31,8 @@ internal fun PipelineDestination(
onSelectionChange: (PaneSelection) -> Unit, onSelectionChange: (PaneSelection) -> Unit,
listState: LazyListState, listState: LazyListState,
onOpenRun: (Long) -> Unit, onOpenRun: (Long) -> Unit,
attention: List<AttentionEntry>,
onOpenAttention: () -> Unit,
) { ) {
val depth = selection.depth val depth = selection.depth
val onBack: () -> Unit = { onSelectionChange(backFrom(selection)) } val onBack: () -> Unit = { onSelectionChange(backFrom(selection)) }
@@ -70,6 +72,8 @@ internal fun PipelineDestination(
covered = covered, covered = covered,
wide = wide, wide = wide,
listState = listState, listState = listState,
attention = attention,
onOpenAttention = onOpenAttention,
) )
1 -> rememberPaneContent( 1 -> rememberPaneContent(
selection.itemId.takeIf { it != 0L }?.let { selection.itemId.takeIf { it != 0L }?.let {
@@ -92,6 +96,8 @@ internal fun PipelineDestination(
) )
}, },
covered = covered, covered = covered,
attention = attention,
onOpenAttention = onOpenAttention,
) )
} }
2 -> rememberPaneContent( 2 -> rememberPaneContent(
@@ -58,7 +58,6 @@ import net.awan.pipelines.data.transport.ConnectionState
import net.awan.pipelines.notify.NOTIFICATION_RATIONALE import net.awan.pipelines.notify.NOTIFICATION_RATIONALE
import net.awan.pipelines.notify.alertPermissionPrompt import net.awan.pipelines.notify.alertPermissionPrompt
import net.awan.pipelines.ui.chat.ChatScreen import net.awan.pipelines.ui.chat.ChatScreen
import net.awan.pipelines.ui.components.AttentionIndicator
import net.awan.pipelines.ui.components.AttentionSheet import net.awan.pipelines.ui.components.AttentionSheet
import net.awan.pipelines.ui.components.BottomStripInset import net.awan.pipelines.ui.components.BottomStripInset
import net.awan.pipelines.ui.components.ConnectionBanner import net.awan.pipelines.ui.components.ConnectionBanner
@@ -67,10 +66,8 @@ import net.awan.pipelines.ui.components.LocalPillBottomInset
import net.awan.pipelines.ui.components.MotionStandard import net.awan.pipelines.ui.components.MotionStandard
import net.awan.pipelines.ui.components.paneSafeArea import net.awan.pipelines.ui.components.paneSafeArea
import net.awan.pipelines.ui.components.spec import net.awan.pipelines.ui.components.spec
import net.awan.pipelines.ui.theme.ATTENTION_CHIP_RESERVE
import net.awan.pipelines.ui.theme.DESTINATION_PILL_RESERVE import net.awan.pipelines.ui.theme.DESTINATION_PILL_RESERVE
import net.awan.pipelines.ui.theme.SPACING_L import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_S
/** One destination the floating pill holds: its nav [route], the accessible [label] and its glyph. */ /** One destination the floating pill holds: its nav [route], the accessible [label] and its glyph. */
internal data class TopDestination(val route: String, val label: String, val icon: ImageVector) internal data class TopDestination(val route: String, val label: String, val icon: ImageVector)
@@ -348,6 +345,8 @@ fun PipelinesApp(
selection = pipelineSelection, selection = pipelineSelection,
onSelectionChange = { pipelineSelection = it }, onSelectionChange = { pipelineSelection = it },
listState = pipelineListState, listState = pipelineListState,
attention = attention,
onOpenAttention = { attentionOpen = true },
onOpenRun = { runId -> onOpenRun = { runId ->
runSelection = PaneSelection( runSelection = PaneSelection(
pane = MasterPane.Detail, pane = MasterPane.Detail,
@@ -368,6 +367,8 @@ fun PipelinesApp(
listState = runListState, listState = runListState,
decisionRequest = decisionRequest, decisionRequest = decisionRequest,
onDecisionRequestHandled = { decisionRequest = null }, onDecisionRequestHandled = { decisionRequest = null },
attention = attention,
onOpenAttention = { attentionOpen = true },
) )
} }
composable("chat") { composable("chat") {
@@ -398,7 +399,7 @@ fun PipelinesApp(
// Composed after the NavHost, so while the field is open Back (button // Composed after the NavHost, so while the field is open Back (button
// or gesture) dismisses the morph before any pane's own Back handler. // or gesture) dismisses the morph before any pane's own Back handler.
BackHandler(enabled = searchState.open) { dismissSearch() } BackHandler(enabled = searchState.open) { dismissSearch() }
// The results panel, the attention chip and the destination bar share // The results panel and destination bar share
// one bottom-anchored, inset-clearing column — the overlay layer, drawn // one bottom-anchored, inset-clearing column — the overlay layer, drawn
// above the content and never part of its layout. `paneSafeArea` // above the content and never part of its layout. `paneSafeArea`
// (WindowInsets.safeDrawing) is applied once here, so the pill clears the // (WindowInsets.safeDrawing) is applied once here, so the pill clears the
@@ -412,8 +413,7 @@ fun PipelinesApp(
// The overlay's resting place is the window width's in [destinationPillAlignment]: // The overlay's resting place is the window width's in [destinationPillAlignment]:
// horizontally centred on a narrow window, anchored to the bottom-right // horizontally centred on a narrow window, anchored to the bottom-right
// corner on a wide one. Its margin comes from the named [SPACING_L], so the // corner on a wide one. Its margin comes from the named [SPACING_L], so the
// corner placement adds no new number. That rule positions the pill; the // corner placement adds no new number.
// attention chip above it keeps its own bottom-right place at every width.
// While a bottom selector strip is up, the whole overlay is lifted by that // While a bottom selector strip is up, the whole overlay is lifted by that
// strip's measured height ([pillBottomOffset]), so the pill never overlaps it. // strip's measured height ([pillBottomOffset]), so the pill never overlaps it.
Column( Column(
@@ -441,15 +441,6 @@ fun PipelinesApp(
.padding(bottom = SPACING_L), .padding(bottom = SPACING_L),
) )
} }
// The attention chip is not part of the pill's placement rule: it
// keeps its own bottom-right resting place at every width (as it
// had before the pill became width-dependent), so only the pill
// follows [destinationPillAlignment].
AttentionIndicator(
entries = attention,
onClick = { attentionOpen = true },
modifier = Modifier.align(Alignment.End).padding(bottom = SPACING_S),
)
// The pill stands down while a conversation or run detail is open; // The pill stands down while a conversation or run detail is open;
// the search field it morphs into is unreachable there anyway (the // the search field it morphs into is unreachable there anyway (the
// field opens from the pill), so nothing is stranded by not drawing it. // field opens from the pill), so nothing is stranded by not drawing it.
@@ -537,8 +528,8 @@ internal fun destinationPillVisible(
): Boolean = !(currentRoute == CHAT_ROUTE && conversationOpen) && !runDetailOpen ): Boolean = !(currentRoute == CHAT_ROUTE && conversationOpen) && !runDetailOpen
/** /**
* Where the bottom overlay — the destination pill and the attention chip above it * Where the bottom destination pill rests in the window: horizontally centred on a
* — rests in the window: horizontally centred on a **narrow** window and anchored * **narrow** window and anchored
* to the bottom-right **corner** on a **wide** one. The overlay is drawn above the * to the bottom-right **corner** on a **wide** one. The overlay is drawn above the
* content and never takes layout space either way, so this is purely where it * content and never takes layout space either way, so this is purely where it
* sits. A pure function of the window width, so the one arrangement rule is * sits. A pure function of the window width, so the one arrangement rule is
@@ -561,8 +552,7 @@ internal fun contentPillPadding(pillVisible: Boolean): Dp = 0.dp
/** /**
* The trailing bottom space a scrollable screen keeps so its last row scrolls clear * The trailing bottom space a scrollable screen keeps so its last row scrolls clear
* of the floating bottom stack — the destination pill and the attention chip above * of the floating destination pill, built from the named [DESTINATION_PILL_RESERVE]
* it — built from the named [DESTINATION_PILL_RESERVE] and [ATTENTION_CHIP_RESERVE]
* while the pill is drawn, and none while it is hidden (an open conversation or a * while the pill is drawn, and none while it is hidden (an open conversation or a
* run detail, see [destinationPillVisible]) so a hidden pill * run detail, see [destinationPillVisible]) so a hidden pill
* leaves no empty band at the end of a list. Published to the content through * leaves no empty band at the end of a list. Published to the content through
@@ -574,7 +564,7 @@ internal fun contentPillPadding(pillVisible: Boolean): Dp = 0.dp
* the pill appears and disappears. * the pill appears and disappears.
*/ */
internal fun pillScrollInset(pillVisible: Boolean): Dp = internal fun pillScrollInset(pillVisible: Boolean): Dp =
if (pillVisible) DESTINATION_PILL_RESERVE + ATTENTION_CHIP_RESERVE else 0.dp if (pillVisible) DESTINATION_PILL_RESERVE else 0.dp
/** /**
* How far above the window's bottom the floating pill rests: its own [SPACING_L] * How far above the window's bottom the floating pill rests: its own [SPACING_L]
@@ -34,6 +34,8 @@ internal fun RunsDestination(
listState: LazyListState, listState: LazyListState,
decisionRequest: Long? = null, decisionRequest: Long? = null,
onDecisionRequestHandled: () -> Unit = {}, onDecisionRequestHandled: () -> Unit = {},
attention: List<AttentionEntry>,
onOpenAttention: () -> Unit,
) { ) {
val depth = selection.depth val depth = selection.depth
val onBack: () -> Unit = { onSelectionChange(backFrom(selection)) } val onBack: () -> Unit = { onSelectionChange(backFrom(selection)) }
@@ -83,6 +85,8 @@ internal fun RunsDestination(
covered = covered, covered = covered,
wide = wide, wide = wide,
listState = listState, listState = listState,
attention = attention,
onOpenAttention = onOpenAttention,
) )
1 -> rememberPaneContent( 1 -> rememberPaneContent(
selection.itemId.takeIf { it != 0L }?.let { it to selection.sectionIndex }, selection.itemId.takeIf { it != 0L }?.let { it to selection.sectionIndex },
@@ -110,6 +114,8 @@ internal fun RunsDestination(
covered = covered, covered = covered,
requestDecision = decisionRequest == itemId, requestDecision = decisionRequest == itemId,
onDecisionRequestHandled = onDecisionRequestHandled, onDecisionRequestHandled = onDecisionRequestHandled,
attention = attention,
onOpenAttention = onOpenAttention,
) )
} }
2 -> rememberPaneContent( 2 -> rememberPaneContent(
@@ -894,15 +894,45 @@ class ChatStore(
fun history(sessionId: String, messages: List<ChatMessage>, nextCursor: String = "", hasMore: Boolean = false) { fun history(sessionId: String, messages: List<ChatMessage>, nextCursor: String = "", hasMore: Boolean = false) {
update(sessionId) { update(sessionId) {
val existing = it.messages.associateBy { message -> message.id } val existing = it.messages.associateBy { message -> message.id }
// Operation identity remains valid after a live user event replaces
// local-* with the server's synthetic id. Index every user turn,
// not only optimistic records, so a later history read can replace
// that synthetic id with the provider's authoritative id.
val existingUserByOperation = it.messages
.asSequence()
.filter { message -> message.role == ChatProtocol.ROLE_USER && message.operationId.isNotBlank() }
.associateBy { message -> message.operationId }
val reconciledIds = messages.asSequence()
.mapNotNull { message -> existingUserByOperation[message.operationId]?.id }
.toSet()
val authoritativeMessages = messages.map { message ->
val local = existingUserByOperation[message.operationId]
if (local == null || message.role != ChatProtocol.ROLE_USER) {
message
} else {
// History is authoritative for identity and ordering, but it
// does not carry the phone's local attachment parts or live
// fields. Keep those fields on the same turn while replacing
// the temporary local id.
message.copy(
client = message.client.ifBlank { local.client },
parts = message.parts + local.parts.filter { localPart ->
message.parts.none { it.type == localPart.type && it.id == localPart.id } &&
(localPart.type == ChatProtocol.PART_FILE || localPart.type == ChatProtocol.PART_TEXT || localPart.type == ChatProtocol.PART_REASONING)
},
)
}
}
val baseline = it.historyBeforeLoad?.associateBy { message -> message.id } val baseline = it.historyBeforeLoad?.associateBy { message -> message.id }
val pageIds = messages.mapTo(mutableSetOf()) { message -> message.id } val pageIds = authoritativeMessages.mapTo(mutableSetOf()) { message -> message.id }
val firstOverlap = it.messages.indexOfFirst { message -> message.id in pageIds } val firstOverlap = it.messages.indexOfFirst { message -> message.id in pageIds }
val olderPrefix = when { val olderPrefix = when {
firstOverlap >= 0 -> it.messages.take(firstOverlap) firstOverlap >= 0 -> it.messages.take(firstOverlap)
it.historyBeforeLoad != null && !it.historyLoadOlder -> it.messages it.historyBeforeLoad != null && !it.historyLoadOlder -> it.messages
else -> emptyList() else -> emptyList()
} }
val merged = (olderPrefix + messages + it.messages).fold(LinkedHashMap<String, ChatMessage>()) { result, message -> val merged = (olderPrefix + authoritativeMessages + it.messages.filterNot { message -> message.id in reconciledIds })
.fold(LinkedHashMap<String, ChatMessage>()) { result, message ->
// A live event may have extended this message while the read was // A live event may have extended this message while the read was
// in flight. Preserve only that fold, not stale pre-request cache // in flight. Preserve only that fold, not stale pre-request cache
// which would otherwise hide text missed during a disconnect. // which would otherwise hide text missed during a disconnect.
@@ -1071,6 +1101,7 @@ class ChatStore(
sessionId: String, sessionId: String,
text: String, text: String,
attachments: List<ChatAttachment> = emptyList(), attachments: List<ChatAttachment> = emptyList(),
operationId: String = "",
): String? { ): String? {
var id: String? = null var id: String? = null
update(sessionId) { thread -> update(sessionId) { thread ->
@@ -1079,6 +1110,7 @@ class ChatStore(
id = id!!, id = id!!,
sessionId = sessionId, sessionId = sessionId,
role = ChatProtocol.ROLE_USER, role = ChatProtocol.ROLE_USER,
operationId = operationId,
parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, text = text)) + parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, text = text)) +
attachments.map { attachmentPart(it) }, attachments.map { attachmentPart(it) },
) )
@@ -1156,12 +1188,28 @@ class ChatStore(
val text = frame.part?.text.orEmpty() val text = frame.part?.text.orEmpty()
if (frame.messageId.isEmpty() || text.isEmpty()) return if (frame.messageId.isEmpty() || text.isEmpty()) return
update(frame.sessionId) { thread -> update(frame.sessionId) { thread ->
val optimistic = thread.messages.firstOrNull {
it.role == ChatProtocol.ROLE_USER &&
it.id.startsWith(LOCAL_MESSAGE_PREFIX) &&
frame.operationId.isNotBlank() && it.operationId == frame.operationId
}
if (optimistic != null) {
val replacement = optimistic.copy(id = frame.messageId, client = frame.client.ifBlank { optimistic.client })
return@update thread.copy(messages = thread.messages.map { if (it.id == optimistic.id) replacement else it })
}
// A replay can arrive after authoritative history has already
// replaced the optimistic id. Operation identity is a correlation
// key, not a second message id.
if (frame.operationId.isNotBlank() && thread.messages.any {
it.role == ChatProtocol.ROLE_USER && it.operationId == frame.operationId
}) return@update thread
if (thread.messages.any { it.id == frame.messageId }) return@update thread if (thread.messages.any { it.id == frame.messageId }) return@update thread
val message = ChatMessage( val message = ChatMessage(
id = frame.messageId, id = frame.messageId,
sessionId = frame.sessionId, sessionId = frame.sessionId,
role = ChatProtocol.ROLE_USER, role = ChatProtocol.ROLE_USER,
client = frame.client, client = frame.client,
operationId = frame.operationId,
parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, text = text)), parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, text = text)),
) )
thread.copy(messages = thread.messages + message) thread.copy(messages = thread.messages + message)
@@ -6,10 +6,11 @@ import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.NotificationsActive import androidx.compose.material.icons.filled.NotificationsActive
import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
@@ -25,10 +26,8 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.AttentionEntry import net.awan.pipelines.ui.AttentionEntry
import net.awan.pipelines.ui.AttentionKind import net.awan.pipelines.ui.AttentionKind
import net.awan.pipelines.ui.attentionHeadline
import net.awan.pipelines.ui.attentionDismissalSnapshot import net.awan.pipelines.ui.attentionDismissalSnapshot
import net.awan.pipelines.ui.theme.ICON_INLINE_DP import net.awan.pipelines.ui.theme.ICON_INLINE_DP
import net.awan.pipelines.ui.theme.SPACING_L import net.awan.pipelines.ui.theme.SPACING_L
@@ -52,43 +51,22 @@ internal fun attentionRunState(kind: AttentionKind): RunState = when (kind) {
AttentionKind.Failed -> RunState.Failed AttentionKind.Failed -> RunState.Failed
} }
/** /** The notifications action shared by the main and detail app bars. */
* The floating indicator: the count and the most important item, tappable to open
* the list. Hidden (draws nothing) when [entries] is empty, so it never becomes a
* permanent chrome element.
*/
@Composable @Composable
fun AttentionIndicator( fun AttentionAction(
entries: List<AttentionEntry>, entries: List<AttentionEntry>,
onClick: () -> Unit, onClick: () -> Unit,
modifier: Modifier = Modifier,
) { ) {
if (entries.isEmpty()) return IconButton(onClick = onClick) {
val scheme = MaterialTheme.colorScheme BadgedBox(badge = {
Surface( if (entries.isNotEmpty()) Badge { Text(entries.size.toString()) }
onClick = onClick, }) {
modifier = modifier,
shape = RoundedCornerShape(50),
color = scheme.errorContainer,
contentColor = scheme.onErrorContainer,
shadowElevation = 6.dp,
) {
Row(
modifier = Modifier.padding(horizontal = SPACING_M, vertical = SPACING_S),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
) {
Icon( Icon(
imageVector = Icons.Default.NotificationsActive, imageVector = Icons.Default.NotificationsActive,
contentDescription = null, contentDescription = if (entries.isEmpty()) "Notifications" else
"Notifications, ${entries.size} needing attention",
modifier = Modifier.size(ICON_INLINE_DP), modifier = Modifier.size(ICON_INLINE_DP),
) )
Text(
text = attentionHeadline(entries),
style = MaterialTheme.typography.labelLarge,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
} }
} }
} }
@@ -12,7 +12,6 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
@@ -41,7 +40,6 @@ import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.theme.DETAIL_MAX_WIDTH_DP
import net.awan.pipelines.ui.theme.ICON_RAIL_DP import net.awan.pipelines.ui.theme.ICON_RAIL_DP
import net.awan.pipelines.ui.theme.SPACING_L import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_M import net.awan.pipelines.ui.theme.SPACING_M
@@ -229,9 +227,9 @@ private fun RailTab(tab: DetailTab, selected: Boolean, onClick: () -> Unit) {
} }
/** /**
* Constrains a text tab's single scroll container to a comfortable reading width * Gives a tab body the complete safe-area width supplied by its page container.
* on a wide window (centred) instead of letting lines run edge to edge; on a * Internal content remains responsible for any narrower, purpose-specific layout
* narrow window the content simply fills the tab. * such as chat bubbles.
*/ */
@Composable @Composable
fun DetailTabBody( fun DetailTabBody(
@@ -239,18 +237,7 @@ fun DetailTabBody(
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
content: @Composable (Modifier) -> Unit, content: @Composable (Modifier) -> Unit,
) { ) {
if (wide) { content(modifier.fillMaxSize())
Box(modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) {
content(
Modifier
.fillMaxHeight()
.widthIn(max = DETAIL_MAX_WIDTH_DP.dp)
.fillMaxWidth(),
)
}
} else {
content(modifier.fillMaxSize())
}
} }
/** /**
@@ -63,6 +63,8 @@ import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_M import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_S import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XS import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.AttentionEntry
import net.awan.pipelines.ui.components.AttentionAction
import net.awan.pipelines.ui.theme.pipelinesText import net.awan.pipelines.ui.theme.pipelinesText
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@@ -79,6 +81,8 @@ fun PipelineDetailScreen(
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
wide: Boolean = false, wide: Boolean = false,
covered: Boolean = false, covered: Boolean = false,
attention: List<AttentionEntry> = emptyList(),
onOpenAttention: () -> Unit = {},
) { ) {
val state by vm.pipelineDetail.collectAsStateWithLifecycle() val state by vm.pipelineDetail.collectAsStateWithLifecycle()
val runsState by vm.runs.collectAsStateWithLifecycle() val runsState by vm.runs.collectAsStateWithLifecycle()
@@ -124,6 +128,7 @@ fun PipelineDetailScreen(
}, },
windowInsets = paneSafeArea().only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal), windowInsets = paneSafeArea().only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal),
actions = { actions = {
AttentionAction(attention, onOpenAttention)
IconButton(onClick = { vm.loadPipeline(pipelineId, version) }) { IconButton(onClick = { vm.loadPipeline(pipelineId, version) }) {
Icon(Icons.Default.Refresh, contentDescription = "Refresh pipeline") Icon(Icons.Default.Refresh, contentDescription = "Refresh pipeline")
} }
@@ -37,6 +37,8 @@ import java.time.OffsetDateTime
import java.time.ZoneId import java.time.ZoneId
import net.awan.pipelines.data.protocol.PipelineSummary import net.awan.pipelines.data.protocol.PipelineSummary
import net.awan.pipelines.ui.AppViewModel import net.awan.pipelines.ui.AppViewModel
import net.awan.pipelines.ui.AttentionEntry
import net.awan.pipelines.ui.components.AttentionAction
import net.awan.pipelines.ui.components.DetailTabBody import net.awan.pipelines.ui.components.DetailTabBody
import net.awan.pipelines.ui.components.EmptyState import net.awan.pipelines.ui.components.EmptyState
import net.awan.pipelines.ui.components.ErrorState import net.awan.pipelines.ui.components.ErrorState
@@ -74,6 +76,8 @@ fun PipelineListScreen(
covered: Boolean = false, covered: Boolean = false,
wide: Boolean = false, wide: Boolean = false,
listState: LazyListState, listState: LazyListState,
attention: List<AttentionEntry> = emptyList(),
onOpenAttention: () -> Unit = {},
) { ) {
val state by vm.pipelines.collectAsStateWithLifecycle() val state by vm.pipelines.collectAsStateWithLifecycle()
val runsState by vm.runs.collectAsStateWithLifecycle() val runsState by vm.runs.collectAsStateWithLifecycle()
@@ -151,6 +155,7 @@ fun PipelineListScreen(
title = { Text("Pipelines") }, title = { Text("Pipelines") },
windowInsets = paneSafeArea().only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal), windowInsets = paneSafeArea().only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal),
actions = { actions = {
AttentionAction(attention, onOpenAttention)
PipelineFilterControl( PipelineFilterControl(
filters = filters, filters = filters,
onName = { vm.setPipelineFilterName(it) }, onName = { vm.setPipelineFilterName(it) },
@@ -52,6 +52,8 @@ import net.awan.pipelines.ui.runIdentity
import net.awan.pipelines.ui.runLabel import net.awan.pipelines.ui.runLabel
import net.awan.pipelines.ui.theme.SPACING_L import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_S import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.AttentionEntry
import net.awan.pipelines.ui.components.AttentionAction
import net.awan.pipelines.ui.theme.pipelinesText import net.awan.pipelines.ui.theme.pipelinesText
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@@ -68,6 +70,8 @@ fun RunDetailScreen(
covered: Boolean = false, covered: Boolean = false,
requestDecision: Boolean = false, requestDecision: Boolean = false,
onDecisionRequestHandled: () -> Unit = {}, onDecisionRequestHandled: () -> Unit = {},
attention: List<AttentionEntry> = emptyList(),
onOpenAttention: () -> Unit = {},
) { ) {
val state by vm.runDetail.collectAsStateWithLifecycle() val state by vm.runDetail.collectAsStateWithLifecycle()
val runsState by vm.runs.collectAsStateWithLifecycle() val runsState by vm.runs.collectAsStateWithLifecycle()
@@ -177,6 +181,7 @@ fun RunDetailScreen(
}, },
windowInsets = paneSafeArea().only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal), windowInsets = paneSafeArea().only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal),
actions = { actions = {
AttentionAction(attention, onOpenAttention)
LiveBadge(runStream, Modifier.padding(end = SPACING_S)) LiveBadge(runStream, Modifier.padding(end = SPACING_S))
IconButton(onClick = { vm.loadRun(runId) }) { IconButton(onClick = { vm.loadRun(runId) }) {
Icon(Icons.Default.Refresh, contentDescription = "Refresh run") Icon(Icons.Default.Refresh, contentDescription = "Refresh run")
@@ -48,6 +48,8 @@ import java.time.format.DateTimeFormatter
import net.awan.pipelines.data.protocol.RunSummary import net.awan.pipelines.data.protocol.RunSummary
import net.awan.pipelines.data.protocol.UsageStats import net.awan.pipelines.data.protocol.UsageStats
import net.awan.pipelines.ui.AppViewModel import net.awan.pipelines.ui.AppViewModel
import net.awan.pipelines.ui.AttentionEntry
import net.awan.pipelines.ui.components.AttentionAction
import net.awan.pipelines.ui.components.DetailTabBody import net.awan.pipelines.ui.components.DetailTabBody
import net.awan.pipelines.ui.components.EmptyState import net.awan.pipelines.ui.components.EmptyState
import net.awan.pipelines.ui.components.ErrorState import net.awan.pipelines.ui.components.ErrorState
@@ -98,6 +100,8 @@ fun RunHistoryScreen(
covered: Boolean = false, covered: Boolean = false,
wide: Boolean = false, wide: Boolean = false,
listState: LazyListState, listState: LazyListState,
attention: List<AttentionEntry> = emptyList(),
onOpenAttention: () -> Unit = {},
) { ) {
val state by vm.runs.collectAsStateWithLifecycle() val state by vm.runs.collectAsStateWithLifecycle()
val runStream by vm.runStream.collectAsStateWithLifecycle() val runStream by vm.runStream.collectAsStateWithLifecycle()
@@ -153,6 +157,7 @@ fun RunHistoryScreen(
title = { Text(if (filterPipelineId == null) "Runs" else "Runs for this pipeline") }, title = { Text(if (filterPipelineId == null) "Runs" else "Runs for this pipeline") },
windowInsets = paneSafeArea().only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal), windowInsets = paneSafeArea().only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal),
actions = { actions = {
AttentionAction(attention, onOpenAttention)
RunFilterControl( RunFilterControl(
filters = filters, filters = filters,
pipelines = pipelineOptions, pipelines = pipelineOptions,
@@ -84,24 +84,11 @@ internal val MIN_COVERED_PANE_WIDTH_DP = 112.dp
*/ */
internal val DESTINATION_PILL_RESERVE = 88.dp internal val DESTINATION_PILL_RESERVE = 88.dp
/** // ---- Detail rail (ui/components/DetailTabs.kt) ------------------------------
* Bottom space the floating attention chip occupies above the destination pill:
* the chip's own height (its single label line plus its vertical padding) plus the
* gap below it. Added to a scrollable's trailing space alongside
* [DESTINATION_PILL_RESERVE] while the pill is drawn, so the chip can never be laid
* out over a row, a field or a button and the content does not jump as it appears
* and clears.
*/
internal val ATTENTION_CHIP_RESERVE = SPACING_XXL + SPACING_M
// ---- Detail rail and max content width (ui/components/DetailTabs.kt) -------
/** The always-visible wide section rail's width (icons with labels). */ /** The always-visible wide section rail's width (icons with labels). */
internal const val WIDE_RAIL_WIDTH_DP = 200 internal const val WIDE_RAIL_WIDTH_DP = 200
/** Comfortable max text width for a tab body on a wide window. */
const val DETAIL_MAX_WIDTH_DP = 840
// ---- Workflow graph geometry (ui/graph/WorkflowGraph.kt) ------------------- // ---- Workflow graph geometry (ui/graph/WorkflowGraph.kt) -------------------
// The graph's node, edge and legend geometry. These are named here like every // The graph's node, edge and legend geometry. These are named here like every
// other app dimension so the graph file imports them instead of writing raw dp // other app dimension so the graph file imports them instead of writing raw dp
@@ -3,7 +3,6 @@ package net.awan.pipelines.ui
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.theme.ATTENTION_CHIP_RESERVE
import net.awan.pipelines.ui.theme.DESTINATION_PILL_RESERVE import net.awan.pipelines.ui.theme.DESTINATION_PILL_RESERVE
import net.awan.pipelines.ui.theme.SPACING_L import net.awan.pipelines.ui.theme.SPACING_L
import org.junit.Assert.assertEquals import org.junit.Assert.assertEquals
@@ -146,11 +145,11 @@ class PipelinesNavTest {
@Test @Test
fun theScrollInsetTracksTheDrawnPillSoAListNeitherJumpsNorHidesItsLastRow() { fun theScrollInsetTracksTheDrawnPillSoAListNeitherJumpsNorHidesItsLastRow() {
// Drawn: a scrollable keeps the named pill + attention-chip space at the // Drawn: a scrollable keeps the named pill space at the end of its own
// end of its own scroll content and its last row scrolls clear of the whole // scroll content and its last row scrolls clear of the floating pill. Hidden: no clearance,
// floating bottom stack. Hidden: no clearance, so there is no empty band // so there is no empty band
// where the pill used to be. // where the pill used to be.
val drawnInset = DESTINATION_PILL_RESERVE + ATTENTION_CHIP_RESERVE val drawnInset = DESTINATION_PILL_RESERVE
assertDp(drawnInset.value, pillScrollInset(pillVisible = true)) assertDp(drawnInset.value, pillScrollInset(pillVisible = true))
assertDp(0f, pillScrollInset(pillVisible = false)) assertDp(0f, pillScrollInset(pillVisible = false))
// One predicate drives both the drawing and the clearance, so the space can // One predicate drives both the drawing and the clearance, so the space can
@@ -1,6 +1,7 @@
package net.awan.pipelines.ui.chat package net.awan.pipelines.ui.chat
import net.awan.pipelines.data.protocol.ChatEventFrame import net.awan.pipelines.data.protocol.ChatEventFrame
import net.awan.pipelines.data.PipelinesRepository
import net.awan.pipelines.data.protocol.ChatMessage import net.awan.pipelines.data.protocol.ChatMessage
import net.awan.pipelines.data.protocol.ChatPart import net.awan.pipelines.data.protocol.ChatPart
import net.awan.pipelines.data.protocol.ChatPermissionFrame import net.awan.pipelines.data.protocol.ChatPermissionFrame
@@ -317,6 +318,97 @@ class MultiChatStateTest {
assertEquals(2, store.value.thread("a")!!.messages.size) assertEquals(2, store.value.thread("a")!!.messages.size)
} }
@Test
fun canonicalUserEventReplacesOptimisticTurnByOperationIdentity() {
val store = ChatStore()
store.open(session("a"))
val local = store.appendLocalUserMessage("a", "X", operationId = "op-x")!!
store.event(ChatEventFrame(
sessionId = "a",
messageId = "native-x",
kind = ChatProtocol.EVENT_USER,
operationId = "op-x",
client = "Phone",
part = ChatPart(type = ChatProtocol.PART_TEXT, text = "X"),
))
val messages = store.value.thread("a")!!.messages
assertEquals(listOf("native-x"), messages.map { it.id })
assertEquals("Phone", messages.single().client)
assertEquals("op-x", messages.single().operationId)
assertFalse(messages.any { it.id == local })
}
@Test
fun delayedHistoryReconcilesOptimisticTurnAndKeepsDistinctRepeatedText() {
val store = ChatStore()
store.open(session("a"))
val attachmentUri = "content://x"
store.appendLocalUserMessage("a", "X", listOf(ChatAttachment(uri = attachmentUri, name = "x.txt", mime = "text/plain")), "op-x")
// The sender sees the live event before the provider history catches up.
store.event(ChatEventFrame(
sessionId = "a", messageId = "native-x", kind = ChatProtocol.EVENT_USER,
operationId = "op-x", client = "Phone", part = ChatPart(type = ChatProtocol.PART_TEXT, text = "X"),
))
// History replaces the synthetic event id, but must keep the same turn
// (including its attachment) rather than appending a second X.
store.history("a", listOf(ChatMessage(
id = "native-history-x", sessionId = "a", role = ChatProtocol.ROLE_USER,
operationId = "op-x", client = "Phone",
parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, text = "X")),
)))
// A different client sends Y after the history read.
store.event(ChatEventFrame(
sessionId = "a", messageId = "native-y", kind = ChatProtocol.EVENT_USER,
operationId = "op-y", client = "Computer", part = ChatPart(type = ChatProtocol.PART_TEXT, text = "Y"),
))
// The delayed original X is an idempotent delivery, not another turn.
store.event(ChatEventFrame(
sessionId = "a", messageId = "native-x", kind = ChatProtocol.EVENT_USER,
operationId = "op-x", client = "Phone", part = ChatPart(type = ChatProtocol.PART_TEXT, text = "X"),
))
// A later, genuinely different X remains a separate message.
store.event(ChatEventFrame(
sessionId = "a", messageId = "native-x-2", kind = ChatProtocol.EVENT_USER,
operationId = "op-x-2", client = "Phone", part = ChatPart(type = ChatProtocol.PART_TEXT, text = "X"),
))
val messages = store.value.thread("a")!!.messages
assertEquals(listOf("native-history-x", "native-y", "native-x-2"), messages.map { it.id })
assertEquals(listOf("X", "Y", "X"), messages.map { it.parts.first().text })
assertEquals(listOf("Phone", "Computer", "Phone"), messages.map { it.client })
assertEquals(listOf("op-x", "op-y", "op-x-2"), messages.map { it.operationId })
assertEquals(attachmentUri, messages.first().parts.firstOrNull { it.type == ChatProtocol.PART_FILE }?.uri)
}
@Test
fun emptyOperationDoesNotInventASharedNativeMessageId() {
assertEquals("", PipelinesRepository.nativeMessageId(""))
assertEquals("", PipelinesRepository.nativeMessageId(" "))
assertEquals("msg_opx", PipelinesRepository.nativeMessageId("op-x"))
}
@Test
fun historyOperationIdentityReplacesLocalIdWithoutDroppingAttachment() {
val store = ChatStore()
store.open(session("a"))
store.appendLocalUserMessage(
"a", "X",
listOf(ChatAttachment(uri = "content://x", name = "x.txt", mime = "text/plain")),
"op-x",
)
store.history("a", listOf(ChatMessage(
id = "native-x", sessionId = "a", role = ChatProtocol.ROLE_USER,
client = "Phone", operationId = "op-x",
parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, text = "X")),
)))
val message = store.value.thread("a")!!.messages.single()
assertEquals("native-x", message.id)
assertEquals("op-x", message.operationId)
assertTrue(message.parts.any { it.type == ChatProtocol.PART_FILE && it.uri == "content://x" })
}
@Test @Test
fun remoteAnswerClearsTheApprovalCard() { fun remoteAnswerClearsTheApprovalCard() {
val store = ChatStore() val store = ChatStore()
@@ -1,6 +1,7 @@
package net.awan.pipelines.ui.components package net.awan.pipelines.ui.components
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import java.io.File
import org.junit.Assert.assertEquals import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue import org.junit.Assert.assertTrue
@@ -75,4 +76,17 @@ class DetailTabsTest {
state.toggle("evidence-4") state.toggle("evidence-4")
assertFalse(state.isExpanded("evidence-4")) assertFalse(state.isExpanded("evidence-4"))
} }
@Test
fun detailTabBodyUsesThePageSafeAreaWithoutAnArtificialWideCap() {
val source = File(
System.getProperty("user.dir"),
"src/main/java/net/awan/pipelines/ui/components/DetailTabs.kt",
).readText()
assertTrue(source.contains("content(modifier.fillMaxSize())"))
assertFalse(source.contains("DETAIL_MAX_WIDTH_DP"))
assertFalse(source.contains("widthIn(max"))
assertFalse(source.contains("contentAlignment = Alignment.TopCenter"))
}
} }
@@ -0,0 +1,10 @@
# Action-bar notification access
The in-app attention entry point moved from the floating bottom indicator into the
existing main/detail app bars. The action remains present when the destination pill
is hidden, and its badge uses the existing attention list count; the attention sheet
and permission behavior are unchanged.
The packaged OpenCode skill references that describe the old floating attention
indicator may be stale. The manual `docs-fold` pipeline should fold this note into
the shared documentation and references; this item does not edit those shared files.
@@ -0,0 +1,7 @@
# Cross-client message reconciliation
The chat wire contract now carries a durable prompt operation identity through the
optimistic Android message and the server's cross-client user event. Existing
shared README/topic and packaged skill references that describe user echoes as
connection-local are stale; `docs-fold` should update them. This item does not
edit shared documentation.
+24
View File
@@ -0,0 +1,24 @@
# Full-width shared page body
## What changed
`android/app/src/main/java/net/awan/pipelines/ui/components/DetailTabs.kt` no longer
centres wide `DetailTabBody` content inside the artificial `DETAIL_MAX_WIDTH_DP` cap.
The body now passes its page modifier through at the available safe-area width for
Runs, Pipelines, Chats and Settings. Insets, scroll padding and narrower internal
layouts (including chat bubbles) remain owned by their respective callers.
The wide navigation rail and pane-stack policy were not changed. The obsolete
`DETAIL_MAX_WIDTH_DP` token was removed from `ui/theme/Dimens.kt`; no dependency or
server change is involved.
`DetailTabsTest` pins the full-width body implementation and guards against restoring
the centered cap. Device rendering on compact and wide windows remains for the UI
review stage.
## Documentation now stale (for `docs-fold`)
- `android/README.md` near the detail-tabs geometry/token description still names
`DETAIL_MAX_WIDTH_DP` as the wide page-body cap. Remove that token from the
description and state that shared page bodies use the available safe-area width;
keep any separate navigation-rail width description unchanged.
+10
View File
@@ -82,6 +82,13 @@ func (c *Chat) call(ctx context.Context, method, path string, body any) ([]byte,
// (authenticated, bounded, directory-scoped). The endpoint returns the inbox // (authenticated, bounded, directory-scoped). The endpoint returns the inbox
// envelope immediately; the reply arrives on Stream. // envelope immediately; the reply arrives on Stream.
func (c *Chat) Prompt(ctx context.Context, id, text string) error { func (c *Chat) Prompt(ctx context.Context, id, text string) error {
return c.PromptWithMessageID(ctx, id, text, "")
}
// PromptWithMessageID forwards the caller's canonical message id to OpenCode.
// OpenCode persists this id in history, which is the only safe bridge between
// the live user echo and an authoritative history page.
func (c *Chat) PromptWithMessageID(ctx context.Context, id, text, messageID string) error {
if !sessionID.MatchString(id) { if !sessionID.MatchString(id) {
return fmt.Errorf("invalid OpenCode session id") return fmt.Errorf("invalid OpenCode session id")
} }
@@ -92,6 +99,9 @@ func (c *Chat) Prompt(ctx context.Context, id, text string) error {
// the same "text" field, so one shape works on both backends without a // the same "text" field, so one shape works on both backends without a
// second request format. // second request format.
body := map[string]any{"text": text} body := map[string]any{"text": text}
if messageID != "" {
body["id"] = messageID
}
if _, err := c.call(ctx, "post", "/api/session/"+id+"/prompt", body); err != nil { if _, err := c.call(ctx, "post", "/api/session/"+id+"/prompt", body); err != nil {
return err return err
} }
+3 -2
View File
@@ -782,7 +782,7 @@ func TestChatV1ConnectionDrivesThroughCall(t *testing.T) {
chat := NewChat(&Connection{Backend: "v1", URL: srv.URL, Directory: "/repo", models: map[string]map[string]string{}, responses: map[string][]byte{}}) chat := NewChat(&Connection{Backend: "v1", URL: srv.URL, Directory: "/repo", models: map[string]map[string]string{}, responses: map[string][]byte{}})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel() defer cancel()
if err := chat.Prompt(ctx, "ses_1", "hello"); err != nil { if err := chat.PromptWithMessageID(ctx, "ses_1", "hello", "msg_canonical"); err != nil {
t.Fatalf("prompt: %v", err) t.Fatalf("prompt: %v", err)
} }
if !sawPrompt { if !sawPrompt {
@@ -792,6 +792,7 @@ func TestChatV1ConnectionDrivesThroughCall(t *testing.T) {
// V2 `parts` shape and the v1 translation has to preserve it, or the native // V2 `parts` shape and the v1 translation has to preserve it, or the native
// serve process receives an empty prompt. // serve process receives an empty prompt.
var sent struct { var sent struct {
ID string `json:"id"`
Parts []struct { Parts []struct {
Type string `json:"type"` Type string `json:"type"`
Text string `json:"text"` Text string `json:"text"`
@@ -800,7 +801,7 @@ func TestChatV1ConnectionDrivesThroughCall(t *testing.T) {
if err := json.Unmarshal([]byte(promptBody), &sent); err != nil { if err := json.Unmarshal([]byte(promptBody), &sent); err != nil {
t.Fatalf("prompt body: %v (%s)", err, promptBody) t.Fatalf("prompt body: %v (%s)", err, promptBody)
} }
if len(sent.Parts) != 1 || sent.Parts[0].Type != protocol.ChatPartText || sent.Parts[0].Text != "hello" { if sent.ID != "msg_canonical" || len(sent.Parts) != 1 || sent.Parts[0].Type != protocol.ChatPartText || sent.Parts[0].Text != "hello" {
t.Fatalf("prompt text not carried through the v1 translation: %s", promptBody) t.Fatalf("prompt text not carried through the v1 translation: %s", promptBody)
} }
var got []protocol.ChatEventFrame var got []protocol.ChatEventFrame
+19
View File
@@ -64,6 +64,25 @@ func TestChatV2PromptShapeAndAuth(t *testing.T) {
} }
} }
func TestChatV2PromptWithMessageID(t *testing.T) {
var body map[string]string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatal(err)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":{"id":"msg_canonical","sessionID":"ses_1","type":"user"}}`))
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
if err := chat.PromptWithMessageID(context.Background(), "ses_1", "same text", "msg_canonical"); err != nil {
t.Fatal(err)
}
if body["id"] != "msg_canonical" || body["text"] != "same text" {
t.Fatalf("prompt body = %+v", body)
}
}
// TestChatStreamRealV2Shapes replays the exact event frames the installed 2.0.20 // TestChatStreamRealV2Shapes replays the exact event frames the installed 2.0.20
// service emitted on /api/event during a live turn (captured, not documented): // service emitted on /api/event during a live turn (captured, not documented):
// a step start, token text delta, usage and a step end whose data carries no // a step start, token text delta, usage and a step end whose data carries no
+4
View File
@@ -195,6 +195,7 @@ func (c *Connection) Call(ctx context.Context, method, path string, body any) ([
var request struct { var request struct {
Prompt string `json:"prompt"` Prompt string `json:"prompt"`
Text string `json:"text"` Text string `json:"text"`
ID string `json:"id"`
Format json.RawMessage `json:"format"` Format json.RawMessage `json:"format"`
Parts []struct { Parts []struct {
Text string `json:"text"` Text string `json:"text"`
@@ -219,6 +220,9 @@ func (c *Connection) Call(ctx context.Context, method, path string, body any) ([
} }
} }
payload := map[string]any{"model": c.models[id], "parts": []map[string]string{{"type": "text", "text": text}}} payload := map[string]any{"model": c.models[id], "parts": []map[string]string{{"type": "text", "text": text}}}
if request.ID != "" {
payload["id"] = request.ID
}
if len(request.Format) > 0 { if len(request.Format) > 0 {
supported, err := c.supportsFormat(ctx, request.Format) supported, err := c.supportsFormat(ctx, request.Format)
if err != nil { if err != nil {
+16 -9
View File
@@ -224,12 +224,17 @@ type ChatHistoryPage struct {
// message; the server sanitises it and falls back to a generic label when it is // message; the server sanitises it and falls back to a generic label when it is
// blank. // blank.
type ChatPromptRequest struct { type ChatPromptRequest struct {
SessionID string `json:"session_id"` SessionID string `json:"session_id"`
Text string `json:"text"` Text string `json:"text"`
Model string `json:"model,omitempty"` Model string `json:"model,omitempty"`
Agent string `json:"agent,omitempty"` Agent string `json:"agent,omitempty"`
Files []string `json:"files,omitempty"` Files []string `json:"files,omitempty"`
Client string `json:"client,omitempty"` Client string `json:"client,omitempty"`
OperationID string `json:"operation_id,omitempty"`
// NativeMessageID is the caller-supplied OpenCode message identity. It is
// sent with the prompt so history can be reconciled without guessing from
// text, time, order or page boundaries.
NativeMessageID string `json:"native_message_id,omitempty"`
} }
// ChatMessage is one stored turn returned by chat_messages. A user turn is a // ChatMessage is one stored turn returned by chat_messages. A user turn is a
@@ -245,8 +250,9 @@ type ChatMessage struct {
// Client is the sending device's label on a user turn the server echoed, so a // Client is the sending device's label on a user turn the server echoed, so a
// resumed transcript still says who sent the message. It is empty on an // resumed transcript still says who sent the message. It is empty on an
// assistant turn. // assistant turn.
Client string `json:"client,omitempty"` Client string `json:"client,omitempty"`
Parts []ChatPart `json:"parts"` OperationID string `json:"operation_id,omitempty"`
Parts []ChatPart `json:"parts"`
} }
// ChatDeltaPartID is the stable part id an incremental text or reasoning delta // ChatDeltaPartID is the stable part id an incremental text or reasoning delta
@@ -334,7 +340,8 @@ type ChatEventFrame struct {
Shell *ChatShell `json:"shell,omitempty"` Shell *ChatShell `json:"shell,omitempty"`
// Client is the sending device's label on a user frame (ChatEventUser), so a // Client is the sending device's label on a user frame (ChatEventUser), so a
// transcript can say who sent the message. It is empty on assistant frames. // transcript can say who sent the message. It is empty on assistant frames.
Client string `json:"client,omitempty"` Client string `json:"client,omitempty"`
OperationID string `json:"operation_id,omitempty"`
} }
// ChatStep is a progress marker for the current step of a turn. // ChatStep is a progress marker for the current step of a turn.
+4
View File
@@ -42,6 +42,10 @@ type chatBroker interface {
Reply(ctx context.Context, request protocol.ChatReplyRequest) error Reply(ctx context.Context, request protocol.ChatReplyRequest) error
} }
type chatPromptWithMessageID interface {
PromptWithMessageID(context.Context, string, string, string) error
}
type chatShellOutputReader interface { type chatShellOutputReader interface {
ShellOutput(ctx context.Context, query protocol.ChatShellOutputQuery) (protocol.ChatShellOutputPage, error) ShellOutput(ctx context.Context, query protocol.ChatShellOutputQuery) (protocol.ChatShellOutputPage, error)
} }
+1
View File
@@ -26,6 +26,7 @@ func handleChatMessages(ctx context.Context, request protocol.Message, broker ch
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return return
} }
page.Messages = hub.reconcileHistory(query.SessionID, page.Messages)
response.ChatMessages = page.Messages // legacy peers keep working. response.ChatMessages = page.Messages // legacy peers keep working.
response.ChatHistory = &page response.ChatHistory = &page
_ = write(response) _ = write(response)
+43 -6
View File
@@ -55,11 +55,12 @@ type chatPart struct {
// are carried for a user turn the server echoed (a prompt another client sent), // are carried for a user turn the server echoed (a prompt another client sent),
// so a resumed transcript still says who sent it. // so a resumed transcript still says who sent it.
type chatMessage struct { type chatMessage struct {
id string id string
role string role string
client string client string
order []string operationID string
parts map[string]*chatPart order []string
parts map[string]*chatPart
} }
type chatTurn struct { type chatTurn struct {
@@ -168,12 +169,15 @@ func (h *chatHub) applyLocked(frame protocol.ChatEventFrame) {
role = protocol.ChatRoleUser role = protocol.ChatRoleUser
client = frame.Client client = frame.Client
} }
message = &chatMessage{id: frame.MessageID, role: role, client: client, parts: map[string]*chatPart{}} message = &chatMessage{id: frame.MessageID, role: role, client: client, operationID: frame.OperationID, parts: map[string]*chatPart{}}
turn.order = append(turn.order, frame.MessageID) turn.order = append(turn.order, frame.MessageID)
turn.messages[frame.MessageID] = message turn.messages[frame.MessageID] = message
} else if message.client == "" && frame.Kind == protocol.ChatEventUser { } else if message.client == "" && frame.Kind == protocol.ChatEventUser {
message.client = frame.Client message.client = frame.Client
} }
if message.operationID == "" && frame.Kind == protocol.ChatEventUser {
message.operationID = frame.OperationID
}
switch frame.Kind { switch frame.Kind {
case protocol.ChatEventUser: case protocol.ChatEventUser:
if frame.Part == nil || frame.Part.ID == "" || frame.Part.Text == "" || turn.overflow { if frame.Part == nil || frame.Part.ID == "" || frame.Part.Text == "" || turn.overflow {
@@ -448,6 +452,7 @@ func (h *chatHub) snapshot(sessionID string) []protocol.ChatMessage {
out.Role = message.role out.Role = message.role
} }
out.Client = message.client out.Client = message.client
out.OperationID = message.operationID
for _, partID := range message.order { for _, partID := range message.order {
if part, ok := message.parts[partID]; ok { if part, ok := message.parts[partID]; ok {
piece := part.part piece := part.part
@@ -460,6 +465,38 @@ func (h *chatHub) snapshot(sessionID string) []protocol.ChatMessage {
return messages return messages
} }
// reconcileHistory applies only the explicit native-id mapping established by a
// caller-supplied prompt. It never infers identity from text, timestamps,
// position, ordering or page boundaries.
func (h *chatHub) reconcileHistory(sessionID string, messages []protocol.ChatMessage) []protocol.ChatMessage {
h.mu.Lock()
defer h.mu.Unlock()
turn := h.turns[sessionID]
if turn == nil {
return messages
}
byNativeID := make(map[string]*chatMessage)
for _, message := range turn.messages {
if message.role == protocol.ChatRoleUser && message.id != "" && message.operationID != "" {
byNativeID[message.id] = message
}
}
if len(byNativeID) == 0 {
return messages
}
out := make([]protocol.ChatMessage, len(messages))
copy(out, messages)
for i := range out {
if live := byNativeID[out[i].ID]; live != nil {
out[i].OperationID = live.operationID
if out[i].Client == "" {
out[i].Client = live.client
}
}
}
return out
}
// shellSnapshot returns the session's still-running shells, in the order they // shellSnapshot returns the session's still-running shells, in the order they
// started, so a client attaching to the session's stream can be re-synced the // started, so a client attaching to the session's stream can be re-synced the
// background processes it cannot have seen. It is the shell half of the resume // background processes it cannot have seen. It is the shell half of the resume
+14 -6
View File
@@ -100,10 +100,12 @@ func (s *chatSub) close() {
// request id; write is kept either way so a later broker failure is still // request id; write is kept either way so a later broker failure is still
// reported to the client that sent it. // reported to the client that sent it.
type chatQueuedPrompt struct { type chatQueuedPrompt struct {
text string text string
requestID string operationID string
write func(protocol.Message) error nativeID string
acked bool requestID string
write func(protocol.Message) error
acked bool
} }
type chatObservation struct { type chatObservation struct {
@@ -658,8 +660,14 @@ func (h *chatHub) runTurn(room *chatRoom, p *chatQueuedPrompt, done chan struct{
return return
} }
} }
if err := broker.Prompt(room.ctx, room.sessionID, p.text); err != nil { var promptErr error
h.failPrompt(room, p, err) if withID, ok := broker.(chatPromptWithMessageID); ok {
promptErr = withID.PromptWithMessageID(room.ctx, room.sessionID, p.text, p.nativeID)
} else {
promptErr = broker.Prompt(room.ctx, room.sessionID, p.text)
}
if promptErr != nil {
h.failPrompt(room, p, promptErr)
h.endRoomTurn(room) h.endRoomTurn(room)
return return
} }
+14 -8
View File
@@ -54,16 +54,22 @@ func handleChatPrompt(ctx context.Context, request protocol.Message, broker chat
// The user turn every *other* client sees, carrying the sender's label. The // The user turn every *other* client sees, carrying the sender's label. The
// sender's own client appended it locally, so it is excluded below. // sender's own client appended it locally, so it is excluded below.
userFrame := protocol.ChatEventFrame{ userFrame := protocol.ChatEventFrame{
SessionID: sessionID, SessionID: sessionID,
MessageID: hub.nextUserMessageID(), MessageID: prompt.NativeMessageID,
Kind: protocol.ChatEventUser, Kind: protocol.ChatEventUser,
Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: prompt.Text}, Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: prompt.Text},
Client: sub.label, Client: sub.label,
OperationID: prompt.OperationID,
}
if userFrame.MessageID == "" {
userFrame.MessageID = hub.nextUserMessageID()
} }
queued, refused := hub.submitPrompt(sessionID, &chatQueuedPrompt{ queued, refused := hub.submitPrompt(sessionID, &chatQueuedPrompt{
text: prompt.Text, text: prompt.Text,
requestID: request.ID, operationID: prompt.OperationID,
write: write, nativeID: userFrame.MessageID,
requestID: request.ID,
write: write,
}) })
if refused { if refused {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " already has the maximum number of prompts queued"}) _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " already has the maximum number of prompts queued"})
+98
View File
@@ -948,6 +948,104 @@ func TestChatHubKeepsMessagesSeparate(t *testing.T) {
} }
} }
// OpenCode history exposes native message ids but no prompt operation id. The
// broker must therefore leave partial, reordered, older and overlapping pages
// untouched rather than inventing a positional identity mapping.
func TestChatHubHistoryDoesNotInventOperationIdentity(t *testing.T) {
hub := newChatHub()
page := []protocol.ChatMessage{
{ID: "history-y", Role: protocol.ChatRoleUser, OperationID: "provider-value"},
{ID: "history-x", Role: protocol.ChatRoleUser},
}
got := hub.reconcileHistory("ses_1", page)
if len(got) != len(page) || got[0].ID != "history-y" || got[0].OperationID != "provider-value" || got[1].OperationID != "" {
t.Fatalf("history changed without a canonical provider mapping: %+v", got)
}
}
func TestChatHubHistoryMapsOnlyCanonicalNativeIdentity(t *testing.T) {
hub := newChatHub()
hub.apply(protocol.ChatEventFrame{
SessionID: "ses_1", MessageID: "msg_x", Kind: protocol.ChatEventUser,
Client: "Phone", OperationID: "op_x",
Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: "same"},
})
hub.apply(protocol.ChatEventFrame{
SessionID: "ses_1", MessageID: "msg_y", Kind: protocol.ChatEventUser,
Client: "Laptop", OperationID: "op_y",
Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: "same"},
})
got := hub.reconcileHistory("ses_1", []protocol.ChatMessage{
{ID: "msg_y", Role: protocol.ChatRoleUser},
{ID: "unrelated", Role: protocol.ChatRoleUser, Parts: []protocol.ChatPart{{Text: "same"}}},
{ID: "msg_x", Role: protocol.ChatRoleUser},
})
if got[0].OperationID != "op_y" || got[2].OperationID != "op_x" || got[1].OperationID != "" {
t.Fatalf("history identity mapping = %+v", got)
}
}
// TestChatMessagesReconcilesProviderPagesThroughTheHandler exercises the normal
// history path, rather than calling reconcileHistory alone. The provider fixture
// deliberately returns partial, reordered, older and overlapping pages (including
// equal timestamps); only the explicit native ids may restore operation identity.
func TestChatMessagesReconcilesProviderPagesThroughTheHandler(t *testing.T) {
hub := newChatHub()
for _, turn := range []struct {
id, operation, client string
}{
{"msg_x", "op_x", "Phone"},
{"msg_y", "op_y", "Computer"},
} {
hub.apply(protocol.ChatEventFrame{
SessionID: "ses_1", MessageID: turn.id, Kind: protocol.ChatEventUser,
OperationID: turn.operation, Client: turn.client,
Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: turn.operation},
})
}
pages := []struct {
name string
messages []protocol.ChatMessage
}{
{"partial-reordered", []protocol.ChatMessage{
{ID: "msg_y", Role: protocol.ChatRoleUser, CreatedAt: 10},
{ID: "msg_x", Role: protocol.ChatRoleUser, CreatedAt: 10},
}},
{"older", []protocol.ChatMessage{
{ID: "msg_x", Role: protocol.ChatRoleUser, CreatedAt: 10},
}},
{"overlap-reconnect", []protocol.ChatMessage{
{ID: "msg_y", Role: protocol.ChatRoleUser, CreatedAt: 10},
{ID: "unrelated", Role: protocol.ChatRoleUser, CreatedAt: 10},
}},
}
for _, page := range pages {
broker := scriptedChat()
broker.messages = page.messages
var response protocol.Message
handleChatMessages(context.Background(), protocol.Message{
Type: protocol.ChatMessages, ID: page.name,
ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"},
}, broker, hub, func(message protocol.Message) error {
response = message
return nil
})
if response.Type != protocol.ChatMessages || response.ChatHistory == nil {
t.Fatalf("%s response = %+v", page.name, response)
}
for _, message := range response.ChatHistory.Messages {
want := map[string]string{"msg_x": "op_x", "msg_y": "op_y"}[message.ID]
if want != "" && message.OperationID != want {
t.Fatalf("%s message %q operation = %q, want %q", page.name, message.ID, message.OperationID, want)
}
if message.ID == "unrelated" && message.OperationID != "" {
t.Fatalf("%s invented identity for unrelated message: %+v", page.name, message)
}
}
}
}
// TestChatHubChargesToolStateBytes pins the retained-state cap: a tool part's // TestChatHubChargesToolStateBytes pins the retained-state cap: a tool part's
// input/content bytes count against it, and an upsert that would exceed the cap // input/content bytes count against it, and an upsert that would exceed the cap
// is dropped with the overflow diagnostic rather than growing memory. // is dropped with the overflow diagnostic rather than growing memory.