diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt index 98e6501a..7ac1a3eb 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt @@ -845,16 +845,20 @@ class ChatStore( fun history(sessionId: String, messages: List, nextCursor: String = "", hasMore: Boolean = false) { update(sessionId) { val existing = it.messages.associateBy { message -> message.id } - val optimisticByOperation = it.messages + // 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.id.startsWith(LOCAL_MESSAGE_PREFIX) && message.operationId.isNotBlank() } + .filter { message -> message.role == ChatProtocol.ROLE_USER && message.operationId.isNotBlank() } .associateBy { message -> message.operationId } val reconciledIds = messages.asSequence() - .mapNotNull { message -> optimisticByOperation[message.operationId]?.id } + .mapNotNull { message -> existingUserByOperation[message.operationId]?.id } .toSet() val authoritativeMessages = messages.map { message -> - val optimistic = optimisticByOperation[message.operationId] - if (optimistic == null || message.role != ChatProtocol.ROLE_USER) { + val local = existingUserByOperation[message.operationId] + if (local == null || message.role != ChatProtocol.ROLE_USER) { message } else { // History is authoritative for identity and ordering, but it @@ -862,9 +866,10 @@ class ChatStore( // fields. Keep those fields on the same turn while replacing // the temporary local id. message.copy( - client = message.client.ifBlank { optimistic.client }, - parts = message.parts + optimistic.parts.filter { localPart -> - localPart.type == ChatProtocol.PART_FILE && message.parts.none { it.type == ChatProtocol.PART_FILE && it.uri == localPart.uri } + 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) }, ) } diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/MultiChatStateTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/MultiChatStateTest.kt index 9b07c3d1..dc17a7d4 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/chat/MultiChatStateTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/MultiChatStateTest.kt @@ -344,15 +344,24 @@ class MultiChatStateTest { 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"), )) - // A replayed X is an idempotent delivery, not another turn. + // 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"), @@ -364,7 +373,7 @@ class MultiChatStateTest { )) val messages = store.value.thread("a")!!.messages - assertEquals(listOf("native-x", "native-y", "native-x-2"), messages.map { it.id }) + 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 }) diff --git a/internal/server/chat_hub.go b/internal/server/chat_hub.go index e2ea42d0..ac430ce7 100644 --- a/internal/server/chat_hub.go +++ b/internal/server/chat_hub.go @@ -465,41 +465,14 @@ func (h *chatHub) snapshot(sessionID string) []protocol.ChatMessage { return messages } -// reconcileHistory annotates an authoritative page with operation identities -// from the retained live user turns. Pairing is by the backend's message order, -// never by text, timestamps, or a connection/request id. It is deliberately -// conservative: a partial page cannot establish a safe one-to-one mapping. +// reconcileHistory intentionally does not infer identity. OpenCode history +// exposes only its native message id and does not echo the prompt operation id, +// so there is no reliable mapping from a retained cross-client user event to a +// history record. In particular, position, text, timestamps and page boundaries +// are not identity keys; annotating with any of them corrupts partial, reordered, +// older or overlapping pages. The live event already carries the operation id. 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 - } - var live []*chatMessage - for _, id := range turn.order { - message := turn.messages[id] - if message != nil && message.role == protocol.ChatRoleUser && message.operationID != "" { - live = append(live, message) - } - } - var users []int - for i := range messages { - if messages[i].Role == protocol.ChatRoleUser { - users = append(users, i) - } - } - if len(users) == 0 || len(users) != len(live) { - return messages - } - out := append([]protocol.ChatMessage(nil), messages...) - for i, index := range users { - out[index].OperationID = live[i].operationID - if out[index].Client == "" { - out[index].Client = live[i].client - } - } - return out + return messages } // shellSnapshot returns the session's still-running shells, in the order they diff --git a/internal/server/chat_test.go b/internal/server/chat_test.go index 33d7b4d0..e9868dd8 100644 --- a/internal/server/chat_test.go +++ b/internal/server/chat_test.go @@ -948,6 +948,21 @@ 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) + } +} + // TestChatHubChargesToolStateBytes pins the retained-state cap: a tool part's // input/content bytes count against it, and an upsert that would exceed the cap // is dropped with the overflow diagnostic rather than growing memory.