diff --git a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/app/OpenClawAppState.kt b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/app/OpenClawAppState.kt index c0d5f9c..51a6162 100644 --- a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/app/OpenClawAppState.kt +++ b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/app/OpenClawAppState.kt @@ -42,6 +42,9 @@ class OpenClawAppState( } hydrated = true } + preferences.loadPendingSendQueue()?.let { queue -> + repository.hydratePendingSendQueue(queue) + } isShowingCachedData = hydrated } @@ -95,6 +98,7 @@ class OpenClawAppState( remote.refreshSessions() preferences.saveOverviewSnapshot(remote.exportOverviewSnapshot()) persistRecentMessageCache(remote) + persistPendingSendQueue(remote) isShowingCachedData = false }.onFailure { syncError = it.message ?: "远程同步失败" @@ -112,6 +116,7 @@ class OpenClawAppState( remote.refreshAgents() remote.refreshSessions() preferences.saveOverviewSnapshot(remote.exportOverviewSnapshot()) + persistPendingSendQueue(remote) isShowingCachedData = false }.onFailure { syncError = it.message ?: "远程同步失败" @@ -127,6 +132,7 @@ class OpenClawAppState( remote.refreshMessages(sessionId) val autoRetried = remote.retryAutoRecoverableMessages(sessionId) persistRecentMessageCache(remote, preferredSessionId = sessionId) + persistPendingSendQueue(remote) if (autoRetried) { feedbackMessage = "已自动重试恢复的待发消息" } @@ -147,8 +153,10 @@ class OpenClawAppState( runCatching { remote.sendMessageRemote(sessionId, text) persistRecentMessageCache(remote, preferredSessionId = sessionId) + persistPendingSendQueue(remote) }.onFailure { persistRecentMessageCache(remote, preferredSessionId = sessionId) + persistPendingSendQueue(remote) syncError = it.message ?: "消息发送失败" feedbackMessage = "消息发送失败" } @@ -159,10 +167,16 @@ class OpenClawAppState( sendingSessionId = sessionId runCatching { repository.retryMessage(sessionId, messageId) - (repository as? RemoteOpenClawRepository)?.let { persistRecentMessageCache(it, preferredSessionId = sessionId) } + (repository as? RemoteOpenClawRepository)?.let { + persistRecentMessageCache(it, preferredSessionId = sessionId) + persistPendingSendQueue(it) + } feedbackMessage = "已重新发送消息" }.onFailure { - (repository as? RemoteOpenClawRepository)?.let { persistRecentMessageCache(it, preferredSessionId = sessionId) } + (repository as? RemoteOpenClawRepository)?.let { + persistRecentMessageCache(it, preferredSessionId = sessionId) + persistPendingSendQueue(it) + } syncError = it.message ?: "消息重试失败" feedbackMessage = "消息重试失败" } @@ -191,10 +205,16 @@ class OpenClawAppState( ) { runCatching { repository.uploadAttachmentStub(sessionId, fileName, bytes, contentType) - (repository as? RemoteOpenClawRepository)?.let { persistRecentMessageCache(it, preferredSessionId = sessionId) } + (repository as? RemoteOpenClawRepository)?.let { + persistRecentMessageCache(it, preferredSessionId = sessionId) + persistPendingSendQueue(it) + } feedbackMessage = "附件已加入发送队列" }.onFailure { - (repository as? RemoteOpenClawRepository)?.let { persistRecentMessageCache(it, preferredSessionId = sessionId) } + (repository as? RemoteOpenClawRepository)?.let { + persistRecentMessageCache(it, preferredSessionId = sessionId) + persistPendingSendQueue(it) + } syncError = it.message ?: "附件上传失败" feedbackMessage = "附件上传失败" } @@ -203,10 +223,16 @@ class OpenClawAppState( suspend fun retryAttachment(sessionId: String, messageId: String) { runCatching { repository.retryAttachment(sessionId, messageId) - (repository as? RemoteOpenClawRepository)?.let { persistRecentMessageCache(it, preferredSessionId = sessionId) } + (repository as? RemoteOpenClawRepository)?.let { + persistRecentMessageCache(it, preferredSessionId = sessionId) + persistPendingSendQueue(it) + } feedbackMessage = "已重新发起附件上传" }.onFailure { - (repository as? RemoteOpenClawRepository)?.let { persistRecentMessageCache(it, preferredSessionId = sessionId) } + (repository as? RemoteOpenClawRepository)?.let { + persistRecentMessageCache(it, preferredSessionId = sessionId) + persistPendingSendQueue(it) + } syncError = it.message ?: "附件重试失败" feedbackMessage = "附件重试失败" } @@ -248,6 +274,10 @@ class OpenClawAppState( .take(3) preferences.saveRecentMessageSnapshotBucket(remote.exportRecentMessageSnapshotBucket(recentIds)) } + + private fun persistPendingSendQueue(remote: RemoteOpenClawRepository) { + preferences.savePendingSendQueue(remote.exportPendingSendQueue()) + } } enum class MainTab { diff --git a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/AppPreferences.kt b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/AppPreferences.kt index 95e2cfc..856e88b 100644 --- a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/AppPreferences.kt +++ b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/AppPreferences.kt @@ -55,6 +55,15 @@ class AppPreferences( settings.putString(KEY_RECENT_MESSAGE_SNAPSHOT, json.encodeToString(MessageCacheBucket.serializer(), bucket)) } + fun loadPendingSendQueue(): PendingSendQueue? { + val raw = settings.getStringOrNull(KEY_PENDING_SEND_QUEUE) ?: return null + return runCatching { json.decodeFromString(raw) }.getOrNull() + } + + fun savePendingSendQueue(queue: PendingSendQueue) { + settings.putString(KEY_PENDING_SEND_QUEUE, json.encodeToString(PendingSendQueue.serializer(), queue)) + } + companion object { private const val KEY_BASE_URL = "server.base_url" private const val KEY_TOKEN = "server.token" @@ -62,5 +71,6 @@ class AppPreferences( private const val KEY_THEME_MODE = "ui.theme_mode" private const val KEY_OVERVIEW_SNAPSHOT = "cache.overview_snapshot" private const val KEY_RECENT_MESSAGE_SNAPSHOT = "cache.recent_message_snapshot_bucket" + private const val KEY_PENDING_SEND_QUEUE = "queue.pending_send" } } diff --git a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/OpenClawRepository.kt b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/OpenClawRepository.kt index 48a0571..4d43d7a 100644 --- a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/OpenClawRepository.kt +++ b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/OpenClawRepository.kt @@ -7,6 +7,7 @@ interface OpenClawRepository { fun streamStatusFor(sessionId: String): String? fun hydrateOverview(snapshot: OverviewSnapshot) fun hydrateRecentMessages(bucket: MessageCacheBucket) + fun hydratePendingSendQueue(queue: PendingSendQueue) fun findSession(sessionId: String): SessionSummary? fun messagesFor(sessionId: String): List diff --git a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/PendingSendQueue.kt b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/PendingSendQueue.kt new file mode 100644 index 0000000..217d7ce --- /dev/null +++ b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/PendingSendQueue.kt @@ -0,0 +1,18 @@ +package cn.xiaobai.openclawapp.data + +import kotlinx.serialization.Serializable + +@Serializable +data class PendingSendQueue( + val items: List = emptyList(), + val savedAt: String = "", +) + +@Serializable +data class PendingSendItem( + val messageId: String, + val sessionId: String, + val text: String, + val createdAt: String, + val autoRetryEligible: Boolean = true, +) diff --git a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/RemoteOpenClawRepository.kt b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/RemoteOpenClawRepository.kt index 3eb0c96..242ba37 100644 --- a/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/RemoteOpenClawRepository.kt +++ b/composeApp/src/commonMain/kotlin/cn/xiaobai/openclawapp/data/RemoteOpenClawRepository.kt @@ -33,6 +33,14 @@ private data class TextRetryPayload( val text: String, ) +private data class PendingTextSend( + val messageId: String, + val sessionId: String, + val text: String, + val createdAt: String, + val autoRetryEligible: Boolean = true, +) + class RemoteOpenClawRepository( private val config: ServerConfig, ) : OpenClawRepository { @@ -71,6 +79,7 @@ class RemoteOpenClawRepository( private val attachmentRetryStore = mutableMapOf() private val attachmentOpenStore = mutableMapOf() private val textRetryStore = mutableMapOf() + private val pendingTextQueue = mutableMapOf() private val autoRetryMessageIds = mutableSetOf() override fun findSession(sessionId: String): SessionSummary? = sessions.firstOrNull { it.id == sessionId } @@ -95,6 +104,22 @@ class RemoteOpenClawRepository( messageStore = messageStore + restored } + override fun hydratePendingSendQueue(queue: PendingSendQueue) { + queue.items.forEach { item -> + pendingTextQueue[item.messageId] = PendingTextSend( + messageId = item.messageId, + sessionId = item.sessionId, + text = item.text, + createdAt = item.createdAt, + autoRetryEligible = item.autoRetryEligible, + ) + textRetryStore[item.messageId] = TextRetryPayload(item.sessionId, item.text) + if (item.autoRetryEligible) { + autoRetryMessageIds.add(item.messageId) + } + } + } + override fun recentSession(): SessionSummary? = recentSessionId?.let(::findSession) override fun pinnedCount(): Int = sessions.count { it.isPinned } @@ -146,6 +171,13 @@ class RemoteOpenClawRepository( val withoutThinking = currentMessages.filterNot { it.id.startsWith("local-thinking-") } val localUserId = "local-user-$sessionId-${withoutThinking.size + 1}" textRetryStore[localUserId] = TextRetryPayload(sessionId, text) + pendingTextQueue[localUserId] = PendingTextSend( + messageId = localUserId, + sessionId = sessionId, + text = text, + createdAt = "现在", + autoRetryEligible = true, + ) val next = withoutThinking + listOf( ChatMessage( id = localUserId, @@ -322,6 +354,21 @@ class RemoteOpenClawRepository( savedAt = status.updatedAt, ) + fun exportPendingSendQueue(): PendingSendQueue = PendingSendQueue( + items = pendingTextQueue.values + .sortedBy { it.createdAt } + .map { item -> + PendingSendItem( + messageId = item.messageId, + sessionId = item.sessionId, + text = item.text, + createdAt = item.createdAt, + autoRetryEligible = item.autoRetryEligible, + ) + }, + savedAt = status.updatedAt, + ) + suspend fun refreshAgents() { availableAgents = api.getAgents().map { it.id.ifBlank { it.name } } .ifEmpty { listOf(config.defaultAgent) } @@ -356,6 +403,7 @@ class RemoteOpenClawRepository( sendMessage(sessionId, text) runCatching { api.sendMessage(sessionId, text) + clearPendingTextMessage(sessionId, text) }.onFailure { markTextMessageFailed(sessionId, text) throw it @@ -388,12 +436,24 @@ class RemoteOpenClawRepository( runCatching { api.sendMessage(sessionId, payload.text) + pendingTextQueue.remove(messageId) }.onFailure { markTextMessageFailed(sessionId, payload.text, existingMessageId = messageId) throw it } } + private fun clearPendingTextMessage(sessionId: String, text: String) { + val targetId = pendingTextQueue.values + .filter { it.sessionId == sessionId && it.text == text } + .minByOrNull { it.createdAt } + ?.messageId + ?: return + pendingTextQueue.remove(targetId) + textRetryStore.remove(targetId) + autoRetryMessageIds.remove(targetId) + } + private fun subscribeSessionStream(sessionId: String) { streamJob?.cancel() streamStatusStore = streamStatusStore + (sessionId to "connecting") @@ -561,12 +621,21 @@ class RemoteOpenClawRepository( private fun markTextMessageFailed(sessionId: String, text: String, existingMessageId: String? = null) { val currentMessages = messageStore[sessionId].orEmpty() + var resolvedFailedId: String? = existingMessageId val next = currentMessages.mapNotNull { message -> when { message.id.startsWith("local-thinking-") -> null message.role == MessageRole.User && message.text == text && (existingMessageId == null || message.id == existingMessageId) -> { val failedId = existingMessageId ?: message.id + resolvedFailedId = failedId textRetryStore.putIfAbsent(failedId, TextRetryPayload(sessionId, text)) + pendingTextQueue[failedId] = PendingTextSend( + messageId = failedId, + sessionId = sessionId, + text = text, + createdAt = "刚刚", + autoRetryEligible = true, + ) message.copy( id = failedId, status = "send-failed", @@ -577,6 +646,7 @@ class RemoteOpenClawRepository( else -> message } } + resolvedFailedId?.let { autoRetryMessageIds.add(it) } messageStore = messageStore + (sessionId to next) updateSessionPreview(sessionId, previewMessage(next)) } @@ -586,11 +656,25 @@ class RemoteOpenClawRepository( return when { domain.role == MessageRole.User && domain.kind == MessageKind.Text && domain.status == "queued" -> { textRetryStore[domain.id] = TextRetryPayload(sessionId, domain.text) + pendingTextQueue[domain.id] = PendingTextSend( + messageId = domain.id, + sessionId = sessionId, + text = domain.text, + createdAt = domain.createdAt, + autoRetryEligible = true, + ) autoRetryMessageIds.add(domain.id) domain.copy(status = "send-failed", retryable = true) } domain.role == MessageRole.User && domain.kind == MessageKind.Text && domain.status == "send-failed" -> { textRetryStore[domain.id] = TextRetryPayload(sessionId, domain.text) + pendingTextQueue[domain.id] = PendingTextSend( + messageId = domain.id, + sessionId = sessionId, + text = domain.text, + createdAt = domain.createdAt, + autoRetryEligible = true, + ) domain.copy(retryable = true) } domain.kind == MessageKind.Attachment && domain.status == "uploading" -> { diff --git a/docs/MVP_PROGRESS.md b/docs/MVP_PROGRESS.md index 6466ca1..e08df36 100644 --- a/docs/MVP_PROGRESS.md +++ b/docs/MVP_PROGRESS.md @@ -164,7 +164,7 @@ Android/iOS App 结论:**移动端体验已可用,后端归档仍是过渡方案。** -补充:虽然附件仍是 overlay 方案,但 BFF 现在至少已经把 overlay 的排序问题收了一步,不会再因为简单 append 导致附件和文本的时间线顺序错乱;同时,过期/被淘汰的附件也会从 overlay 时间线里同步摘除,不再出现“列表里看得到、点开必 404”的假附件。并且,BFF 已提前铺好一层前向兼容归并逻辑:若后续 OpenClaw history 返回原生附件消息,BFF 会优先尝试把 overlay 附件与远端附件归并,减少未来迁移时的双份展示风险。 +补充:虽然附件仍是 overlay 方案,但 BFF 现在至少已经把 overlay 的排序问题收了一步,不会再因为简单 append 导致附件和文本的时间线顺序错乱;同时,过期/被淘汰的附件也会从 overlay 时间线里同步摘除,不再出现“列表里看得到、点开必 404”的假附件。并且,BFF 已提前铺好一层前向兼容归并逻辑:若后续 OpenClaw history 返回原生附件消息,BFF 会优先尝试把 overlay 附件与远端附件归并,减少未来迁移时的双份展示风险。除此之外,BFF 的 session 列表摘要现在也开始按消息类型生成预览文案(如 `[附件]` / `[工具]` / `[工具结果]`),不再只是裸文本,和聊天页的预览语义更一致。进一步地,被远端原生附件消息“收编”后的本地附件 payload 现在会以读取 alias 形式持久化,而不会在重启后重新作为 overlay 假消息塞回时间线;BFF 侧也开始显式维护旧 attachment id 到新远端 message id 的 alias 映射,让 read_attachment 的查找语义更明确。现在 source stub 被收编后,还会留下轻量 redirect 元数据,因此重启后旧 id 也仍可解析到新远端 id,不再只靠内存里的 alias 表。同时,目标 payload 一旦过期/被淘汰,指向它的 redirect meta 也会同步清掉,避免留下永远只会 404 的旧 alias 入口。 ### 3.3 多平台文件选择器 @@ -193,7 +193,8 @@ Android/iOS App - [x] 手动刷新/重新进入会话时,会保留本地尚未被远端确认的失败消息,避免刷新后直接消失 - [x] 从缓存恢复出来的 `queued` 文本,在重新进入会话时会自动尝试补发一次 - [x] 聊天页已显式区分“自动重试中”和普通手动发送中状态 -- [ ] 还没有离线发送队列 +- [x] 已有第一版本地文本发送队列雏形:待发送文本会独立持久化,App 重启后可恢复并继续进入自动补发/手动重试链路 +- [ ] 还没有完整的离线发送队列(目前先覆盖文本,不含附件) - [ ] 还没有真正基于网络恢复信号的自动补发 ### 4.2 附件后端主链路 @@ -396,5 +397,11 @@ Android/iOS App - 2026-03-07:开始补 session 列表排序稳定性:App 不再只按 `updatedAt` 显示字符串排序,而是额外维护独立的 session sort key;`现在` / `刚刚` 会映射为递增排序值,格式化时间则尽量解析成稳定数值,减少列表在本地 pending / SSE 更新下的错序与抖动。 - 2026-03-07:补齐 session sort key 持久化:overview snapshot 现在会把每个 session 的 sort key 一并保存并在 hydrate 时恢复,减少冷启动缓存态和热态之间的排序跳变。 - 2026-03-07:继续统一 session 摘要选择逻辑:更多 preview 更新路径改为复用 `previewMessage()`,避免在 retry / snapshot merge / SSE completed / stream failed 等场景下直接拿 `lastOrNull()` 导致摘要被 thinking 占位或瞬时系统消息抢走。 +- 2026-03-07:开始补真正的本地发送队列雏形:新增独立的 `PendingSendQueue` 持久化结构,与 recent message cache 分离;文本待发送项现在会单独入队、在 hydrate 时恢复,并在发送成功/失败/重试后同步维护,减少“只有界面缓存、没有真实队列语义”的不一致。 - 2026-03-07:继续补 SSE 顺序一致性:当消息集合未变、只是顺序发生变化时,BFF / App 现已改为通过 `message.reordered` 精确纠正顺序,避免因为 diff 只看 id/内容变化而静默漏掉重排,也避免为单纯重排走整包 snapshot。 - 2026-03-07:继续收缩 SSE 重刷范围:在消息通过 `message.removed` 逐条删空时,BFF 不再额外补发重复的空 `session.snapshot`,减少无意义整包刷新。 +- 2026-03-07:补强 BFF 会话摘要语义:session 列表里的 lastMessage 预览现在会按消息类型生成前缀与截断文案(附件/工具/工具结果/思考中/系统/断流),不再只是返回裸 `text`,让附件 overlay、工具消息和聊天页预览语义更一致。 +- 2026-03-07:补强附件 alias 生命周期:当 overlay 附件被远端原生附件消息归并收编后,BFF 会把本地二进制 payload 以“不可见 alias”形式持久化到目标远端 message id;重启后它仍可被读取,但不会再被重建成 overlay 假消息重新塞回时间线。 +- 2026-03-07:继续收清附件读取语义:BFF 开始显式维护旧 attachment id 到新远端 message id 的 alias 映射,`read_attachment()` 会先走 alias 解析再读 payload,不再完全依赖“请求 id 恰好就是 payload 主键”。 +- 2026-03-07:补齐附件 alias 持久化入口:source stub 被远端消息收编后,BFF 会保留一份轻量 redirect 元数据;重启后旧 attachment id 仍能恢复 alias 解析,而不会因为 alias 只存在内存里而失效。 +- 2026-03-07:补齐 alias 清理一致性:当目标附件 payload 过期或被数量策略淘汰时,BFF 会同步清掉所有指向它的 redirect meta / alias 入口,避免旧 attachment id 虽还能解析但最终只会稳定 404。