Skip to content

Commit a52eb21

Browse files
authored
feat(apps): connect multiple gateways simultaneously (#111932)
* feat(apps): support simultaneous gateways * fix(apps): satisfy multi-gateway checks * chore(apps): refresh multi-gateway baselines * style(android): format gateway fleet code
1 parent e2bb043 commit a52eb21

34 files changed

Lines changed: 2243 additions & 598 deletions

‎apps/.i18n/native-source.json‎

Lines changed: 390 additions & 350 deletions
Large diffs are not rendered by default.

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -572,6 +572,7 @@ class MainViewModel private constructor(
572572
val manualTls: StateFlow<Boolean> = prefs.manualTls
573573
val pairedGateways: StateFlow<List<GatewayRegistryEntry>> = prefs.gatewayRegistry.entries
574574
val activeGatewayStableId: StateFlow<String?> = prefs.gatewayRegistry.activeStableId
575+
val connectedGatewayStableIds: StateFlow<List<String>> = prefs.gatewayRegistry.connectedStableIds
575576
val onboardingCompleted: StateFlow<Boolean> = prefs.onboardingCompleted
576577
val canvasDebugStatusEnabled: StateFlow<Boolean> = prefs.canvasDebugStatusEnabled
577578
val installedAppsSharingEnabled: StateFlow<Boolean> = prefs.installedAppsSharingEnabled
@@ -1221,6 +1222,13 @@ class MainViewModel private constructor(
12211222
}
12221223
}
12231224

1225+
fun setGatewayConnectionEnabled(
1226+
stableId: String,
1227+
enabled: Boolean,
1228+
) {
1229+
ensureRuntime().setGatewayConnectionEnabled(stableId, enabled)
1230+
}
1231+
12241232
fun forgetGateway(stableId: String) {
12251233
val operation = gatewayConfigOperationSeq.incrementAndGet()
12261234
viewModelScope.launch(Dispatchers.Default) {

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

Lines changed: 167 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1352,6 +1352,15 @@ class NodeRuntime private constructor(
13521352
customHeadersProvider = prefs::loadGatewayCustomHeaders,
13531353
)
13541354

1355+
private data class SecondaryOperatorRuntime(
1356+
val endpoint: GatewayEndpoint,
1357+
val session: GatewaySession,
1358+
)
1359+
1360+
private val secondaryOperatorSessions = ConcurrentHashMap<String, SecondaryOperatorRuntime>()
1361+
private val _backgroundGatewayStatuses = MutableStateFlow<Map<String, String>>(emptyMap())
1362+
val backgroundGatewayStatuses: StateFlow<Map<String, String>> = _backgroundGatewayStatuses.asStateFlow()
1363+
13551364
private val wearProxyController by lazy {
13561365
WearProxyController(
13571366
requestGateway = ::requestWearGateway,
@@ -2684,6 +2693,7 @@ class NodeRuntime private constructor(
26842693
val lastDiscoveredStableId: StateFlow<String> = prefs.lastDiscoveredStableId
26852694
val pairedGateways: StateFlow<List<GatewayRegistryEntry>> = prefs.gatewayRegistry.entries
26862695
val activeGatewayStableId: StateFlow<String?> = prefs.gatewayRegistry.activeStableId
2696+
val connectedGatewayStableIds: StateFlow<List<String>> = prefs.gatewayRegistry.connectedStableIds
26872697
val canvasDebugStatusEnabled: StateFlow<Boolean> = prefs.canvasDebugStatusEnabled
26882698
val installedAppsSharingEnabled: StateFlow<Boolean> = prefs.installedAppsSharingEnabled
26892699
val notificationForwardingEnabled: StateFlow<Boolean> = prefs.notificationForwardingEnabled
@@ -2701,6 +2711,7 @@ class NodeRuntime private constructor(
27012711
private var didAutoConnect = false
27022712

27032713
@Volatile private var preferredGatewayReconnectSuppressed = initialReconnectSuppressed
2714+
private val secondaryGatewayConnectionsEnabled = MutableStateFlow(!initialReconnectSuppressed)
27042715

27052716
val chatSessionKey: StateFlow<String> = chat.sessionKey
27062717
val chatSessionOwnerAgentId: StateFlow<String?> = chat.sessionOwnerAgentId
@@ -2830,6 +2841,20 @@ class NodeRuntime private constructor(
28302841
autoConnectIfNeeded()
28312842
}
28322843
}
2844+
scope.launch(Dispatchers.Default) {
2845+
combine(
2846+
prefs.gatewayRegistry.entries,
2847+
prefs.gatewayRegistry.connectedStableIds,
2848+
prefs.gatewayRegistry.activeStableId,
2849+
gateways,
2850+
combine(_isForeground, secondaryGatewayConnectionsEnabled) { foreground, enabled ->
2851+
foreground && enabled
2852+
},
2853+
) { entries, connectedIds, activeId, discovered, shouldRun ->
2854+
BackgroundGatewayFleetSnapshot(entries, connectedIds, activeId, discovered, shouldRun)
2855+
}.distinctUntilChanged()
2856+
.collect(::reconcileBackgroundGatewayFleet)
2857+
}
28332858
} else {
28342859
applyScreenshotFixture()
28352860
}
@@ -2968,8 +2993,92 @@ class NodeRuntime private constructor(
29682993
prefs.setLastDiscoveredStableId(list.first().stableId)
29692994
}
29702995

2971-
private fun resolvePreferredGatewayEndpoint(): GatewayEndpoint? {
2972-
val entry = prefs.gatewayRegistry.activeEntry() ?: return null
2996+
private data class BackgroundGatewayFleetSnapshot(
2997+
val entries: List<GatewayRegistryEntry>,
2998+
val connectedIds: List<String>,
2999+
val activeId: String?,
3000+
val discovered: List<GatewayEndpoint>,
3001+
val shouldRun: Boolean,
3002+
)
3003+
3004+
private suspend fun reconcileBackgroundGatewayFleet(snapshot: BackgroundGatewayFleetSnapshot) {
3005+
val desired =
3006+
if (!snapshot.shouldRun) {
3007+
emptyMap()
3008+
} else {
3009+
backgroundGatewayStableIds(
3010+
entries = snapshot.entries,
3011+
connectedIds = snapshot.connectedIds,
3012+
activeId = snapshot.activeId,
3013+
foreground = true,
3014+
).asSequence()
3015+
.mapNotNull { stableId ->
3016+
val entry = snapshot.entries.firstOrNull { it.stableId == stableId } ?: return@mapNotNull null
3017+
val endpoint = resolveRegistryEndpoint(entry, snapshot.discovered) ?: return@mapNotNull null
3018+
stableId to endpoint
3019+
}.toMap()
3020+
}
3021+
3022+
secondaryOperatorSessions.keys
3023+
.filterNot(desired::containsKey)
3024+
.forEach { stableId ->
3025+
secondaryOperatorSessions.remove(stableId)?.session?.disconnectAndJoin()
3026+
updateBackgroundGatewayStatus(stableId, null)
3027+
}
3028+
3029+
for ((stableId, endpoint) in desired) {
3030+
val existing = secondaryOperatorSessions[stableId]
3031+
if (existing?.endpoint == endpoint) continue
3032+
existing?.session?.disconnectAndJoin()
3033+
val auth = resolveGatewayConnectAuth(endpoint)
3034+
val storedOperatorEntry = loadStoredRoleDeviceAuthEntry(endpoint, "operator")
3035+
val operatorAuth = resolveOperatorSessionConnectAuth(auth, storedOperatorEntry?.token)
3036+
if (operatorAuth == null) {
3037+
updateBackgroundGatewayStatus(stableId, "Needs setup")
3038+
secondaryOperatorSessions.remove(stableId)
3039+
continue
3040+
}
3041+
val session =
3042+
GatewaySession(
3043+
scope = scope,
3044+
identityStore = identityStore,
3045+
deviceAuthStore = deviceAuthStore,
3046+
onConnected = {
3047+
prefs.gatewayRegistry.markConnected(stableId, System.currentTimeMillis())
3048+
updateBackgroundGatewayStatus(stableId, "Connected")
3049+
},
3050+
onDisconnected = { message -> updateBackgroundGatewayStatus(stableId, message) },
3051+
onConnectFailure = { error, _ -> updateBackgroundGatewayStatus(stableId, error.message) },
3052+
// Secondary sessions retain authenticated presence only. Focused UI state and
3053+
// capability commands remain exclusively owned by the active runtime sessions.
3054+
onEvent = { _, _ -> },
3055+
customHeadersProvider = prefs::loadGatewayCustomHeaders,
3056+
)
3057+
secondaryOperatorSessions[stableId] = SecondaryOperatorRuntime(endpoint, session)
3058+
updateBackgroundGatewayStatus(stableId, "Connecting…")
3059+
val usesStoredOperatorDeviceToken =
3060+
operatorSessionUsesStoredDeviceToken(auth, storedOperatorEntry?.token)
3061+
session.connect(
3062+
endpoint,
3063+
operatorAuth.token,
3064+
operatorAuth.bootstrapToken,
3065+
operatorAuth.password,
3066+
connectionManager.buildOperatorConnectOptions(
3067+
scopes =
3068+
operatorConnectScopesForAuth(
3069+
usesStoredDeviceToken = usesStoredOperatorDeviceToken,
3070+
storedOperatorScopes = storedOperatorEntry?.scopes,
3071+
),
3072+
),
3073+
connectionManager.resolveTlsParams(endpoint),
3074+
)
3075+
}
3076+
}
3077+
3078+
private fun resolveRegistryEndpoint(
3079+
entry: GatewayRegistryEntry,
3080+
discovered: List<GatewayEndpoint> = gateways.value,
3081+
): GatewayEndpoint? {
29733082
return when (entry.kind) {
29743083
GatewayRegistryEntryKind.MANUAL -> {
29753084
val host = entry.host?.trim().orEmpty()
@@ -2978,13 +3087,32 @@ class NodeRuntime private constructor(
29783087
GatewayEndpoint.manual(host = host, port = port)
29793088
}
29803089
GatewayRegistryEntryKind.DISCOVERED -> {
2981-
val endpoint = gateways.value.firstOrNull { it.stableId == entry.stableId } ?: return null
3090+
val endpoint = discovered.firstOrNull { it.stableId == entry.stableId } ?: return null
29823091
val storedFingerprint = prefs.loadGatewayTlsFingerprint(endpoint.stableId)?.trim().orEmpty()
29833092
endpoint.takeIf { storedFingerprint.isNotEmpty() }
29843093
}
29853094
}
29863095
}
29873096

3097+
private fun updateBackgroundGatewayStatus(
3098+
stableId: String,
3099+
status: String?,
3100+
) {
3101+
synchronized(secondaryOperatorSessions) {
3102+
_backgroundGatewayStatuses.value =
3103+
if (status == null) {
3104+
_backgroundGatewayStatuses.value - stableId
3105+
} else {
3106+
_backgroundGatewayStatuses.value + (stableId to status)
3107+
}
3108+
}
3109+
}
3110+
3111+
private fun resolvePreferredGatewayEndpoint(): GatewayEndpoint? {
3112+
val entry = prefs.gatewayRegistry.activeEntry() ?: return null
3113+
return resolveRegistryEndpoint(entry)
3114+
}
3115+
29883116
suspend fun switchToGateway(stableId: String): Boolean {
29893117
val entry =
29903118
prefs.gatewayRegistry.entries.value
@@ -3007,11 +3135,20 @@ class NodeRuntime private constructor(
30073135
return connectSwitchingGateway(endpoint)
30083136
}
30093137

3138+
fun setGatewayConnectionEnabled(
3139+
stableId: String,
3140+
enabled: Boolean,
3141+
) {
3142+
if (enabled) secondaryGatewayConnectionsEnabled.value = true
3143+
prefs.gatewayRegistry.setConnectionEnabled(stableId, enabled)
3144+
}
3145+
30103146
suspend fun connectSwitchingGateway(
30113147
endpoint: GatewayEndpoint,
30123148
explicitAuth: GatewayConnectAuth? = null,
30133149
): Boolean {
30143150
preferredGatewayReconnectSuppressed = false
3151+
secondaryGatewayConnectionsEnabled.value = true
30153152
val intent = gatewayLifecycleIntentSeq.incrementAndGet()
30163153
return gatewaySwitchMutex.withLock {
30173154
if (intent != gatewayLifecycleIntentSeq.get()) return@withLock false
@@ -3960,6 +4097,7 @@ class NodeRuntime private constructor(
39604097

39614098
fun refreshGatewayConnection() {
39624099
preferredGatewayReconnectSuppressed = false
4100+
secondaryGatewayConnectionsEnabled.value = true
39634101
gatewayLifecycleIntentSeq.incrementAndGet()
39644102
launchGatewayLifecycle {
39654103
val endpoint = connectedEndpoint
@@ -4222,6 +4360,7 @@ class NodeRuntime private constructor(
42224360

42234361
fun connect(endpoint: GatewayEndpoint) {
42244362
preferredGatewayReconnectSuppressed = false
4363+
secondaryGatewayConnectionsEnabled.value = true
42254364
gatewayLifecycleIntentSeq.incrementAndGet()
42264365
launchConnect(endpoint, explicitAuth = null)
42274366
}
@@ -4231,6 +4370,7 @@ class NodeRuntime private constructor(
42314370
auth: GatewayConnectAuth,
42324371
) {
42334372
preferredGatewayReconnectSuppressed = false
4373+
secondaryGatewayConnectionsEnabled.value = true
42344374
gatewayLifecycleIntentSeq.incrementAndGet()
42354375
launchConnect(endpoint, explicitAuth = auth)
42364376
}
@@ -4393,19 +4533,30 @@ class NodeRuntime private constructor(
43934533
fun disconnect() {
43944534
synchronized(gatewayLifecycleIntentLock) {
43954535
preferredGatewayReconnectSuppressed = true
4536+
secondaryGatewayConnectionsEnabled.value = false
43964537
gatewayLifecycleIntentSeq.incrementAndGet()
4538+
disconnectSecondaryGatewayConnections()
43974539
disconnect(retireRunState = false)
43984540
}
43994541
}
44004542

44014543
fun prepareForGatewaySetup() {
44024544
synchronized(gatewayLifecycleIntentLock) {
44034545
preferredGatewayReconnectSuppressed = true
4546+
secondaryGatewayConnectionsEnabled.value = false
44044547
gatewayLifecycleIntentSeq.incrementAndGet()
4548+
disconnectSecondaryGatewayConnections()
44054549
disconnect(retireRunState = true)
44064550
}
44074551
}
44084552

4553+
private fun disconnectSecondaryGatewayConnections() {
4554+
val sessions = secondaryOperatorSessions.values.map { it.session }
4555+
secondaryOperatorSessions.clear()
4556+
_backgroundGatewayStatuses.value = emptyMap()
4557+
sessions.forEach { it.disconnect() }
4558+
}
4559+
44094560
private fun disconnect(retireRunState: Boolean) {
44104561
if (wearRealtimeTalkControllerLazy.isInitialized()) wearRealtimeTalkController.abort()
44114562
prepareDisconnect(retireRunState)
@@ -4423,6 +4574,8 @@ class NodeRuntime private constructor(
44234574
private suspend fun forgetGatewayLocked(stableId: String): Boolean {
44244575
val normalized = stableId.trim()
44254576
if (normalized.isEmpty()) return false
4577+
secondaryOperatorSessions.remove(normalized)?.session?.disconnectAndJoin()
4578+
updateBackgroundGatewayStatus(normalized, null)
44264579
val wasActive = prefs.gatewayRegistry.activeStableId.value == normalized
44274580
val connectOperationsDrained =
44284581
synchronized(gatewayAuthLifecycleLock) {
@@ -8108,6 +8261,17 @@ internal fun normalizeOperatorScopes(scopes: List<String>): List<String> =
81088261
.distinct()
81098262
.sorted()
81108263

8264+
internal fun backgroundGatewayStableIds(
8265+
entries: List<GatewayRegistryEntry>,
8266+
connectedIds: List<String>,
8267+
activeId: String?,
8268+
foreground: Boolean,
8269+
): List<String> {
8270+
if (!foreground) return emptyList()
8271+
val registered = entries.mapTo(mutableSetOf()) { it.stableId }
8272+
return connectedIds.distinct().filter { it != activeId && it in registered }
8273+
}
8274+
81118275
private enum class HomeCanvasGatewayState {
81128276
Connected,
81138277
Connecting,

0 commit comments

Comments
 (0)