Fix/issue 470 stuck reconnecting (#495)
* fix(ws): stop chat opening from racing the singleton into a stuck RECONNECTING Root cause: HermesWsClient is a global singleton connected once at login; every tab observes its single connectionStatus. ChatViewModel is recreated on every chat-tab open and its init calls connectWebSocket() -> wsClient.connect(). connect() only guarded the CONNECTED case, so when the socket had dropped (singleton in RECONNECTING with its own scheduled reconnect) opening chat spawned a SECOND socket on the same webSocket field. The orphaned socket's later onClosed set connected=false + re-armed RECONNECTING after the new socket connected, and currentBackoff kept resetting on each chat open, leaving the status stuck on RECONNECTING while every other tab (which never calls connect()) stayed healthy. Fix: - HermesWsClient.connect() now no-ops while CONNECTING/RECONNECTING (in-flight socket already pending) and while AUTH_EXPIRED (needs re-auth, not a loop). - ChatViewModel.connectWebSocket() mirrors the same terminal-state guard so the chat tab never disturbs an already-working or already-recovering connection. Behavior-preserving: happy path (CONNECTED) and genuine terminal states (DISCONNECTED/NO_NETWORK) still connect as before. * fix(#470): sync cookie store scope with selected profile ID Update AuthManager to switch CookieManager to the active server profile ID on startup and on runtime profile change. * fix(#470): prevent stale token cache and load initial cookie scope Pass active profile scope to CookieManager.initialize on startup and update setProfileToken to sync the in-memory cachedToken. * feat(chat): add re-login action and credentials popup to connection banner Add a Re-login button to the connection status banner and a dialog to prompt for credentials, allowing the user to refresh session cookies/tokens and reconnect the WebSocket. * fix(chat): address PR #495 review feedback * fix(chat): restore reconnect action in banner * fix: resolve composable invocation in ReloginDialog * fix(chat): enable re-login action during reconnecting state Add the Re-login button to the connection status banner when connectionStatus is RECONNECTING, allowing users to re-authenticate and resolve stuck reconnect loops.
This commit is contained in:
6 files changed
+319
-21
No files matched your search
@@ -109,7 +109,6 @@ import androidx.core.content.FileProvider
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import coil.compose.AsyncImage
|
||||
import com.m57.hermescontrol.AuthLoginScreen
|
||||
import com.m57.hermescontrol.NavigationController
|
||||
import com.m57.hermescontrol.R
|
||||
import com.m57.hermescontrol.data.model.Attachment
|
||||
@@ -148,6 +147,7 @@ fun ChatScreen(
|
||||
var inputText by rememberSaveable { mutableStateOf("") }
|
||||
var isListening by rememberSaveable { mutableStateOf(false) }
|
||||
var lastAnimatedMessageId by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var showReloginDialog by rememberSaveable { mutableStateOf(false) }
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
val isDark = isSystemInDarkTheme()
|
||||
val context = LocalContext.current
|
||||
@@ -362,7 +362,7 @@ fun ChatScreen(
|
||||
ChatTopBanner(
|
||||
connectionStatus = state.connectionStatus,
|
||||
onReconnect = viewModel::reconnect,
|
||||
onAuthExpired = { NavigationController.navigateTo(AuthLoginScreen) },
|
||||
onReloginClick = { showReloginDialog = true },
|
||||
)
|
||||
|
||||
Box(
|
||||
@@ -480,6 +480,15 @@ fun ChatScreen(
|
||||
onRemoveAttachment = viewModel::removeAttachment,
|
||||
)
|
||||
}
|
||||
|
||||
if (showReloginDialog) {
|
||||
ReloginDialog(
|
||||
onDismiss = { showReloginDialog = false },
|
||||
onRelogin = { username, password, onResult ->
|
||||
viewModel.relogin(username, password, onResult)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1340,7 +1349,7 @@ private fun ChatLifecycleEffects(
|
||||
private fun ChatTopBanner(
|
||||
connectionStatus: ConnectionStatus,
|
||||
onReconnect: () -> Unit,
|
||||
onAuthExpired: () -> Unit,
|
||||
onReloginClick: () -> Unit,
|
||||
) {
|
||||
val isShown =
|
||||
connectionStatus != ConnectionStatus.CONNECTED &&
|
||||
@@ -1384,9 +1393,30 @@ private fun ChatTopBanner(
|
||||
)
|
||||
}
|
||||
when (connectionStatus) {
|
||||
ConnectionStatus.DISCONNECTED,
|
||||
ConnectionStatus.NO_NETWORK,
|
||||
-> {
|
||||
ConnectionStatus.DISCONNECTED -> {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
TextButton(
|
||||
onClick = onReloginClick,
|
||||
colors =
|
||||
androidx.compose.material3.ButtonDefaults.textButtonColors(
|
||||
contentColor = LocalHermesStatusColors.current.error,
|
||||
),
|
||||
) {
|
||||
Text(stringResource(R.string.chat_action_relogin))
|
||||
}
|
||||
TextButton(
|
||||
onClick = onReconnect,
|
||||
colors =
|
||||
androidx.compose.material3.ButtonDefaults.textButtonColors(
|
||||
contentColor = LocalHermesStatusColors.current.error,
|
||||
),
|
||||
) {
|
||||
Text(stringResource(R.string.chat_action_reconnect))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ConnectionStatus.NO_NETWORK -> {
|
||||
TextButton(
|
||||
onClick = onReconnect,
|
||||
colors =
|
||||
@@ -1397,18 +1427,22 @@ private fun ChatTopBanner(
|
||||
Text(stringResource(R.string.chat_action_reconnect))
|
||||
}
|
||||
}
|
||||
ConnectionStatus.AUTH_EXPIRED -> {
|
||||
|
||||
ConnectionStatus.RECONNECTING,
|
||||
ConnectionStatus.AUTH_EXPIRED,
|
||||
-> {
|
||||
TextButton(
|
||||
onClick = onAuthExpired,
|
||||
onClick = onReloginClick,
|
||||
colors =
|
||||
androidx.compose.material3.ButtonDefaults.textButtonColors(
|
||||
contentColor = LocalHermesStatusColors.current.error,
|
||||
),
|
||||
) {
|
||||
Text(stringResource(R.string.chat_action_sign_in))
|
||||
Text(stringResource(R.string.chat_action_relogin))
|
||||
}
|
||||
}
|
||||
else -> { /* RECONNECTING: auto, no button */ }
|
||||
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1627,3 +1661,99 @@ private fun BoxScope.ChatScrollToBottomFab(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ReloginDialog(
|
||||
onDismiss: () -> Unit,
|
||||
onRelogin: (String, String, (Boolean, String?) -> Unit) -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val statusColors = LocalHermesStatusColors.current
|
||||
var username by rememberSaveable { mutableStateOf("") }
|
||||
var password by rememberSaveable { mutableStateOf("") }
|
||||
var isLoading by remember { mutableStateOf(false) }
|
||||
var errorMessage by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = { if (!isLoading) onDismiss() },
|
||||
title = { Text(stringResource(R.string.chat_relogin_title)) },
|
||||
text = {
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = username,
|
||||
onValueChange = {
|
||||
username = it
|
||||
errorMessage = null
|
||||
},
|
||||
label = { Text(stringResource(R.string.chat_relogin_username)) },
|
||||
singleLine = true,
|
||||
enabled = !isLoading,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = password,
|
||||
onValueChange = {
|
||||
password = it
|
||||
errorMessage = null
|
||||
},
|
||||
label = { Text(stringResource(R.string.chat_relogin_password)) },
|
||||
singleLine = true,
|
||||
enabled = !isLoading,
|
||||
visualTransformation =
|
||||
androidx.compose.ui.text.input
|
||||
.PasswordVisualTransformation(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
if (errorMessage != null) {
|
||||
Text(
|
||||
text = errorMessage!!,
|
||||
color = statusColors.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
enabled = !isLoading,
|
||||
onClick = {
|
||||
if (username.isBlank() || password.isBlank()) {
|
||||
errorMessage = context.getString(R.string.chat_relogin_error_empty)
|
||||
return@TextButton
|
||||
}
|
||||
isLoading = true
|
||||
errorMessage = null
|
||||
onRelogin(username, password) { success, error ->
|
||||
isLoading = false
|
||||
if (success) {
|
||||
onDismiss()
|
||||
} else {
|
||||
errorMessage = error ?: "Unknown error"
|
||||
}
|
||||
}
|
||||
},
|
||||
) {
|
||||
if (isLoading) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
strokeWidth = 2.dp,
|
||||
color = statusColors.info,
|
||||
)
|
||||
} else {
|
||||
Text(stringResource(R.string.chat_relogin_submit))
|
||||
}
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(
|
||||
enabled = !isLoading,
|
||||
onClick = onDismiss,
|
||||
) {
|
||||
Text(stringResource(R.string.chat_relogin_cancel))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -34,6 +34,10 @@ import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import kotlinx.serialization.json.decodeFromJsonElement
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
private const val TAG = "ChatViewModel"
|
||||
@@ -195,6 +199,20 @@ class ChatViewModel(
|
||||
private fun connectWebSocket(setLoading: Boolean = false) {
|
||||
val token = AuthManager.getToken() ?: return
|
||||
|
||||
// Don't disturb an already-working (or already-recovering) connection.
|
||||
// HermesWsClient is a global singleton shared by every tab; the chat tab
|
||||
// is recreated on every open, so calling connect() here must be a no-op
|
||||
// unless the singleton is in a terminal state. Re-entering connect() while
|
||||
// it is CONNECTING/RECONNECTING races the in-flight socket and can leave
|
||||
// the status stuck on RECONNECTING (see HermesWsClient.connect).
|
||||
val status = wsClient.connectionStatus.value
|
||||
if (status == ConnectionStatus.CONNECTING ||
|
||||
status == ConnectionStatus.RECONNECTING ||
|
||||
status == ConnectionStatus.AUTH_EXPIRED
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
if (setLoading) {
|
||||
_uiState.update { it.copy(isLoading = true) }
|
||||
}
|
||||
@@ -1079,6 +1097,105 @@ class ChatViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
fun relogin(
|
||||
username: String,
|
||||
password: String,
|
||||
onResult: (Boolean, String?) -> Unit,
|
||||
) {
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
val host = AuthManager.getHost()
|
||||
val port = AuthManager.getPort()
|
||||
val baseUrl = "http://$host:$port"
|
||||
val jsonMediaType = "application/json; charset=utf-8".toMediaType()
|
||||
val jsonBody =
|
||||
JSONObject()
|
||||
.put("provider", "basic")
|
||||
.put("username", username)
|
||||
.put("password", password)
|
||||
.put("next", "")
|
||||
.toString()
|
||||
|
||||
try {
|
||||
val loginClient =
|
||||
com.m57.hermescontrol.data.remote.OkHttpProvider.probe
|
||||
.newBuilder()
|
||||
.connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
val loginReq =
|
||||
Request
|
||||
.Builder()
|
||||
.url("$baseUrl/auth/password-login")
|
||||
.header("Content-Type", "application/json")
|
||||
.post(jsonBody.toRequestBody(jsonMediaType))
|
||||
.build()
|
||||
loginClient.newCall(loginReq).execute().use { loginResp ->
|
||||
if (!loginResp.isSuccessful) {
|
||||
val msg =
|
||||
when (loginResp.code) {
|
||||
401 -> "Invalid username or password (401)"
|
||||
403 -> "Forbidden (403)"
|
||||
else -> "HTTP error code: ${loginResp.code}"
|
||||
}
|
||||
withContext(Dispatchers.Main) {
|
||||
onResult(false, msg)
|
||||
}
|
||||
return@launch
|
||||
}
|
||||
}
|
||||
|
||||
val ticketClient =
|
||||
com.m57.hermescontrol.data.remote.OkHttpProvider.base
|
||||
.newBuilder()
|
||||
.connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
val ticketReq =
|
||||
Request
|
||||
.Builder()
|
||||
.url("$baseUrl/api/auth/ws-ticket")
|
||||
.post("{}".toRequestBody(jsonMediaType))
|
||||
.build()
|
||||
ticketClient.newCall(ticketReq).execute().use { ticketResp ->
|
||||
if (!ticketResp.isSuccessful) {
|
||||
withContext(Dispatchers.Main) {
|
||||
onResult(false, "Failed to mint WS ticket: HTTP ${ticketResp.code}")
|
||||
}
|
||||
return@launch
|
||||
}
|
||||
|
||||
val body = ticketResp.body?.string().orEmpty()
|
||||
val ticket = JSONObject(body).optString("ticket").takeIf { it.isNotBlank() }
|
||||
|
||||
if (ticket.isNullOrBlank()) {
|
||||
withContext(Dispatchers.Main) {
|
||||
onResult(false, "Invalid ticket returned from server")
|
||||
}
|
||||
return@launch
|
||||
}
|
||||
|
||||
AuthManager.setWsAuthParam("ticket")
|
||||
AuthManager.setToken(ticket)
|
||||
|
||||
withContext(Dispatchers.Main) {
|
||||
onResult(true, null)
|
||||
reconnect()
|
||||
}
|
||||
}
|
||||
} catch (e: java.io.IOException) {
|
||||
withContext(Dispatchers.Main) {
|
||||
onResult(false, "Connection failed: ${e.message}")
|
||||
}
|
||||
} catch (e: org.json.JSONException) {
|
||||
withContext(Dispatchers.Main) {
|
||||
onResult(false, "Connection failed: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun addSystemMessage(
|
||||
text: String,
|
||||
persist: Boolean = false,
|
||||
|
||||
Reference in new issue
Block a user