@@ -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()
0 commit comments