Skip to content

Commit fe40361

Browse files
authored
fix(ui): chat stays blocked after model credentials recover (#132179)
* fix(ui): refresh chat readiness after credential recovery Keep retained Chat and New Session on one accepted metadata publication flow, preserve session profile locks, and notify clients when authoritative metadata settles. Fence stale responses and publish persisted inline model selections; refresh Android metadata through the same event. Release note: Control UI chat recovers model readiness after credential or selection changes without reloading, clearing drafts, or hiding prior errors. * test(gateway): adopt prepared metadata projection fixture * fix(ui): preserve metadata scope across chat interactions Read slash commands from the active session publication and rebind retained global chats when agent selection changes. Preserve warm picker state until the authoritative session projection settles. Integrate runtime fixtures and move cross-layer persisted-selection coverage into the Gateway lane without changing check limits. * test(ui): return valid empty lifecycle RPC results * test(ui): keep metadata regression within suite limits * test(gateway): supply prepared model metadata in auth recovery regression * test(gateway): preserve session metadata read access Extend the documented view/suggest read-policy matrix to chat history, startup, and metadata. Participation continues to gate mutations; existing none, incognito, and pending-profile guards remain unchanged. * fix(android): retain session scope in chat metadata Preserve profile-specific availability across metadata refreshes and same-agent session transitions. Carry the required prepared catalog owner into the Gateway lifecycle regression fixture. * fix(ui): preserve draft controls when reconnecting * fix(android): negotiate session metadata refresh scope Advertise session-scoped chat metadata through hello capabilities while preserving the shipped agent-only request and cache contract for older peers. Refresh matching session mutations and missed metadata publications through one synchronous request fence, retaining accepted catalogs and chat drafts. * fix(ui): split streamed pull-request refresh from chat events Keep the merged event owner below the unchanged 700-line lint bound. Move existing link parsing and bounded stream refresh without changing behavior, reply visibility, terminal recovery, or metadata invalidation. The merged guard fails at 710 lines before and passes after. Existing 117 UI tests, forced UI types, lint, build, and isolated P0 review pass.
1 parent 6b27585 commit fe40361

60 files changed

Lines changed: 2432 additions & 902 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/android/app/src/main/java/ai/openclaw/app/chat/ChatController.kt‎

Lines changed: 73 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ import java.util.concurrent.atomic.AtomicLong
6262
// Bounds one-shot search list fetches like the primary session list.
6363
internal const val SESSION_LIST_FETCH_LIMIT = 200
6464
internal const val SESSION_UNREAD_ACK_CAPABILITY = "session-unread-ack-contract"
65+
private const val SESSION_SCOPED_CHAT_METADATA_CAPABILITY = "session-scoped-chat-metadata"
6566
private val QUESTION_REFRESH_RETRY_DELAYS_MS = longArrayOf(1_000L, 2_000L, 4_000L)
6667
private val SWARM_REFRESH_RETRY_DELAYS_MS = longArrayOf(1_000L, 2_000L, 4_000L)
6768
private const val WEAR_AGENT_PULSE_SWARM_MAX_ROWS = 1_000
@@ -109,6 +110,17 @@ private class MainSessionReadiness(
109110

110111
private class BranchListingUnsupportedException : IllegalStateException("sessions.branches.list is not supported by this gateway")
111112

113+
private data class ChatMetadataScope(
114+
val agentId: String,
115+
val sessionKey: String?,
116+
) {
117+
fun params(): JsonObject =
118+
buildJsonObject {
119+
put("agentId", JsonPrimitive(agentId))
120+
sessionKey?.let { put("sessionKey", JsonPrimitive(it)) }
121+
}
122+
}
123+
112124
class ChatController internal constructor(
113125
private val scope: CoroutineScope,
114126
private val json: Json,
@@ -624,7 +636,8 @@ class ChatController internal constructor(
624636
private val newChatCreateInFlight = AtomicBoolean(false)
625637

626638
private var lastHealthPollAtMs: Long? = null
627-
private var chatMetadataAgentId: String? = null
639+
private val chatMetadataRequestSequence = AtomicLong(0)
640+
private var chatMetadataScope: ChatMetadataScope? = null
628641
private var chatMetadataLoadState = ChatMetadataLoadState.Unloaded
629642
private var sessionsListArchived = false
630643

@@ -698,6 +711,7 @@ class ChatController internal constructor(
698711

699712
/** Clears transient chat state when the operator gateway session disconnects. */
700713
fun onDisconnected(message: String) {
714+
chatMetadataRequestSequence.incrementAndGet()
701715
retireMainSessionReadiness()
702716
reconciledOutboxBranchScopes.clear()
703717
ambiguousMutationReconciliationStates.clear()
@@ -710,10 +724,7 @@ class ChatController internal constructor(
710724
reconnectRecoveryGeneration = null
711725
_healthOk.value = false
712726
updateErrorText(null)
713-
_commands.value = emptyList()
714-
_modelCatalog.value = emptyList()
715-
chatMetadataAgentId = null
716-
chatMetadataLoadState = ChatMetadataLoadState.Unloaded
727+
clearChatMetadata()
717728
disableSwarmProgress()
718729
clearLiveHistoryMarker()
719730
synchronized(pendingRuns) {
@@ -824,6 +835,7 @@ class ChatController internal constructor(
824835

825836
/** Invalidates and clears gateway-bound UI state before a target switch can race old responses. */
826837
fun onGatewayScopeChanging(retireRunState: Boolean = false) {
838+
chatMetadataRequestSequence.incrementAndGet()
827839
retireMainSessionReadiness()
828840
disableSwarmProgress()
829841
synchronized(gatewayScopeApplyLock) {
@@ -851,10 +863,7 @@ class ChatController internal constructor(
851863
unreadActivationObserved = false
852864
unreadActivationMarkedUnreadAt = null
853865
unreadPatchRequested = false
854-
_commands.value = emptyList()
855-
_modelCatalog.value = emptyList()
856-
chatMetadataAgentId = null
857-
chatMetadataLoadState = ChatMetadataLoadState.Unloaded
866+
clearChatMetadata()
858867
lastHealthPollAtMs = null
859868
// Outbox rows are gateway-scoped too; the next publish repopulates them for the new scope.
860869
_outboxItems.value = emptyList()
@@ -2205,7 +2214,9 @@ class ChatController internal constructor(
22052214

22062215
/** Refreshes the available text slash commands for the current gateway. */
22072216
fun refreshCommands() {
2208-
scope.launch { fetchChatMetadata() }
2217+
// Retire old reads before queued work runs; keep the last accepted same-scope catalog.
2218+
val requestSequence = chatMetadataRequestSequence.incrementAndGet()
2219+
scope.launch { fetchChatMetadata(requestSequence) }
22092220
}
22102221

22112222
/** Persists the normalized thinking level used for subsequent chat sends. */
@@ -2543,12 +2554,10 @@ class ChatController internal constructor(
25432554
applyThinkingMetadata(_sessions.value.firstOrNull { it.key == key })
25442555
_selectedModelRef.value = null
25452556
lastHandledTerminalRunId = null
2546-
val nextAgentId = resolveAgentIdForSessionKey(key)
2547-
if (chatMetadataAgentId != nextAgentId) {
2548-
_commands.value = emptyList()
2549-
_modelCatalog.value = emptyList()
2550-
chatMetadataAgentId = null
2551-
chatMetadataLoadState = ChatMetadataLoadState.Unloaded
2557+
val nextMetadataScope = currentChatMetadataScope()
2558+
if (chatMetadataScope != nextMetadataScope) {
2559+
chatMetadataRequestSequence.incrementAndGet()
2560+
clearChatMetadata(nextMetadataScope)
25522561
disableSwarmProgress(key)
25532562
}
25542563
updateErrorText(null)
@@ -3393,6 +3402,8 @@ class ChatController internal constructor(
33933402
}
33943403
}
33953404
"seqGap" -> {
3405+
// Metadata notifications can be dropped too, even when history and health remain current.
3406+
refreshCommands()
33963407
// Missed events can hide terminal state or usage for any active run.
33973408
// Keep ownership, discard incomplete telemetry, and recover from snapshots.
33983409
resetSwarmProgress()
@@ -3413,6 +3424,7 @@ class ChatController internal constructor(
34133424
if (payloadJson.isNullOrBlank()) return
34143425
handleChatEvent(payloadJson)
34153426
}
3427+
"chat.metadata.changed" -> refreshCommands()
34163428
"sessions.changed" -> {
34173429
if (payloadJson.isNullOrBlank()) {
34183430
refreshSessionsForCurrentWindow()
@@ -4447,21 +4459,43 @@ class ChatController internal constructor(
44474459
return false
44484460
}
44494461

4450-
private suspend fun fetchChatMetadata() {
4462+
private fun currentChatMetadataScope(): ChatMetadataScope? {
4463+
val sessionKey = _sessionKey.value
4464+
val agentId = resolveAgentIdForSessionKey(sessionKey) ?: return null
4465+
// Stable v2026.7.1-2 accepts only agentId. Retire this negotiation only when the
4466+
// minimum supported Gateway contract guarantees session-scoped chat.metadata.
4467+
return ChatMetadataScope(agentId, sessionKey.takeIf { gatewayAdvertisesCapability(SESSION_SCOPED_CHAT_METADATA_CAPABILITY) == true })
4468+
}
4469+
4470+
private fun clearChatMetadata(nextScope: ChatMetadataScope? = null) {
4471+
_commands.value = emptyList()
4472+
_modelCatalog.value = emptyList()
4473+
chatMetadataScope = nextScope
4474+
chatMetadataLoadState = ChatMetadataLoadState.Unloaded
4475+
}
4476+
4477+
private suspend fun fetchChatMetadata(requestSequence: Long = chatMetadataRequestSequence.incrementAndGet()) {
44514478
val requestCacheScope = currentCacheScope()
4452-
val agentId = resolveAgentIdForSessionKey(_sessionKey.value) ?: return
4479+
val metadataScope = currentChatMetadataScope() ?: return
4480+
synchronized(gatewayScopeApplyLock) {
4481+
if (requestSequence != chatMetadataRequestSequence.get()) return
4482+
if (chatMetadataScope != metadataScope) {
4483+
clearChatMetadata(metadataScope)
4484+
disableSwarmProgress()
4485+
}
4486+
}
44534487
var shouldRefreshSwarm = false
44544488
var shouldDisableSwarm = false
44554489
try {
4456-
val params =
4457-
buildJsonObject {
4458-
put("agentId", JsonPrimitive(agentId))
4459-
}
4460-
val res = requestGatewayBound(requestCacheScope?.gatewayId, "chat.metadata", params.toString())
4490+
val res = requestGatewayBound(requestCacheScope?.gatewayId, "chat.metadata", metadataScope.params().toString())
44614491
val root = json.parseToJsonElement(res).asObjectOrNull()
44624492
val metadataSwarmEnabled = root?.get("swarmEnabled").asBooleanOrNull() == true
44634493
synchronized(gatewayScopeApplyLock) {
4464-
if (requestCacheScope == currentCacheScope() && agentId == resolveAgentIdForSessionKey(_sessionKey.value)) {
4494+
if (
4495+
requestSequence == chatMetadataRequestSequence.get() &&
4496+
requestCacheScope == currentCacheScope() &&
4497+
metadataScope == currentChatMetadataScope()
4498+
) {
44654499
_commands.value = parseChatCommands(json, res)
44664500
val models = parseGatewayModels(root?.get("models") as? JsonArray)
44674501
_modelCatalog.value = models
@@ -4473,23 +4507,13 @@ class ChatController internal constructor(
44734507
chatMetadataLoadState == ChatMetadataLoadState.RetryEmptyCatalog -> ChatMetadataLoadState.Loaded
44744508
else -> ChatMetadataLoadState.RetryEmptyCatalog
44754509
}
4476-
chatMetadataAgentId = agentId
44774510
synchronized(swarmLock) { swarmEnabled = metadataSwarmEnabled }
44784511
shouldRefreshSwarm = metadataSwarmEnabled
44794512
shouldDisableSwarm = !metadataSwarmEnabled
44804513
}
44814514
}
44824515
} catch (_: Throwable) {
4483-
synchronized(gatewayScopeApplyLock) {
4484-
if (requestCacheScope == currentCacheScope() && agentId == resolveAgentIdForSessionKey(_sessionKey.value)) {
4485-
_commands.value = emptyList()
4486-
_modelCatalog.value = emptyList()
4487-
chatMetadataAgentId = null
4488-
chatMetadataLoadState = ChatMetadataLoadState.Unloaded
4489-
synchronized(swarmLock) { swarmEnabled = false }
4490-
shouldDisableSwarm = true
4491-
}
4492-
}
4516+
// A transport failure is not a replacement availability or capability snapshot.
44934517
}
44944518
when {
44954519
shouldRefreshSwarm -> refreshSwarmSessions()
@@ -4750,13 +4774,13 @@ class ChatController internal constructor(
47504774
}
47514775

47524776
private fun hasCurrentChatMetadata(): Boolean {
4753-
val activeAgentId = resolveAgentIdForSessionKey(_sessionKey.value) ?: return false
4754-
return chatMetadataLoadState == ChatMetadataLoadState.Loaded && chatMetadataAgentId == activeAgentId
4777+
val currentScope = currentChatMetadataScope() ?: return false
4778+
return chatMetadataLoadState == ChatMetadataLoadState.Loaded && chatMetadataScope == currentScope
47554779
}
47564780

47574781
private fun refreshCommandsAfterReconnect() {
47584782
if (hasCurrentChatMetadata()) return
4759-
scope.launch { fetchChatMetadata() }
4783+
refreshCommands()
47604784
}
47614785

47624786
/**
@@ -5800,6 +5824,17 @@ class ChatController internal constructor(
58005824
val swarmKind = swarmKindElement.asStringOrNull()?.trim()
58015825
if (swarmEvent && (swarmKind == "phase" || swarmKind == "log")) return
58025826
val reason = payload["reason"].asStringOrNull()
5827+
if (reason == "patch" || reason == "command-metadata" || reason == "reset" || payload["phase"].asStringOrNull() == "reset") {
5828+
val session = eventSessionObject(payload)
5829+
val key = payload["sessionKey"].asStringOrNull() ?: session?.get("key").asStringOrNull()
5830+
val agentId =
5831+
key?.let(::resolveAgentIdFromMainSessionKey)
5832+
?: payload["agentId"].asStringOrNull()
5833+
?: session?.get("ownerAgentId").asStringOrNull()
5834+
val currentScope = currentChatMetadataScope()
5835+
// Profile-only mutations do not change global credentials or the visible session key.
5836+
if (key != null && currentScope?.sessionKey == key && currentScope.agentId == agentId) refreshCommands()
5837+
}
58035838
if (reason == "rewind" || reason == "branch-switch") {
58045839
// Mutation events do not contain a session preview. Refresh the drawer even for a
58055840
// background session and even when this event is deferred behind a local mutation lease.

‎apps/android/app/src/main/java/ai/openclaw/app/gateway/GatewayProtocol.kt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -792,6 +792,7 @@ enum class GatewayEvent(
792792
ConnectChallenge("connect.challenge"),
793793
Agent("agent"),
794794
Chat("chat"),
795+
ChatMetadataChanged("chat.metadata.changed"),
795796
UiCommand("ui.command"),
796797
SessionApproval("session.approval"),
797798
SessionMessage("session.message"),

0 commit comments

Comments
 (0)