Skip to content

Commit 8f589ba

Browse files
feat(android): switch saved gateways from the sidebar (#148209)
Add a searchable Gateway picker and a cancellable connection flow to the Android sidebar. Preserve Gateway-scoped drafts, attachments, and safe connection handoff while reusing existing credential and TLS handling. Include regression coverage and documentation. Co-authored-by: IWhatsskill <[email protected]>
1 parent 1a5ea15 commit 8f589ba

16 files changed

Lines changed: 1869 additions & 109 deletions

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

Lines changed: 29 additions & 11 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

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

Lines changed: 102 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,20 @@ class MainViewModel private constructor(
334334
val requestedHomeDestination: StateFlow<HomeDestination?> = _requestedHomeDestination
335335
private val requestedSettingsRouteState = MutableStateFlow<SettingsRoute?>(null)
336336
internal val requestedSettingsRoute: StateFlow<SettingsRoute?> get() = requestedSettingsRouteState
337+
338+
internal class GatewayAdditionRequest
339+
340+
private val gatewayAdditionRequestState = MutableStateFlow<GatewayAdditionRequest?>(null)
341+
internal val gatewayAdditionRequest: StateFlow<GatewayAdditionRequest?> = gatewayAdditionRequestState
342+
343+
internal fun openGatewayAddition() {
344+
gatewayAdditionRequestState.compareAndSet(null, GatewayAdditionRequest())
345+
}
346+
347+
internal fun dismissGatewayAddition(request: GatewayAdditionRequest) {
348+
gatewayAdditionRequestState.compareAndSet(request, null)
349+
}
350+
337351
private val _startOnboardingAtGatewaySetup = MutableStateFlow(false)
338352
val startOnboardingAtGatewaySetup: StateFlow<Boolean> = _startOnboardingAtGatewaySetup
339353
private val chatDraftState = MutableStateFlow<ChatDraft?>(null)
@@ -416,6 +430,7 @@ class MainViewModel private constructor(
416430
}
417431

418432
override fun onCleared() {
433+
gatewayAdditionRequestState.value = null
419434
removeChatSessionDeletionListener?.invoke()
420435
removeChatSessionDeletionListener = null
421436
attachedComposerRuntime = null
@@ -593,6 +608,8 @@ class MainViewModel private constructor(
593608
val manualHost: StateFlow<String> = prefs.manualHost
594609
val manualPort: StateFlow<Int> = prefs.manualPort
595610
val manualTls: StateFlow<Boolean> = prefs.manualTls
611+
internal val gatewayConnectionHandoff: StateFlow<GatewayConnectionHandoff> =
612+
runtimeState(initial = GatewayConnectionHandoff()) { it.gatewayConnectionHandoff }
596613
val pairedGateways: StateFlow<List<GatewayRegistryEntry>> = prefs.gatewayRegistry.entries
597614
val activeGatewayStableId: StateFlow<String?> = prefs.gatewayRegistry.activeStableId
598615
val connectedGatewayStableIds: StateFlow<List<String>> = prefs.gatewayRegistry.connectedStableIds
@@ -793,10 +810,17 @@ class MainViewModel private constructor(
793810
chatComposerState.removeMediaOwners(matches)
794811
}
795812

796-
internal fun saveGatewayConfigAndConnect(plan: GatewayConnectPlan) {
797-
// Gateway pairing touches encrypted prefs, identity files, and sockets; keep
798-
// the whole sequence off the Compose thread so retries cannot trigger ANRs.
799-
launchGatewayConnectionOperation { runtime, operation ->
813+
internal fun saveGatewayConfigAndConnect(
814+
plan: GatewayConnectPlan,
815+
addition: GatewayAdditionRequest? = null,
816+
) {
817+
if (addition != null && (gatewayAdditionRequestState.value !== addition || !canBeginQuickGatewayConnection(ensureRuntime()))) return
818+
// Only an explicitly confirmed, still-current addition enters connection admission.
819+
// Opening, editing, scanning, and dismissing the dialog never reach this boundary.
820+
launchGatewayConnectionOperation(
821+
quickSwitch = addition != null,
822+
onAdmitted = { addition?.let(::dismissGatewayAddition) },
823+
) { runtime, operation ->
800824
val config = plan.config
801825
val endpoint =
802826
GatewayEndpoint.manual(
@@ -808,6 +832,13 @@ class MainViewModel private constructor(
808832
val targetAlreadyPaired =
809833
prefs.gatewayRegistry.entries.value
810834
.any { it.stableId == endpoint.stableId }
835+
if (addition != null && targetAlreadyPaired) {
836+
// Adding an existing target selects it; replacing its credentials belongs to Manage Gateways.
837+
if (runtime.switchToGateway(endpoint.stableId, operation) == GatewayTargetSelection.Unavailable) {
838+
showUnavailableGateway(operation)
839+
}
840+
return@launchGatewayConnectionOperation
841+
}
811842
val blankCredentials = config.token.isEmpty() && config.bootstrapToken.isEmpty() && config.password.isEmpty()
812843
val preservesPairedTarget =
813844
targetAlreadyPaired && blankCredentials && plan.savedAuthAction == GatewaySavedAuthAction.REPLACE_ENDPOINT
@@ -870,7 +901,8 @@ class MainViewModel private constructor(
870901
}
871902

872903
/** Re-enters gateway setup after disconnecting and clearing one-time setup credentials. */
873-
fun pairNewGateway() {
904+
fun returnToGatewaySetup() {
905+
gatewayAdditionRequestState.value = null
874906
NodeForegroundService.stop(nodeApp)
875907
launchGatewayConfigOperation {
876908
nodeApp.peekRuntime()?.also { runtime ->
@@ -1310,6 +1342,32 @@ class MainViewModel private constructor(
13101342
}
13111343
}
13121344

1345+
fun openGatewaySettings() {
1346+
requestedSettingsRouteState.value = SettingsRoute.Gateway
1347+
_requestedHomeDestination.value = HomeDestination.Settings
1348+
}
1349+
1350+
internal fun switchGatewayFromSidebar(stableId: String) {
1351+
val runtime = ensureRuntime()
1352+
// Read owners now; Compose's last enabled state is not admission authority.
1353+
if (stableId == runtime.gatewayConnectionHandoff.value.focusedStableId) return
1354+
if (!canBeginQuickGatewayConnection(runtime)) return
1355+
launchGatewayConnectionOperation(quickSwitch = true) { owner, isCurrent ->
1356+
if (owner.switchToGateway(stableId, isCurrent) == GatewayTargetSelection.Unavailable) {
1357+
showUnavailableGateway(isCurrent)
1358+
}
1359+
}
1360+
}
1361+
1362+
private fun canBeginQuickGatewayConnection(runtime: NodeRuntime): Boolean {
1363+
if (runtime.gatewayConnectionHandoff.value.pending) return false
1364+
if (chatComposerState.hasPendingGatewaySwitchWork(currentOrProvisionalChatComposerOwner())) {
1365+
Toast.makeText(nodeApp, nativeString("Finish importing media or wait for sending before switching gateways."), Toast.LENGTH_LONG).show()
1366+
return false
1367+
}
1368+
return true
1369+
}
1370+
13131371
fun switchToGateway(stableId: String) {
13141372
launchGatewayConnectionOperation { runtime, isCurrent ->
13151373
if (runtime.switchToGateway(stableId, isCurrent) == GatewayTargetSelection.Unavailable) {
@@ -1344,16 +1402,42 @@ class MainViewModel private constructor(
13441402
NodeForegroundService.stop(nodeApp)
13451403
}
13461404

1347-
private fun launchGatewayConnectionOperation(action: suspend (NodeRuntime, NodeRuntime.GatewayConnectionOperation) -> Unit) {
1348-
val processIntent = resumeNodeServiceForConnection()
1349-
val sequence = gatewayConfigOperationSeq.incrementAndGet()
1350-
val isCurrent = { sequence == gatewayConfigOperationSeq.get() && processIntent() }
1351-
viewModelScope.launch(Dispatchers.Default) {
1405+
private fun launchGatewayConnectionOperation(
1406+
quickSwitch: Boolean = false,
1407+
onAdmitted: () -> Unit = {},
1408+
action: suspend (NodeRuntime, NodeRuntime.GatewayConnectionOperation) -> Unit,
1409+
) {
1410+
val createIntent = {
1411+
val processIntent = resumeNodeServiceForConnection()
1412+
val sequence = gatewayConfigOperationSeq.incrementAndGet()
1413+
val isCurrent = { sequence == gatewayConfigOperationSeq.get() && processIntent() }
1414+
isCurrent
1415+
}
1416+
// Preserve resume-before-startup for existing callers; a rejected quick switch has no service intent.
1417+
val existingCallerIntent = if (quickSwitch) null else createIntent()
1418+
// Publish owner-held admission before dispatch: returning Unit never means the handoff completed.
1419+
viewModelScope.launch(Dispatchers.Default, start = if (quickSwitch) CoroutineStart.UNDISPATCHED else CoroutineStart.DEFAULT) {
13521420
val runtime = ensureRuntime()
1353-
val operation = runtime.beginGatewayConnectionOperation(isCurrent) ?: return@launch
1421+
val operation =
1422+
if (quickSwitch) {
1423+
nodeApp.beginQuickGatewayConnectionOperation(runtime, createIntent)
1424+
} else {
1425+
runtime.beginGatewayConnectionOperation(requireNotNull(existingCallerIntent))
1426+
}
1427+
if (operation == null) {
1428+
if (quickSwitch && runtime.hasActiveGatewaySwitchAudio()) {
1429+
withContext(Dispatchers.Main) {
1430+
Toast.makeText(nodeApp, nativeString("Finish recording or stop dictation or Talk before switching gateways."), Toast.LENGTH_LONG).show()
1431+
}
1432+
}
1433+
return@launch
1434+
}
13541435
try {
1355-
gatewayConfigOperationMutex.withLock {
1356-
if (operation()) action(runtime, operation)
1436+
onAdmitted()
1437+
withContext(Dispatchers.Default) {
1438+
gatewayConfigOperationMutex.withLock {
1439+
if (operation()) action(runtime, operation)
1440+
}
13571441
}
13581442
} finally {
13591443
runtime.finishGatewayConnectionOperation(operation, unlessHandedOff = true)
@@ -1826,9 +1910,11 @@ class MainViewModel private constructor(
18261910
internal fun captureChatShareOwner(): ChatComposerOwner = currentOrProvisionalChatComposerOwner()
18271911

18281912
internal fun isCurrentChatComposerOwner(expected: ChatComposerOwner): Boolean =
1829-
(
1830-
currentChatComposerOwner() ?: currentOrProvisionalChatComposerOwner()
1831-
) == expected
1913+
runtimeRef.value
1914+
?.gatewayConnectionHandoff
1915+
?.value
1916+
?.pending != true &&
1917+
(currentChatComposerOwner() ?: currentOrProvisionalChatComposerOwner()) == expected
18321918

18331919
internal fun createProviderAuthController(owner: ChatComposerOwner): ProviderAuthController? {
18341920
val runtime = ensureRuntime()

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,12 @@ class NodeApp : Application() {
7070
}
7171
}
7272

73+
// Match Stop's service -> runtime lock order. Resolve the runtime before entering this monitor.
74+
internal fun beginQuickGatewayConnectionOperation(
75+
runtime: NodeRuntime,
76+
createIntent: () -> (() -> Boolean),
77+
): NodeRuntime.GatewayConnectionOperation? = synchronized(nodeServiceControlLock) { runtime.beginQuickGatewayConnectionOperation(createIntent) }
78+
7379
internal fun updateNodeServiceIntent(
7480
allowStart: Boolean,
7581
updateService: () -> Unit,

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

Lines changed: 71 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -901,6 +901,12 @@ private fun openAndroidChatStores(
901901
externalTranscriptCache = transcriptCache,
902902
)
903903

904+
/** Presentation of the connection owner's handoff, not saved intent or network health. */
905+
internal data class GatewayConnectionHandoff(
906+
val focusedStableId: String? = null,
907+
val pending: Boolean = false,
908+
)
909+
904910
internal sealed interface GatewayTargetSelection {
905911
class Selected(
906912
val isCurrent: () -> Boolean,
@@ -935,14 +941,22 @@ class NodeRuntime private constructor(
935941
private var gatewayConnectOperationsInFlight = 0
936942
private var gatewayConnectOperationsDrained = CompletableDeferred(Unit)
937943

944+
private val gatewayConnectionHandoffState = MutableStateFlow(GatewayConnectionHandoff())
945+
internal val gatewayConnectionHandoff: StateFlow<GatewayConnectionHandoff> = gatewayConnectionHandoffState.asStateFlow()
946+
938947
@Volatile private var connectingEndpoint: GatewayEndpoint? = null
948+
set(value) {
949+
field = value
950+
publishGatewayConnectionHandoff()
951+
}
939952

940953
private class GatewayConnectAttempt(
941954
val id: Long,
942955
val endpoint: GatewayEndpoint,
943956
) {
944957
val operatorReady = MutableStateFlow<GatewaySession.RequestLease?>(null)
945958
var operation: GatewayConnectionOperation? = null
959+
var chatRestoration: Job? = null
946960
}
947961

948962
private val acceptedConnectAttempt = MutableStateFlow<GatewayConnectAttempt?>(null)
@@ -1169,6 +1183,10 @@ class NodeRuntime private constructor(
11691183

11701184
private val identityStore = DeviceIdentityStore.withPrefs(appContext, prefs)
11711185
private var connectedEndpoint: GatewayEndpoint? = null
1186+
set(value) {
1187+
field = value
1188+
publishGatewayConnectionHandoff()
1189+
}
11721190

11731191
// Identity owns an established connection until disconnect/replacement, independently
11741192
// of the UI request or lifecycle sequence that originally admitted it.
@@ -1614,6 +1632,21 @@ class NodeRuntime private constructor(
16141632
private var gatewayRetirementDisplay: GatewayConnectionDisplay? = null
16151633
private var gatewayStandaloneDisplay: GatewayConnectionDisplay? = null
16161634
private var gatewayConnectionOperation: GatewayConnectionOperation? = null
1635+
set(value) {
1636+
field = value
1637+
publishGatewayConnectionHandoff()
1638+
}
1639+
1640+
private fun publishGatewayConnectionHandoff() {
1641+
gatewayConnectionHandoffState.value =
1642+
GatewayConnectionHandoff(
1643+
focusedStableId = connectedEndpoint?.stableId,
1644+
// An accepted target owns TLS/trust after its queue operation finishes.
1645+
// Socket readiness is deliberately excluded: offline composers remain usable.
1646+
pending = gatewayConnectionOperation != null || connectingEndpoint != null || acceptedConnectAttempt.value?.chatRestoration?.isCompleted == false,
1647+
)
1648+
}
1649+
16171650
private var tlsProbeJob: Job? = null
16181651

16191652
internal class GatewayConnectionOperation(
@@ -3722,7 +3755,6 @@ class NodeRuntime private constructor(
37223755
}
37233756
beginConnect(endpoint, resolveGatewayConnectAuth(endpoint, explicitAuth), intent)
37243757
}
3725-
chat.restoreSelectedGatewayOfflineState()
37263758
return intent()
37273759
} finally {
37283760
finishGatewayConnectionOperation(intent, unlessHandedOff = true)
@@ -3889,10 +3921,15 @@ class NodeRuntime private constructor(
38893921
setVoiceCaptureMode(if (value) VoiceCaptureMode.ManualMic else VoiceCaptureMode.Off)
38903922
}
38913923

3924+
internal fun hasActiveGatewaySwitchAudio(): Boolean =
3925+
synchronized(voiceCaptureOwnershipLock) {
3926+
voiceNoteOwnsMic || dictationOwnsMic || !isVoiceCaptureModeActive(VoiceCaptureMode.Off)
3927+
}
3928+
38923929
internal fun tryAcquireVoiceNoteMic(): Boolean {
38933930
val suppressionUpdate =
38943931
synchronized(voiceCaptureOwnershipLock) {
3895-
if (voiceNoteOwnsMic || dictationOwnsMic || !isVoiceCaptureModeActive(VoiceCaptureMode.Off)) return false
3932+
if (gatewayConnectionHandoff.value.pending || voiceNoteOwnsMic || dictationOwnsMic || !isVoiceCaptureModeActive(VoiceCaptureMode.Off)) return false
38963933
voiceNoteOwnsMic = true
38973934
createVoiceWakeSuppressionUpdateLocked(VoiceWakeSuppressionReason.VoiceNote, true)
38983935
}
@@ -3913,6 +3950,7 @@ class NodeRuntime private constructor(
39133950
val suppressionUpdate =
39143951
synchronized(voiceCaptureOwnershipLock) {
39153952
if (
3953+
gatewayConnectionHandoff.value.pending ||
39163954
dictationOwnsMic ||
39173955
voiceNoteOwnsMic ||
39183956
cameraAudioOwnsMic ||
@@ -4448,7 +4486,7 @@ class NodeRuntime private constructor(
44484486
var ownershipEpoch = 0L
44494487
val suppressionUpdate =
44504488
synchronized(voiceCaptureOwnershipLock) {
4451-
if (mode != VoiceCaptureMode.Off && (voiceNoteOwnsMic || dictationOwnsMic)) return
4489+
if (mode != VoiceCaptureMode.Off && (gatewayConnectionHandoff.value.pending || voiceNoteOwnsMic || dictationOwnsMic)) return
44524490
if (mode != VoiceCaptureMode.Off && cameraAudioOwnsMic) return
44534491
// Every mode command cancels queued PTT intent; only a real transition replaces the capture owner.
44544492
talkPttCommandEpoch.incrementAndGet()
@@ -4720,6 +4758,20 @@ class NodeRuntime private constructor(
47204758
}
47214759
}
47224760

4761+
/** NodeApp holds service control before this lifecycle/microphone admission, matching Stop's lock order. */
4762+
internal fun beginQuickGatewayConnectionOperation(
4763+
createIntent: () -> (() -> Boolean),
4764+
): GatewayConnectionOperation? =
4765+
synchronized(gatewayLifecycleIntentLock) {
4766+
synchronized(voiceCaptureOwnershipLock) {
4767+
if (gatewayConnectionHandoff.value.pending || hasActiveGatewaySwitchAudio()) {
4768+
null
4769+
} else {
4770+
beginGatewayConnectionOperation(createIntent())
4771+
}
4772+
}
4773+
}
4774+
47234775
internal fun beginGatewayConnectionOperation(isCurrent: () -> Boolean): GatewayConnectionOperation? =
47244776
synchronized(gatewayLifecycleIntentLock) {
47254777
if (!isCurrent()) return@synchronized null
@@ -4958,6 +5010,17 @@ class NodeRuntime private constructor(
49585010
val connectAttemptId = beginConnectAttempt(endpoint, intent)
49595011
connectingEndpoint = endpoint
49605012
chat.onGatewayScopeChanging()
5013+
val attempt = checkNotNull(acceptedConnectAttempt.value)
5014+
val restoration = scope.launch(start = CoroutineStart.LAZY) { chat.restoreSelectedGatewayOfflineState() }
5015+
attempt.chatRestoration = restoration
5016+
restoration.invokeOnCompletion {
5017+
synchronized(gatewayLifecycleIntentLock) {
5018+
if (acceptedConnectAttempt.value === attempt) publishGatewayConnectionHandoff()
5019+
}
5020+
}
5021+
// The real local-hydration job belongs to this attempt, independently of TLS admission.
5022+
// Do not hold the switch mutex or prevent a trust decision while the local cache loads.
5023+
restoration.start()
49615024
_pendingGatewayTrust.value = null
49625025
val tls = connectionManager.resolveTlsParams(endpoint)
49635026
if (tls?.required == true) {
@@ -4977,7 +5040,10 @@ class NodeRuntime private constructor(
49775040
}
49785041
}
49795042
} catch (error: Throwable) {
4980-
finishGatewayConnectionOperation(intent)
5043+
synchronized(gatewayLifecycleIntentLock) {
5044+
if (isCurrentConnectAttempt(connectAttemptId)) clearAcceptedConnectAttempt()
5045+
finishGatewayConnectionOperation(intent)
5046+
}
49815047
throw error
49825048
}
49835049
synchronized(gatewayLifecycleIntentLock) {
@@ -5064,6 +5130,7 @@ class NodeRuntime private constructor(
50645130
synchronized(gatewayLifecycleIntentLock) {
50655131
val attempt = acceptedConnectAttempt.value
50665132
acceptedConnectAttempt.value = null
5133+
attempt?.chatRestoration?.cancel()
50675134
// Retiring the target also retires its TLS presentation, even if replacement disappears while queued.
50685135
if (attempt != null) synchronized(gatewayStatusLock) { gatewayStandaloneDisplay = null }
50695136
tlsProbeJob?.cancel()

0 commit comments

Comments
 (0)