Preserve partial cross-client identity fixes before canonical-ID continuation

This commit is contained in:
2026-10-18 23:28:54 +01:00
parent 980f52bd85
commit d630235657
4 changed files with 46 additions and 44 deletions
@@ -845,16 +845,20 @@ class ChatStore(
fun history(sessionId: String, messages: List<ChatMessage>, 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)
},
)
}