From 71b2e847cf90f6659763226f14f788994758cb9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaroslav=20Bene=C5=A1?= Date: Tue, 1 Dec 2026 19:22:40 +0000 Subject: [PATCH] Connect as the other LLeMbas clients do: address, identity, refused token, streams, words MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - One address rule (api/Address.kt): scheme in any case, host lower-cased, path, query and fragment dropped; an http:// address is answered at the address step (this app needs https). - User-Agent llembas-android/ on every request, and the same string as the device code's client_id (the server only stores and shows it). - A 401 of the instance's own (WWW-Authenticate: Bearer realm="lembas") marks the instance whose token it was as signed out: nothing more is asked with it, its pages stay underneath a page that offers the sign-in in one step, and nothing else is forgotten. A 403 stays the server's sentence; a 401 passed on from a provider behind /v1 signs nobody out. - Streams: 45 s of silence is a broken connection (the server's keepalive is every 15 s on all three routes); reconnect 1 s doubling to 60 s, jittered ±20 %, short again only after 30 s of health; a 429 waits for Retry-After. - A sentence for each failure: unreachable, timeout, certificate not trusted, not LLeMbas, "the server answered N", too old, too new. Sign-in polls end by their real reason and survive a dropped network or a restarting server. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 39 ++ .../main/java/eu/llembas/android/LembasApp.kt | 20 +- .../java/eu/llembas/android/MainActivity.kt | 44 +- .../java/eu/llembas/android/api/Address.kt | 51 ++ .../java/eu/llembas/android/api/ApiClient.kt | 51 +- .../java/eu/llembas/android/api/Identity.kt | 91 ++++ .../eu/llembas/android/api/StreamClient.kt | 71 ++- .../android/assist/AssistController.kt | 8 +- .../java/eu/llembas/android/auth/Instances.kt | 39 +- .../main/java/eu/llembas/android/ui/Errors.kt | 89 +++- .../llembas/android/ui/chat/ChatViewModel.kt | 23 +- .../llembas/android/ui/signin/SignInScreen.kt | 163 ++++++- app/src/main/res/values-cs/strings.xml | 11 + app/src/main/res/values-de/strings.xml | 11 + app/src/main/res/values-es/strings.xml | 11 + app/src/main/res/values-fr/strings.xml | 11 + app/src/main/res/values-hu/strings.xml | 11 + app/src/main/res/values-it/strings.xml | 11 + app/src/main/res/values-pl/strings.xml | 11 + app/src/main/res/values-sk/strings.xml | 11 + app/src/main/res/values/strings.xml | 11 + .../java/eu/llembas/android/ClientTest.kt | 7 - .../java/eu/llembas/android/ConnectionTest.kt | 440 ++++++++++++++++++ scripts/strings.py | 13 + scripts/strings_own.json | 104 ++++- 25 files changed, 1256 insertions(+), 96 deletions(-) create mode 100644 app/src/main/java/eu/llembas/android/api/Address.kt create mode 100644 app/src/main/java/eu/llembas/android/api/Identity.kt create mode 100644 app/src/test/java/eu/llembas/android/ConnectionTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index b21b86c..cb9d318 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,45 @@ What changed in each release of LLeMbas for Android. Versions follow SemVer; until 1.0.0 the app is in alpha and releases come off `main`. +## Unreleased + +How the app connects to an instance, brought in line with the other LLeMbas clients. Fixes only. + +### Fixed + +- **An instance that signed the phone out is noticed.** When an instance refuses the app's token + (it was revoked there, or it expired), that instance -- not whichever happens to be in use -- + is marked signed out, nothing more is asked with the dead token, and a page offers *Sign in + again* in one step. Chats being written, the settings kept for the instance and every other + instance stay as they were. Before, each screen showed the server's refusal and the app went on + as if signed in. A "not allowed" (403) is still just the server's sentence, and a refusal + passed on from a provider behind the instance signs nobody out. +- **One rule for the address.** `HTTPS://Example.org/`, `example.org/chat?x=1` and + `example.org:8443/` are read as the other LLeMbas clients read them: the scheme in any case, + the host in lower case, the path dropped. An `http://` address is answered where it is typed + -- this app needs https -- instead of failing later with a library's error. +- **Each failure says what it is.** Cannot be reached, did not answer in time, a certificate the + phone does not trust (with where to install the CA), no LLeMbas instance at the address, "the + server answered 502", an instance too old, an app too old: one sentence each. A server in + trouble is no longer "not a LLeMbas instance", and another service is no longer "an older + LLeMbas". +- **A sign-in ends by its real reason.** Only an expired code is "the code expired"; a server + that restarts or a network that drops while you approve in the browser no longer ends the + sign-in; too many sign-ins is said in the server's words. Cancelling a sign-in no longer + leaves an error line under the address. +- **A dead connection is noticed.** A stream that says nothing for 45 seconds (the instance + sends a keepalive every 15) is opened again, instead of being followed for ever after the + phone changed network. +- **One reconnect schedule.** Streams are opened again after 1 second doubling to 60, each + jittered by a fifth, and quickly again only after a connection held for half a minute. "Too + many requests" (429) waits as long as the instance asks. + +### Changed + +- **The app names itself.** Every request carries `User-Agent: llembas-android/`, and + the sign-in sends the same string, so an instance's list of devices shows which app and + version signed in. + ## [1.0.0-beta.16] — 2026-11-26 ### Added diff --git a/app/src/main/java/eu/llembas/android/LembasApp.kt b/app/src/main/java/eu/llembas/android/LembasApp.kt index 320cb33..5ab4df1 100644 --- a/app/src/main/java/eu/llembas/android/LembasApp.kt +++ b/app/src/main/java/eu/llembas/android/LembasApp.kt @@ -13,6 +13,7 @@ import android.os.Bundle import androidx.core.content.ContextCompat import eu.llembas.android.api.EventsHub import eu.llembas.android.api.Frame +import eu.llembas.android.api.RefusedTokens import eu.llembas.android.api.StreamClient import eu.llembas.android.auth.InstanceStore import eu.llembas.android.wake.AppVisibility @@ -20,14 +21,17 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.launch /** The process: one store of instances, and the notification channels, made once. */ class LembasApp : Application() { lateinit var instances: InstanceStore private set + private val background = CoroutineScope(SupervisorJob() + Dispatchers.Default) + /** The one connection to the person's events route, shared by all that watch it. */ - val events = EventsHub(CoroutineScope(SupervisorJob() + Dispatchers.Default)) + val events = EventsHub(background) /** * The events route of the instance in use, as its frames; null when not signed in. Whoever @@ -35,10 +39,13 @@ class LembasApp : Application() { * a scope that outlives the screen: the connection is open for as long as anybody listens. */ suspend fun eventFrames(): Flow? { - val instance = instances.current() ?: return null + // An instance that signed this phone out is asked nothing more: its route is not opened. + val instance = instances.current()?.takeUnless { it.signedOut } ?: return null val api = instances.clientFor(instance) // Every opening of the route waits at the gate: it is not opened, or opened again, behind a lock. - return events.frames(instance.id) { StreamClient(api).watch(turn = { gate.pass() }) { api.events() } } + // The line is the token's, not only the instance's: after a sign-in again the route is + // opened with the new token, never taken up with the one the instance refused. + return events.frames(eventsKey(instance.id, instance.sealedToken)) { StreamClient(api).watch(turn = { gate.pass() }) { api.events() } } } /** Whether a new request with the account's files may start: the app in front, the phone unlocked. */ @@ -47,6 +54,10 @@ class LembasApp : Application() { override fun onCreate() { super.onCreate() instances = InstanceStore(this) + // A token the instance refuses (a 401 of its own, on any request: a call, a stream, a + // download) signs out the instance that token belongs to -- that one only, and nothing + // else is forgotten. Its screens then offer the sign-in (MainActivity). + RefusedTokens.heard = { token -> background.launch { runCatching { instances.refused(token) } } } // Copies of the account's files left by a process that was killed. A viewer's own are // nobody's now; one another app was handed may still be read there (a mail being // written), so those go by their age only. @@ -126,3 +137,6 @@ class LembasApp : Application() { } val android.content.Context.lembas: LembasApp get() = applicationContext as LembasApp + +/** What names one connection to an instance's events route: the instance and the token it is followed with. */ +fun eventsKey(instanceId: String, sealedToken: String): String = instanceId + "#" + sealedToken.hashCode() diff --git a/app/src/main/java/eu/llembas/android/MainActivity.kt b/app/src/main/java/eu/llembas/android/MainActivity.kt index 7ad02c2..773b1dc 100644 --- a/app/src/main/java/eu/llembas/android/MainActivity.kt +++ b/app/src/main/java/eu/llembas/android/MainActivity.kt @@ -18,6 +18,7 @@ import androidx.compose.material3.Surface import androidx.compose.material3.rememberDrawerState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.key @@ -25,6 +26,8 @@ import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.core.content.ContextCompat import androidx.lifecycle.Lifecycle @@ -62,6 +65,7 @@ import eu.llembas.android.ui.scheduled.SchedulingModelsScreen import eu.llembas.android.ui.settings.McpScreen import eu.llembas.android.ui.settings.SettingsScreen import eu.llembas.android.ui.signin.SignInScreen +import eu.llembas.android.ui.signin.SignedOutScreen import eu.llembas.android.ui.theme.LembasTheme import eu.llembas.android.update.ReleaseCheck import eu.llembas.android.wake.WakeBootReceiver @@ -176,7 +180,45 @@ class MainActivity : ComponentActivity() { when { loaded == null -> Box(Modifier.fillMaxSize()) instance == null -> SignInScreen() - else -> key(instance.id) { Home(instance, open, opened) } + else -> key(instance.id) { Signed(instance, open, opened) } + } + } + + /** + * The instance in use: its pages, and over them the way back in when the instance signed + * this phone out (it refused the token). The pages stay underneath as they were -- a message + * half written is there again after the sign-in -- and ask the instance nothing meanwhile + * (no client is handed out for a signed-out instance). An instance that was signed out + * before its pages were ever up has none to keep: they are made after the sign-in. + */ + @Composable + private fun Signed(instance: Instance, open: Opening?, opened: () -> Unit) { + val scope = rememberCoroutineScope() + var up by rememberSaveable { mutableStateOf(false) } + if (!instance.signedOut && !up) SideEffect { up = true } + Box(Modifier.fillMaxSize()) { + if (up || !instance.signedOut) Home(instance, open, opened) + if (instance.signedOut) { + val all by lembas.instances.instances.collectAsState(initial = emptyList()) + SignedOutScreen( + instance = instance, + others = all.filter { it.id != instance.id }, + onUse = { other -> + scope.launch { + lembas.instances.use(other.id) + FileCache.clear(this@MainActivity) + } + }, + onRemove = { + scope.launch { + Push.disable(this@MainActivity, instance) + lembas.instances.remove(instance.id) + // The copies of the account's files this phone held go with it. + FileCache.clear(this@MainActivity) + } + }, + ) + } } } diff --git a/app/src/main/java/eu/llembas/android/api/Address.kt b/app/src/main/java/eu/llembas/android/api/Address.kt new file mode 100644 index 0000000..5aba289 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/api/Address.kt @@ -0,0 +1,51 @@ +package eu.llembas.android.api + +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull + +/** + * What a typed address is, by the one rule every LLeMbas client reads an address with: trimmed; + * `https://` when no scheme was typed (a scheme is read whatever its case); http and https only; + * the scheme, the host in lower case and a port that is not the scheme's own are kept; a path, a + * query, a fragment and a trailing slash are dropped. + * + * This app talks https only (Android's network policy of the app forbids cleartext), so an + * `http://` address is its own answer: said in words where the address is typed, not as a + * library's error three steps later. + */ +sealed interface Address { + /** An instance's base URL: `https://host` or `https://host:port`, nothing after it. */ + data class Base(val url: String) : Address + + /** Nothing was typed. */ + data object Empty : Address + + /** `http://…`: an address the rule accepts and this app cannot use. */ + data object NeedsHttps : Address + + /** Another scheme (`ftp://…`): no LLeMbas client reads it. */ + data object NotHttp : Address + + /** Not an address at all (no host, a port that is no number). */ + data object Unreadable : Address +} + +private val SCHEME = Regex("^([A-Za-z][A-Za-z0-9+.-]*)://") + +/** [typed] as an [Address]. Pure: nothing is looked up, nothing is asked. */ +fun address(typed: String): Address { + val text = typed.trim() + if (text.isEmpty()) return Address.Empty + val scheme = SCHEME.find(text)?.groupValues?.get(1)?.lowercase() + val rest = if (scheme == null) text else text.substring(text.indexOf("://") + 3) + return when (scheme) { + null, "https" -> { + val url = "https://$rest".toHttpUrlOrNull() ?: return Address.Unreadable + val base = url.newBuilder().username("").password("").encodedPath("/").query(null).fragment(null).build() + Address.Base(base.toString().trimEnd('/')) + } + + "http" -> Address.NeedsHttps + + else -> Address.NotHttp + } +} diff --git a/app/src/main/java/eu/llembas/android/api/ApiClient.kt b/app/src/main/java/eu/llembas/android/api/ApiClient.kt index b12faf9..8fda3c3 100644 --- a/app/src/main/java/eu/llembas/android/api/ApiClient.kt +++ b/app/src/main/java/eu/llembas/android/api/ApiClient.kt @@ -33,8 +33,14 @@ import kotlin.coroutines.resumeWithException /** Where a new agent chat runs: a linked device ([LinkedDevice.id]) and a folder on it. */ data class AgentTarget(val device: String, val directory: String = "") -/** A refusal from the server, in its own words (`{"detail": "…"}`). */ -class ApiException(val status: Int, message: String) : IOException(message) +/** + * A refusal from the server, in its own words (`{"detail": "…"}`). [retryAfter] is the seconds a + * 429 asked the caller to wait (`Retry-After`), where it said so. + */ +class ApiException(val status: Int, message: String, val retryAfter: Long? = null) : IOException(message) + +/** An address that answered, and is no LLeMbas instance: no discovery document, or another service's. */ +class NotLembas : IOException("Not a LLeMbas instance.") private val JSON = "application/json; charset=utf-8".toMediaType() @@ -44,6 +50,8 @@ val SharedHttp: OkHttpClient by lazy { .connectTimeout(15, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .writeTimeout(120, TimeUnit.SECONDS) + // Every request says which app asks, and a token the instance refuses is heard once, here. + .addInterceptor(Identity()) .build() } @@ -60,27 +68,26 @@ suspend fun Call.await(): Response = suspendCancellableCoroutine { cont -> cont.invokeOnCancellation { runCatching { cancel() } } } -/** The address a person typed, as the instance's base URL: https assumed, no trailing slash. */ -fun normaliseBase(typed: String): String { - var text = typed.trim().trimEnd('/') - if (!text.startsWith("http://") && !text.startsWith("https://")) text = "https://$text" - return text.toHttpUrl().toString().trimEnd('/') -} - /** The calls that need no token: finding the instance and signing in. */ class Doorstep(private val http: OkHttpClient = SharedHttp) { suspend fun discover(base: String): Discovery { val response = http.newCall(Request.Builder().url("$base/.well-known/lembas.json").build()).await() return response.use { - if (!it.isSuccessful) throw ApiException(it.code, "Not a LLeMbas instance (${it.code}).") - LembasJson.decodeFromString(Discovery.serializer(), it.body!!.string()) + // No such document: something else lives at the address. Any other refusal -- a proxy + // whose server is down (502), a server that is starting -- is the server's answer, + // said with its number: it may well be a LLeMbas instance. + if (it.code == 404) throw NotLembas() + if (!it.isSuccessful) throw ApiException(it.code, "") + val text = it.body?.string().orEmpty() + // A page, or another program's JSON, is not the document either. + runCatching { LembasJson.decodeFromString(Discovery.serializer(), text) }.getOrNull() ?: throw NotLembas() } } suspend fun deviceCode(url: String, deviceName: String, model: String): DeviceCode { val body = buildJsonObject { put("scope", "app models") - put("client_id", "lembas-android") + put("client_id", USER_AGENT) put("device_name", deviceName) put("device_host", model) put("device_platform", "android") @@ -92,14 +99,23 @@ class Doorstep(private val http: OkHttpClient = SharedHttp) { } } - /** One poll. A pending login is a 400 with `authorization_pending` -- not a failure. */ + /** + * One poll. A pending login is a 400 with `authorization_pending` -- not a failure. An answer + * that is no such document (a proxy's 502 page, a 429) is the server's refusal with its + * number, never "the code expired". + */ suspend fun deviceToken(url: String, deviceCode: String): DeviceToken { val body = buildJsonObject { put("grant_type", "urn:ietf:params:oauth:grant-type:device_code") put("device_code", deviceCode) } val response = http.newCall(post(url, body)).await() - return response.use { LembasJson.decodeFromString(DeviceToken.serializer(), it.body!!.string()) } + return response.use { + val text = it.body?.string().orEmpty() + val said = runCatching { LembasJson.decodeFromString(DeviceToken.serializer(), text) }.getOrNull() + if (said != null && (said.accessToken != null || said.error != null)) return@use said + throw ApiException(it.code, refusal(text).orEmpty(), retryAfterSeconds(it.header("Retry-After"))) + } } private fun post(url: String, body: JsonObject) = Request.Builder().url(url).post(body.toString().toRequestBody(JSON)).build() @@ -116,13 +132,14 @@ internal fun detail(response: Response): String { } /** - * The server's own sentence in a refusal's body: `detail` on `/api/v2`, and OpenAI's shape - * (`error.message`) on `/v1`, where speech lives. Null when the body says neither. + * The server's own sentence in a refusal's body: `detail` on `/api/v2`, OpenAI's shape + * (`error.message`) on `/v1`, where speech lives, and the sign-in's (`error_description`, RFC + * 8628). Null when the body says none of them. */ internal fun refusal(body: String): String? = runCatching { val said = LembasJson.parseToJsonElement(body) as JsonObject fun words(of: Any?): String? = (of as? JsonPrimitive)?.takeUnless { it is JsonNull }?.content?.ifBlank { null } - words(said["detail"]) ?: words((said["error"] as? JsonObject)?.get("message")) + words(said["detail"]) ?: words((said["error"] as? JsonObject)?.get("message")) ?: words(said["error_description"]) }.getOrNull() /** diff --git a/app/src/main/java/eu/llembas/android/api/Identity.kt b/app/src/main/java/eu/llembas/android/api/Identity.kt new file mode 100644 index 0000000..86fbb8a --- /dev/null +++ b/app/src/main/java/eu/llembas/android/api/Identity.kt @@ -0,0 +1,91 @@ +package eu.llembas.android.api + +import eu.llembas.android.BuildConfig +import okhttp3.Interceptor +import okhttp3.Response + +/** This app's name to a server, with [version]: `llembas-android/1.2.3`. */ +fun userAgent(version: String): String = "llembas-android/$version" + +/** + * Who is asking: the `User-Agent` of every request this app makes (calls, streams, uploads and + * downloads) and the device code's `client_id` -- one string, so a server's list of devices and + * its logs name the same program. + */ +val USER_AGENT: String = userAgent(BuildConfig.VERSION_NAME) + +/** + * The token a response says the instance no longer accepts, or null. Only the instance's own + * refusal counts: a 401 with its `WWW-Authenticate: Bearer realm="lembas"`, to a request that + * carried a token. A 401 passed on from somewhere else -- a speech provider behind `/v1` + * refusing the instance's key -- has no such header and signs nobody out; nor does a 403, which + * is the server's sentence about one thing that is not allowed. + */ +fun refusedToken(status: Int, challenge: String?, authorization: String?): String? { + if (status != 401 || challenge == null || authorization == null) return null + val asked = challenge.trim() + if (!asked.startsWith("Bearer", ignoreCase = true) || !asked.contains("realm=\"lembas\"", ignoreCase = true)) return null + if (!authorization.startsWith("Bearer ")) return null + return authorization.removePrefix("Bearer ").trim().ifEmpty { null } +} + +/** + * Where a refused token is said: once for the process, heard by whoever keeps the instances + * (`LembasApp`). It is told the token, not "the instance in use" -- a request of another + * instance, or one that was under way while the person switched, signs out the instance whose + * token it carried and no other. Called on the thread the answer arrived on: the listener only + * hands it on. + */ +object RefusedTokens { + @Volatile + var heard: ((String) -> Unit)? = null +} + +/** Names the app on every request, and listens for the instance refusing a token. */ +internal class Identity : Interceptor { + override fun intercept(chain: Interceptor.Chain): Response { + val request = chain.request().newBuilder().header("User-Agent", USER_AGENT).build() + val response = chain.proceed(request) + refusedToken(response.code, response.header("WWW-Authenticate"), request.header("Authorization"))?.let { token -> + RefusedTokens.heard?.invoke(token) + } + return response + } +} + +/** A `Retry-After` in seconds (the server sends a number), or null: absent, a date, or nonsense. */ +fun retryAfterSeconds(header: String?): Long? = header?.trim()?.toLongOrNull()?.takeIf { it >= 0 } + +/** + * The one reconnect schedule of every LLeMbas client: a pause of 1 second that doubles to 60, + * each within ±20 % so that the clients of a server that restarted do not all return at the same + * moment, and back to 1 second only after a connection that stayed healthy for 30 seconds -- a + * stream that opens, says one frame and breaks again is not a reason to ask every second. + * + * [jitter] gives a number in 0..1 (0.5 is no jitter). + */ +class Reconnect(private val jitter: () -> Double = { Math.random() }) { + private var step = FIRST_MS + + /** + * The pause before the next opening. [healthyMs] is how long the connection that just ended + * had been carrying frames (0 for one that never did); [retryAfterMs] is what the server asked + * for on a 429, honoured when it is the longer of the two (up to [MOST_ASKED_MS]). + */ + fun pause(healthyMs: Long, retryAfterMs: Long = 0): Long { + if (healthyMs >= HEALTHY_MS) step = FIRST_MS + val now = step + step = (step * 2).coerceAtMost(LAST_MS) + val jittered = (now * (0.8 + 0.4 * jitter().coerceIn(0.0, 1.0))).toLong() + return maxOf(jittered, retryAfterMs.coerceIn(0L, MOST_ASKED_MS)) + } + + companion object { + const val FIRST_MS = 1_000L + const val LAST_MS = 60_000L + const val HEALTHY_MS = 30_000L + + /** A server may ask for a long wait; a stream somebody watches is looked at again within five minutes. */ + const val MOST_ASKED_MS = 300_000L + } +} diff --git a/app/src/main/java/eu/llembas/android/api/StreamClient.kt b/app/src/main/java/eu/llembas/android/api/StreamClient.kt index 84638d2..9d59bff 100644 --- a/app/src/main/java/eu/llembas/android/api/StreamClient.kt +++ b/app/src/main/java/eu/llembas/android/api/StreamClient.kt @@ -17,32 +17,40 @@ data class Frame(val event: String, val data: String) /** * Follow a reply: the stream's frames, and when the connection drops before `close`, the same - * stream opened again after a pause -- 1, 2, 4, 8 … up to 30 seconds. Nothing is replayed or + * stream opened again after a pause -- the one schedule of [Reconnect]. Nothing is replayed or * deduplicated: the server's first pass after a reconnect is the whole state, which is exactly * what [LiveReply.apply] wants. * * A refusal (a 4xx: the chat was deleted, the token signed out) ends the flow with the error; - * only a broken connection is retried -- and each opening after the first is a new request, so - * it waits for its `turn` (the gate: nothing new is asked behind a lock). + * only a broken connection is retried, and a 429, which is "later" rather than "no" -- and each + * opening after the first is a new request, so it waits for its `turn` (the gate: nothing new is + * asked behind a lock). + * + * Silence is a broken connection too. Every stream this app follows (a reply's, the person's + * events, a chat's activity) is sent a keepalive by the server at least every 15 seconds, so a + * connection that says nothing for [SILENCE_SECONDS] is dead without having said so -- a phone + * that changed network, a proxy that dropped it -- and is opened again like any other. */ class StreamClient(private val api: ApiClient) { - private val http = api.http.newBuilder().readTimeout(0, TimeUnit.SECONDS).build() + private val http = api.http.newBuilder().readTimeout(SILENCE_SECONDS, TimeUnit.SECONDS).build() fun follow(chatId: String, messageId: String, turn: suspend () -> Unit = {}): Flow = reopened(turn) { once(api.streamRequest(chatId, messageId)) } /** * Follow an events route that ends itself now and then (`close` after a while, as the - * activity panel's does): opened again at once after a `close`, and after a pause that - * grows to 30 seconds when the connection drops or closes without a frame. It runs until + * activity panel's does): opened again at once after a `close`, and after a pause + * ([Reconnect]) when the connection drops or closes without a frame. It runs until * its collector stops; a refusal (4xx) ends it with the error. Each opening, the first * too, waits for its [turn]. */ fun watch(turn: suspend () -> Unit = {}, request: () -> Request): Flow = flow { - var wait = 1_000L + val schedule = Reconnect() while (true) { var closed = false var said = false var refused: ApiException? = null + var since: Long? = null + var slowed = 0L // Every opening is a request of its own: it waits for its turn (the gate). turn() once(request()).collect { result -> @@ -52,13 +60,15 @@ class StreamClient(private val api: ApiClient) { closed = true } else { said = true - wait = 1_000L + if (since == null) since = monotonicMs() emit(result.frame) } } is Outcome.Refused -> refused = result.error + is Outcome.Slowed -> slowed = result.seconds + is Outcome.Dropped -> Unit } } @@ -67,8 +77,7 @@ class StreamClient(private val api: ApiClient) { // that closes having said nothing waits as a dropped one does: a server that only // ever answers `close` must not be asked in a tight loop. if (reopenAtOnce(closed, said)) continue - delay(wait) - wait = (wait * 2).coerceAtMost(30_000L) + delay(schedule.pause(healthyMs = since?.let { monotonicMs() - it } ?: 0L, retryAfterMs = slowed * 1000L)) } } @@ -87,7 +96,10 @@ class StreamClient(private val api: ApiClient) { override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) { val code = response?.code ?: 0 - if (code in 400..499) { + if (code == 429) { + // "Later", not "no": opened again, after what the server asked for. + trySend(Outcome.Slowed(retryAfterSeconds(response?.header("Retry-After")) ?: 0L)) + } else if (code in 400..499) { trySend(Outcome.Refused(ApiException(code, response?.let { detail(it) } ?: "Refused ($code)."))) } else { trySend(Outcome.Dropped) @@ -98,43 +110,62 @@ class StreamClient(private val api: ApiClient) { ) awaitClose { source.cancel() } } + + companion object { + /** + * How long a stream may say nothing before it counts as broken. The server's keepalive + * comes every 15 seconds on each of the three routes followed here; three of them missed + * is not a slow server. + */ + const val SILENCE_SECONDS = 45L + } } -/** What one opening of a stream gave: a frame, a refusal (4xx), or a connection that broke. */ +/** A clock that only goes forward, in milliseconds: for how long a connection lasted. */ +fun monotonicMs(): Long = System.nanoTime() / 1_000_000L + +/** + * What one opening of a stream gave: a frame, a refusal (4xx), a "too many requests" (429, with + * the seconds its `Retry-After` asked for, 0 when it named none), or a connection that broke. + */ sealed interface Outcome { data class Event(val frame: Frame) : Outcome data class Refused(val error: ApiException) : Outcome + data class Slowed(val seconds: Long) : Outcome data object Dropped : Outcome } /** - * A reply's stream, [open]ed again whenever it ends before `close`: after a pause of 1, 2, 4, 8 … - * up to 30 seconds, and after its [turn] -- every opening but the first is a request nobody is - * waiting for at that moment, so it asks first whether it may start. A refusal ends the flow + * A reply's stream, [open]ed again whenever it ends before `close`: after a pause by [schedule] + * (1 second doubling to 60, jittered, and short again only after a connection that held for half + * a minute by [clock]), and after its [turn] -- every opening but the first is a request nobody + * is waiting for at that moment, so it asks first whether it may start. A refusal ends the flow * with the error. */ -fun reopened(turn: suspend () -> Unit, open: () -> Flow): Flow = flow { - var wait = 1_000L +fun reopened(turn: suspend () -> Unit, schedule: Reconnect = Reconnect(), clock: () -> Long = ::monotonicMs, open: () -> Flow): Flow = flow { while (true) { var closed = false var refused: ApiException? = null + var since: Long? = null + var slowed = 0L open().collect { result -> when (result) { is Outcome.Event -> { - wait = 1_000L + if (since == null) since = clock() emit(result.frame) if (result.frame.event == "close") closed = true } is Outcome.Refused -> refused = result.error + is Outcome.Slowed -> slowed = result.seconds + is Outcome.Dropped -> Unit } } refused?.let { throw it } if (closed) return@flow - delay(wait) - wait = (wait * 2).coerceAtMost(30_000L) + delay(schedule.pause(healthyMs = since?.let { clock() - it } ?: 0L, retryAfterMs = slowed * 1000L)) turn() } } diff --git a/app/src/main/java/eu/llembas/android/assist/AssistController.kt b/app/src/main/java/eu/llembas/android/assist/AssistController.kt index 415f3d2..482bd4e 100644 --- a/app/src/main/java/eu/llembas/android/assist/AssistController.kt +++ b/app/src/main/java/eu/llembas/android/assist/AssistController.kt @@ -243,7 +243,9 @@ class AssistController( val own = prefs.forInstance(instance?.id) _state.update { it.copy( - signedIn = instance != null, + // An instance that signed this phone out is "not signed in" here: the sheet says + // to sign in in the app, and asks that instance nothing. + signedIn = instance != null && !instance.signedOut, instanceName = instance?.name?.ifBlank { instance.base }.orEmpty(), voiceReply = prefs.readAloudSpoken, canReadNotifications = prefs.notificationSummaries && NotificationAccess.granted(context), @@ -260,7 +262,7 @@ class AssistController( private suspend fun loadRemote() { val store = context.lembas.instances val prefs = store.prefs.first() - val instance = store.default() ?: return + val instance = store.default()?.takeUnless { it.signedOut } ?: return targetId = instance.id val api = store.clientFor(instance) val own = prefs.forInstance(instance.id) @@ -622,7 +624,7 @@ class AssistController( _state.update { it.copy(conversation = talking) } try { val store = context.lembas.instances - val instance = store.default() ?: throw ApiException(401, "Not signed in.") + val instance = store.default()?.takeUnless { it.signedOut } ?: throw ApiException(401, context.getString(R.string.assist_signed_out)) targetId = instance.id val api = store.clientFor(instance) val prefs = store.prefs.first() diff --git a/app/src/main/java/eu/llembas/android/auth/Instances.kt b/app/src/main/java/eu/llembas/android/auth/Instances.kt index 9108aec..cab874c 100644 --- a/app/src/main/java/eu/llembas/android/auth/Instances.kt +++ b/app/src/main/java/eu/llembas/android/auth/Instances.kt @@ -21,9 +21,14 @@ import javax.crypto.KeyGenerator import javax.crypto.SecretKey import javax.crypto.spec.GCMParameterSpec -/** One instance this phone is signed in to. The token is stored encrypted, never in the clear. */ +/** + * One instance this phone is signed in to. The token is stored encrypted, never in the clear. + * [signedOut]: the instance refused that token (it was revoked there, or it expired). The entry + * stays -- with its place in the list and every choice kept for it -- until the person signs in + * again, which replaces the token, or removes it; meanwhile nothing more is asked with it. + */ @Serializable -data class Instance(val id: String, val base: String, val name: String, val email: String, val sealedToken: String) +data class Instance(val id: String, val base: String, val name: String, val email: String, val sealedToken: String, val signedOut: Boolean = false) /** * The token's lock: an AES key that lives in the Android Keystore and never leaves it. A copy @@ -96,6 +101,17 @@ object InstanceLogic { return Triple(next, added.id, keptDefault) } + /** + * The list after the instance refused a token: every entry whose token [refused] says it was is + * marked signed out, and nothing else changes -- not which instance is in use, not the default, + * not another instance. Null when no entry changes (the token is nobody's any more, or its + * entry is marked already), so that nothing is written. + */ + fun afterRefusal(instances: List, refused: (Instance) -> Boolean): List? { + if (instances.none { !it.signedOut && refused(it) }) return null + return instances.map { if (!it.signedOut && refused(it)) it.copy(signedOut = true) else it } + } + /** Removing [removedId] promotes the surviving default (or first) for active, and the * surviving active (or first) for default, or null when no instance remains. */ fun afterRemove(instances: List, removedId: String, currentActive: String?, currentDefault: String?): Triple, String?, String?> { @@ -216,9 +232,10 @@ class InstanceStore(private val context: Context) { suspend fun default(): Instance? = defaultInstance.first() - suspend fun client(): ApiClient? = current()?.let { clientFor(it) } + /** A client for the instance in use; none when there is no instance, or it signed this phone out. */ + suspend fun client(): ApiClient? = current()?.takeUnless { it.signedOut }?.let { clientFor(it) } - suspend fun defaultClient(): ApiClient? = default()?.let { clientFor(it) } + suspend fun defaultClient(): ApiClient? = default()?.takeUnless { it.signedOut }?.let { clientFor(it) } fun clientFor(instance: Instance): ApiClient = ApiClient(instance.base, TokenCipher.open(instance.sealedToken)) @@ -240,6 +257,20 @@ class InstanceStore(private val context: Context) { return instance } + /** + * The instance refused [token] (a 401 of its own): the entry that holds it is marked signed + * out. Asked by the token, never by "the one in use": the answer may be to a request of + * another instance, or to one sent before the person switched or signed in again -- a token + * that is no entry's any more marks nothing. + */ + suspend fun refused(token: String) { + context.store.edit { prefs -> + val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList() + val next = InstanceLogic.afterRefusal(all) { runCatching { TokenCipher.open(it.sealedToken) }.getOrNull() == token } + if (next != null) prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, next) + } + } + suspend fun use(id: String) { context.store.edit { it[ACTIVE] = id } } diff --git a/app/src/main/java/eu/llembas/android/ui/Errors.kt b/app/src/main/java/eu/llembas/android/ui/Errors.kt index ea5a8bf..e1b8aee 100644 --- a/app/src/main/java/eu/llembas/android/ui/Errors.kt +++ b/app/src/main/java/eu/llembas/android/ui/Errors.kt @@ -3,23 +3,94 @@ package eu.llembas.android.ui import android.content.Context import eu.llembas.android.R import eu.llembas.android.api.ApiException +import eu.llembas.android.api.NotLembas +import java.io.InterruptedIOException import java.net.ConnectException import java.net.NoRouteToHostException import java.net.SocketTimeoutException import java.net.UnknownHostException +import java.net.UnknownServiceException +import java.security.cert.CertPathValidatorException +import java.security.cert.CertificateException +import javax.net.ssl.SSLPeerUnverifiedException + +/** What went wrong between the phone and an instance, as the kinds a person can tell apart. */ +enum class Trouble { + /** The instance said no, or answered with an error: its own sentence, or its number. */ + ANSWERED, + + /** No way to it: no network, a name that does not resolve, a refused connection. */ + UNREACHABLE, + + /** It was reached and did not answer in time. */ + TIMEOUT, + + /** Its certificate is not one this phone trusts. */ + NOT_TRUSTED, + + /** The address is plain http, which this app does not speak. */ + NEEDS_HTTPS, + + /** Something answers there, and it is no LLeMbas instance. */ + NOT_LEMBAS, + + /** None of these: the failure's own message is all there is. */ + OTHER, +} + +/** Which [Trouble] a failure is. Pure, so the cases are a table in a test. */ +fun trouble(e: Throwable): Trouble = when { + e is ApiException -> Trouble.ANSWERED + + e is NotLembas -> Trouble.NOT_LEMBAS + + untrusted(e) -> Trouble.NOT_TRUSTED + + e is UnknownHostException || e is ConnectException || e is NoRouteToHostException -> Trouble.UNREACHABLE + + // OkHttp's own timeouts are an InterruptedIOException saying "timeout". + e is SocketTimeoutException || (e is InterruptedIOException && e.message == "timeout") -> Trouble.TIMEOUT + + // Android's network policy refusing cleartext: "CLEARTEXT communication to … not permitted". + e is UnknownServiceException && e.message.orEmpty().contains("CLEARTEXT", ignoreCase = true) -> Trouble.NEEDS_HTTPS + + else -> Trouble.OTHER +} /** - * A failure in words a person can act on. The server's refusal is its own sentence; a phone - * that cannot reach the instance at all -- no network, a name that does not resolve off the - * home network, a server that is down -- is one sentence saying so, rather than - * "Unable to resolve host" or "failed to connect to /…:443". A certificate the phone does not - * trust keeps its own message: that one names what to fix. + * A failure in words a person can act on, one sentence for each kind of [Trouble]. The server's + * refusal is its own sentence (a 403 says what is not allowed, and signs nobody out); an answer + * without one is said with its number -- "the server answered 502" is never "cannot be reached" + * and never "not a LLeMbas instance". A phone that cannot reach the instance at all, one that + * waited in vain, and a certificate the phone does not trust each say so, the last with what to + * do about it. */ -fun Context.explain(e: Throwable): String = when { - e is ApiException -> e.message?.ifBlank { null } ?: getString(R.string.offline) - unreachable(e) -> getString(R.string.offline) - else -> e.message?.ifBlank { null } ?: e.javaClass.simpleName +fun Context.explain(e: Throwable): String = when (trouble(e)) { + Trouble.ANSWERED -> e.message?.ifBlank { null } ?: getString(R.string.server_answered, ((e as? ApiException)?.status ?: 0).toString()) + Trouble.UNREACHABLE -> getString(R.string.offline) + Trouble.TIMEOUT -> getString(R.string.timed_out) + Trouble.NOT_TRUSTED -> getString(R.string.not_trusted) + Trouble.NEEDS_HTTPS -> getString(R.string.address_needs_https) + Trouble.NOT_LEMBAS -> getString(R.string.signin_not_lembas) + Trouble.OTHER -> e.message?.ifBlank { null } ?: e.javaClass.simpleName } /** Whether a failure means "the instance cannot be reached" rather than "it said no". */ fun unreachable(e: Throwable): Boolean = e is UnknownHostException || e is ConnectException || e is SocketTimeoutException || e is NoRouteToHostException + +/** + * Whether a failure is a certificate this phone does not trust: no authority the phone knows + * signed it, it is out of date, or the name on it is another host's. Looked for down the + * causes, where the platform puts it under the handshake's failure -- a handshake that failed + * for another reason (no protocol in common) is not this. + */ +fun untrusted(e: Throwable): Boolean { + var at: Throwable? = e + var depth = 0 + while (at != null && depth < 8) { + if (at is SSLPeerUnverifiedException || at is CertificateException || at is CertPathValidatorException) return true + at = at.cause + depth++ + } + return false +} diff --git a/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt b/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt index 77bbdaf..51e5c62 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt @@ -42,6 +42,7 @@ import eu.llembas.android.api.Whereabouts import eu.llembas.android.api.named import eu.llembas.android.api.serving import eu.llembas.android.api.whereabouts +import eu.llembas.android.auth.Instance import eu.llembas.android.lembas import eu.llembas.android.ui.explain import eu.llembas.android.ui.files.noSuchRoute @@ -370,8 +371,26 @@ class ChatViewModel(app: Application) : private var agentChat = false private var api: ApiClient? = null - private suspend fun api(): ApiClient = api ?: getApplication().lembas.instances.client()?.also { api = it } - ?: throw ApiException(401, "Not signed in.") + /** The instance this screen's chat is on, as it was when [api] was made: its id, and the token it was made with. */ + private var apiOf: Instance? = null + + /** + * The client for this screen's instance: the one in use when the screen first asked, and that + * one from then on. It is made again when the instance has another token (the person signed + * in again after the instance signed this phone out) -- the old one would be refused for + * ever -- and there is none while the instance is signed out, or once it was removed. + */ + private suspend fun api(): ApiClient { + val store = getApplication().lembas.instances + val mine = apiOf?.id + val now = (if (mine == null) store.current() else store.instances.first().firstOrNull { it.id == mine }) + ?.takeUnless { it.signedOut } ?: throw ApiException(401, getApplication().getString(R.string.assist_signed_out)) + api?.takeIf { apiOf?.sealedToken == now.sealedToken }?.let { return it } + return store.clientFor(now).also { + api = it + apiOf = now + } + } private fun fail(e: Throwable) { // A follow that was replaced by a newer one is cancelled, not failed: nothing to say. diff --git a/app/src/main/java/eu/llembas/android/ui/signin/SignInScreen.kt b/app/src/main/java/eu/llembas/android/ui/signin/SignInScreen.kt index 54fa521..36222a3 100644 --- a/app/src/main/java/eu/llembas/android/ui/signin/SignInScreen.kt +++ b/app/src/main/java/eu/llembas/android/ui/signin/SignInScreen.kt @@ -19,11 +19,13 @@ import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable @@ -47,17 +49,22 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.compose.viewModel import eu.llembas.android.R +import eu.llembas.android.api.Address +import eu.llembas.android.api.ApiException import eu.llembas.android.api.Doorstep import eu.llembas.android.api.ServerFit +import eu.llembas.android.api.address import eu.llembas.android.api.fit -import eu.llembas.android.api.normaliseBase +import eu.llembas.android.auth.Instance import eu.llembas.android.lembas import eu.llembas.android.ui.explain +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch +import java.io.IOException /** Where the sign-in is. The token arrives once, by device code, as `lembas login` gets it. */ sealed interface SignInState { @@ -68,25 +75,56 @@ sealed interface SignInState { data object Done : SignInState } -/** The sentence for a server this app will not work with, or null when it fits. */ +/** + * The sentence for a server this app will not work with, or null when it fits. Each reason has + * its own, and each says which side is the old one: another service is not "an older LLeMbas". + */ fun refusal(fit: ServerFit): Int? = when (fit) { ServerFit.FITS -> null - ServerFit.NOT_LEMBAS, ServerFit.TOO_OLD -> R.string.signin_too_old + ServerFit.NOT_LEMBAS -> R.string.signin_not_lembas + ServerFit.TOO_OLD -> R.string.signin_too_old ServerFit.TOO_NEW -> R.string.signin_too_new } +/** The sentence for an address that cannot be used as it was typed, or null for one that can (or for none yet). */ +fun refusal(read: Address): Int? = when (read) { + is Address.Base, Address.Empty -> null + Address.NeedsHttps -> R.string.address_needs_https + Address.NotHttp, Address.Unreadable -> R.string.address_unreadable +} + +/** + * The sentence a poll's `error` ends the sign-in with, or null while it goes on (still waiting, + * or asked to wait longer). Each end by its real reason: only an expired code is "expired". + */ +fun pollEnd(error: String?): Int? = when (error) { + "authorization_pending", "slow_down" -> null + "access_denied" -> R.string.signin_denied + "expired_token" -> R.string.signin_expired + else -> R.string.signin_failed +} + class SignInViewModel(app: Application) : AndroidViewModel(app) { private val _state = MutableStateFlow(SignInState.Address) val state = _state.asStateFlow() private var polling: Job? = null fun start(typed: String) { + // The address is read before anything is asked: what is wrong with it is said at this step. + val read = address(typed) + val base = (read as? Address.Base)?.url + if (base == null) { + refusal(read)?.let { said -> + polling?.cancel() + _state.value = SignInState.Failed(getApplication().getString(said)) + } + return + } polling?.cancel() polling = viewModelScope.launch { _state.value = SignInState.Finding val doorstep = Doorstep() try { - val base = normaliseBase(typed) val found = doorstep.discover(base) refusal(fit(found))?.let { said -> _state.value = SignInState.Failed(getApplication().getString(said)) @@ -97,9 +135,28 @@ class SignInViewModel(app: Application) : AndroidViewModel(app) { _state.value = SignInState.Code(code.userCode, code.verificationUriComplete.ifEmpty { code.verificationUri }) var interval = code.interval.coerceAtLeast(2) * 1000L val until = System.currentTimeMillis() + code.expiresIn * 1000L + // What last went wrong with a poll, if the code runs out with nothing better to say. + var trouble: Exception? = null while (System.currentTimeMillis() < until) { delay(interval) - val answer = doorstep.deviceToken(found.login.device.token, code.deviceCode) + val answer = try { + doorstep.deviceToken(found.login.device.token, code.deviceCode).also { trouble = null } + } catch (e: ApiException) { + // "Too many requests" is asked again, later; a server in trouble (5xx) may + // be back before the code runs out. Any other answer ends the sign-in. + if (e.status == 429) { + interval = maxOf(interval + 5000L, (e.retryAfter ?: 0L) * 1000L) + } else if (e.status < 500) { + throw e + } + trouble = e + continue + } catch (e: IOException) { + // The phone was away for a moment (the browser came to the front, the + // network changed): the approval may still come, so the next poll asks. + trouble = e + continue + } when { answer.accessToken != null -> { val account = answer.account @@ -115,20 +172,19 @@ class SignInViewModel(app: Application) : AndroidViewModel(app) { answer.error == "slow_down" -> interval += 5000L - answer.error == "authorization_pending" -> Unit - - answer.error == "access_denied" -> { - _state.value = SignInState.Failed(getApplication().getString(R.string.signin_denied)) - return@launch - } - - else -> { - _state.value = SignInState.Failed(getApplication().getString(R.string.signin_expired)) + else -> pollEnd(answer.error)?.let { said -> + _state.value = SignInState.Failed(getApplication().getString(said, answer.error.orEmpty())) return@launch } } } - _state.value = SignInState.Failed(getApplication().getString(R.string.signin_expired)) + val last = trouble + _state.value = SignInState.Failed( + if (last != null) getApplication().explain(last) else getApplication().getString(R.string.signin_expired), + ) + } catch (e: CancellationException) { + // Given up (Cancel, or a new start): not a failure, and nothing to say. + throw e } catch (e: Exception) { _state.value = SignInState.Failed(getApplication().explain(e)) } @@ -139,12 +195,18 @@ class SignInViewModel(app: Application) : AndroidViewModel(app) { polling?.cancel() _state.value = SignInState.Address } + + /** A sign-in that was finished the last time this page was up starts from the address again. */ + fun fresh() { + if (_state.value == SignInState.Done) _state.value = SignInState.Address + } } @Composable fun SignInScreen(onDone: () -> Unit = {}, onCancel: (() -> Unit)? = null, model: SignInViewModel = viewModel()) { val state by model.state.collectAsStateWithLifecycle() LaunchedEffect(state) { if (state == SignInState.Done) onDone() } + LaunchedEffect(Unit) { model.fresh() } var address by rememberSaveable { mutableStateOf("") } val context = LocalContext.current val knownBases by context.lembas.instances.instances.collectAsState(initial = emptyList()) @@ -200,14 +262,71 @@ fun SignInScreen(onDone: () -> Unit = {}, onCancel: (() -> Unit)? = null, model: SignInState.Finding, SignInState.Done -> CircularProgressIndicator() - is SignInState.Code -> { - Text(stringResource(R.string.signin_code_intro), modifier = Modifier.widthIn(max = 420.dp)) - Text(s.userCode, fontFamily = FontFamily.Monospace, fontSize = 32.sp, style = MaterialTheme.typography.headlineLarge) - Button(onClick = { CustomTabsIntent.Builder().build().launchUrl(context, Uri.parse(s.verify)) }) { - Text(stringResource(R.string.signin_open_browser)) + is SignInState.Code -> CodeStep(s, onCancel = { model.reset() }) + } + } +} + +/** The code to approve in the browser, and the way there. Laid out by the column it is put in. */ +@Composable +private fun CodeStep(code: SignInState.Code, onCancel: () -> Unit) { + val context = LocalContext.current + Text(stringResource(R.string.signin_code_intro), modifier = Modifier.widthIn(max = 420.dp)) + Text(code.userCode, fontFamily = FontFamily.Monospace, fontSize = 32.sp, style = MaterialTheme.typography.headlineLarge) + Button(onClick = { CustomTabsIntent.Builder().build().launchUrl(context, Uri.parse(code.verify)) }) { + Text(stringResource(R.string.signin_open_browser)) + } + CircularProgressIndicator() + OutlinedButton(onClick = onCancel) { Text(stringResource(R.string.cancel)) } +} + +/** + * The instance signed this phone out (it refused the token: revoked there, or expired). Shown + * over the instance's pages, which stay as they were underneath -- what was being written is + * still there after the sign-in. One step back in: the address is known, so "Sign in again" + * goes straight to the code. The other instances stay a tap away, and this one can be removed. + */ +@Composable +fun SignedOutScreen( + instance: Instance, + others: List, + onUse: (Instance) -> Unit, + onRemove: () -> Unit, + model: SignInViewModel = viewModel(key = "signed-out:" + instance.id), +) { + val state by model.state.collectAsStateWithLifecycle() + LaunchedEffect(Unit) { model.fresh() } + Surface(modifier = Modifier.fillMaxSize()) { + Column( + // It scrolls: several other instances, large type or a small screen must not push a button out of reach. + modifier = Modifier.fillMaxSize().safeDrawingPadding().verticalScroll(rememberScrollState()).padding(24.dp), + verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Text(stringResource(R.string.app_name), style = MaterialTheme.typography.headlineMedium) + Text( + stringResource(R.string.signed_out, instance.name.ifBlank { instance.base }), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.widthIn(max = 420.dp), + ) + when (val s = state) { + SignInState.Address, is SignInState.Failed -> { + if (s is SignInState.Failed) { + Text(s.message, color = MaterialTheme.colorScheme.error, modifier = Modifier.widthIn(max = 420.dp)) + } + Button(onClick = { model.start(instance.base) }) { Text(stringResource(R.string.signed_out_again)) } + others.forEach { other -> + OutlinedButton(onClick = { onUse(other) }) { + Text(stringResource(R.string.signed_out_use, other.name.ifBlank { other.base })) + } + } + TextButton(onClick = onRemove) { Text(stringResource(R.string.signed_out_remove)) } } - CircularProgressIndicator() - OutlinedButton(onClick = { model.reset() }) { Text(stringResource(R.string.cancel)) } + + SignInState.Finding, SignInState.Done -> CircularProgressIndicator() + + is SignInState.Code -> CodeStep(s, onCancel = { model.reset() }) } } } diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index f72b106..0412a3a 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -13,6 +13,17 @@ Kód vypršel, než byl schválen. Zkuste to znovu. Tato instance používá starší LLeMbas. Tato aplikace potřebuje LLeMbas 2.0 nebo novější. Tato instance používá novější rozhraní API pro aplikace než tato aplikace. Aktualizujte aplikaci. + Na této adrese není žádná instance LLeMbas. + Přihlášení se nepodařilo dokončit (%1$s). Zkuste to znovu. + Tato aplikace potřebuje adresu https://: prosté http není podporováno. + Tuto adresu aplikace nedokáže použít. Zadejte adresu instance, například llm.example.org. + Server odpověděl %1$s. + Instance neodpověděla včas. + Tento telefon nedůvěřuje certifikátu instance: nainstalujte certifikát její certifikační autority mezi uživatelské certifikáty Androidu (Nastavení, Zabezpečení, Šifrování a pověření, Instalovat certifikát). + %1$s tento telefon odhlásila. Přihlaste se znovu a pokračujte: vaše chaty i zdejší nastavení zůstávají. + Přihlásit se znovu + Použít %1$s + Odebrat tuto instanci Nová konverzace Zatím žádné konverzace. Ne všichni, kdo bloudí, jsou ztraceni — založte jednu. Nová konverzace s agentem diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index e8a01c1..2e51f53 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -13,6 +13,17 @@ Der Code ist abgelaufen, bevor er bestätigt wurde. Versuchen Sie es erneut. Auf dieser Instanz läuft ein älteres LLeMbas. Diese App braucht LLeMbas 2.0 oder neuer. Diese Instanz spricht eine neuere App-API als diese App. Aktualisieren Sie die App. + Unter dieser Adresse gibt es keine LLeMbas-Instanz. + Die Anmeldung konnte nicht abgeschlossen werden (%1$s). Versuchen Sie es erneut. + Diese App braucht eine https://-Adresse: einfaches http wird nicht unterstützt. + Diese Adresse kann die App nicht verwenden. Geben Sie die Adresse der Instanz ein, zum Beispiel llm.example.org. + Der Server hat mit %1$s geantwortet. + Die Instanz hat nicht rechtzeitig geantwortet. + Dieses Telefon vertraut dem Zertifikat der Instanz nicht: Installieren Sie das Zertifikat ihrer Zertifizierungsstelle unter den Nutzerzertifikaten von Android (Einstellungen, Sicherheit, Verschlüsselung & Anmeldedaten, Zertifikat installieren). + %1$s hat dieses Telefon abgemeldet. Melden Sie sich erneut an, um fortzufahren: Ihre Chats und Ihre Einstellungen hier bleiben erhalten. + Erneut anmelden + %1$s verwenden + Diese Instanz entfernen Neuer Chat Noch keine Chats. Nicht jeder, der wandert, ist verloren — fangen Sie einen an. Neuer Agent-Chat diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index dcc2831..55d833c 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -13,6 +13,17 @@ El código caducó antes de ser aprobado. Inténtelo de nuevo. Esta instancia usa una versión anterior de LLeMbas. Esta aplicación necesita LLeMbas 2.0 o posterior. Esta instancia habla una API de aplicaciones más reciente que esta aplicación. Actualice la aplicación. + No hay ninguna instancia de LLeMbas en esa dirección. + No se pudo completar el inicio de sesión (%1$s). Inténtelo de nuevo. + Esta aplicación necesita una dirección https://: no se admite http sin cifrar. + La aplicación no puede usar esa dirección. Escriba la dirección de la instancia, por ejemplo llm.example.org. + El servidor respondió %1$s. + La instancia no respondió a tiempo. + Este teléfono no confía en el certificado de la instancia: instale el certificado de su autoridad de certificación entre los certificados de usuario de Android (Ajustes, Seguridad, Cifrado y credenciales, Instalar un certificado). + %1$s cerró la sesión de este teléfono. Inicie sesión de nuevo para continuar: sus chats y lo que configuró aquí se conservan. + Iniciar sesión de nuevo + Usar %1$s + Quitar esta instancia Nuevo chat Aún no hay chats. No todos los que vagan están perdidos — empiece uno. Nuevo chat de agente diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index f7ddb86..bed22ab 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -13,6 +13,17 @@ Le code a expiré avant d\'être approuvé. Réessayez. Cette instance utilise une version plus ancienne de LLeMbas. Cette application nécessite LLeMbas 2.0 ou plus récent. Cette instance utilise une API d\'application plus récente que cette application. Mettez à jour l\'application. + Il n\'y a pas d\'instance LLeMbas à cette adresse. + La connexion n\'a pas pu aboutir (%1$s). Réessayez. + Cette application a besoin d\'une adresse https:// : le simple http n\'est pas pris en charge. + L\'application ne peut pas utiliser cette adresse. Saisissez l\'adresse de l\'instance, par exemple llm.example.org. + Le serveur a répondu %1$s. + L\'instance n\'a pas répondu à temps. + Ce téléphone ne fait pas confiance au certificat de l\'instance : installez le certificat de son autorité de certification parmi les certificats utilisateur d\'Android (Paramètres, Sécurité, Chiffrement et identifiants, Installer un certificat). + %1$s a déconnecté ce téléphone. Reconnectez-vous pour continuer : vos discussions et vos réglages ici sont conservés. + Se reconnecter + Utiliser %1$s + Retirer cette instance Nouvelle conversation Pas encore de conversation. Tous ceux qui errent ne sont pas perdus — commencez-en une. Nouvelle conversation d\'agent diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 119f865..b597e5a 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -13,6 +13,17 @@ A kód lejárt, mielőtt jóváhagyták volna. Próbálja újra. Ezen a példányon régebbi LLeMbas fut. Ehhez az alkalmazáshoz LLeMbas 2.0 vagy újabb kell. Ez a példány újabb alkalmazás-API-t használ, mint ez az alkalmazás. Frissítse az alkalmazást. + Ezen a címen nincs LLeMbas példány. + A bejelentkezést nem sikerült befejezni (%1$s). Próbálja újra. + Ehhez az alkalmazáshoz https:// cím kell: a sima http nem támogatott. + Ezt a címet az alkalmazás nem tudja használni. Írja be a példány címét, például llm.example.org. + A kiszolgáló válasza: %1$s. + A példány nem válaszolt időben. + Ez a telefon nem bízik a példány tanúsítványában: telepítse a hitelesítésszolgáltatója tanúsítványát az Android felhasználói tanúsítványai közé (Beállítások, Biztonság, Titkosítás és hitelesítési adatok, Tanúsítvány telepítése). + %1$s kijelentkeztette ezt a telefont. A folytatáshoz jelentkezzen be újra: a csevegései és az itteni beállításai megmaradnak. + Bejelentkezés újra + %1$s használata + Példány eltávolítása Új csevegés Még nincs csevegés. Nem mindenki van elveszve, aki bolyong — kezdjen el egyet. Új ügynök-csevegés diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 625ed6f..45c31b5 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -13,6 +13,17 @@ Il codice è scaduto prima di essere approvato. Riprova. Questa istanza usa una versione precedente di LLeMbas. Questa app richiede LLeMbas 2.0 o successivo. Questa istanza usa un\'API per l\'app più recente di questa app. Aggiorna l\'app. + Non c\'è nessuna istanza LLeMbas a quell\'indirizzo. + Non è stato possibile completare l\'accesso (%1$s). Riprova. + Questa app richiede un indirizzo https://: il semplice http non è supportato. + L\'app non può usare questo indirizzo. Scrivi l\'indirizzo dell\'istanza, ad esempio llm.example.org. + Il server ha risposto %1$s. + L\'istanza non ha risposto in tempo. + Questo telefono non considera attendibile il certificato dell\'istanza: installa il certificato della sua autorità di certificazione tra i certificati utente di Android (Impostazioni, Sicurezza, Crittografia e credenziali, Installa un certificato). + %1$s ha disconnesso questo telefono. Accedi di nuovo per continuare: le tue chat e le impostazioni fatte qui restano. + Accedi di nuovo + Usa %1$s + Rimuovi questa istanza Nuova chat Ancora nessuna chat. Non tutti quelli che vagano sono perduti — iniziane una. Nuova chat agente diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 7ff9e86..d61a8b3 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -13,6 +13,17 @@ Kod wygasł, zanim został zatwierdzony. Spróbuj ponownie. Ta instancja działa na starszym LLeMbas. Ta aplikacja wymaga LLeMbas 2.0 lub nowszego. Ta instancja używa nowszego API aplikacji niż ta aplikacja. Zaktualizuj aplikację. + Pod tym adresem nie ma instancji LLeMbas. + Nie udało się dokończyć logowania (%1$s). Spróbuj ponownie. + Ta aplikacja wymaga adresu https://: zwykłe http nie jest obsługiwane. + Aplikacja nie może użyć tego adresu. Wpisz adres instancji, na przykład llm.example.org. + Serwer odpowiedział: %1$s. + Instancja nie odpowiedziała na czas. + Ten telefon nie ufa certyfikatowi instancji: zainstaluj certyfikat jej urzędu certyfikacji wśród certyfikatów użytkownika Androida (Ustawienia, Bezpieczeństwo, Szyfrowanie i dane logowania, Zainstaluj certyfikat). + %1$s wylogowała ten telefon. Zaloguj się ponownie, aby kontynuować: Twoje czaty i tutejsze ustawienia zostają. + Zaloguj się ponownie + Użyj %1$s + Usuń tę instancję Nowy czat Nie ma jeszcze czatów. Nie każdy, kto błądzi, jest zgubiony — zacznij jeden. Nowy czat agenta diff --git a/app/src/main/res/values-sk/strings.xml b/app/src/main/res/values-sk/strings.xml index 760f2cd..d54f6e0 100644 --- a/app/src/main/res/values-sk/strings.xml +++ b/app/src/main/res/values-sk/strings.xml @@ -13,6 +13,17 @@ Kód vypršal skôr, než bol schválený. Skúste to znova. Táto inštancia beží na staršom LLeMbas. Táto aplikácia potrebuje LLeMbas 2.0 alebo novší. Táto inštancia používa novšie API pre aplikácie než táto aplikácia. Aktualizujte aplikáciu. + Na tejto adrese nie je žiadna inštancia LLeMbas. + Prihlásenie sa nepodarilo dokončiť (%1$s). Skúste to znova. + Táto aplikácia potrebuje adresu https://: obyčajné http nie je podporované. + Túto adresu aplikácia nevie použiť. Zadajte adresu inštancie, napríklad llm.example.org. + Server odpovedal %1$s. + Inštancia neodpovedala včas. + Tento telefón nedôveruje certifikátu inštancie: nainštalujte certifikát jej certifikačnej autority medzi používateľské certifikáty Androidu (Nastavenia, Zabezpečenie, Šifrovanie a poverenia, Inštalovať certifikát). + %1$s tento telefón odhlásila. Prihláste sa znova a pokračujte: vaše chaty aj tunajšie nastavenia zostávajú. + Prihlásiť sa znova + Použiť %1$s + Odstrániť túto inštanciu Nová konverzácia Zatiaľ žiadne konverzácie. Nie všetci, čo blúdia, sú stratení — začnite jednu. Nová konverzácia s agentom diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index cdf812d..af7186a 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -14,6 +14,17 @@ The code expired before it was approved. Try again. This instance runs an older LLeMbas. This app needs LLeMbas 2.0 or newer. This instance speaks a newer app API than this app. Update the app. + There is no LLeMbas instance at that address. + The sign-in could not be completed (%1$s). Try again. + This app needs an https:// address: plain http is not supported. + That is not an address this app can use. Type the instance\'s address, like llm.example.org. + The server answered %1$s. + The instance did not answer in time. + This phone does not trust the instance\'s certificate: install its CA certificate among Android\'s user certificates (Settings, Security, Encryption & credentials, Install a certificate). + %1$s signed this phone out. Sign in again to go on: your chats and what you set up here are kept. + Sign in again + Use %1$s + Remove this instance New chat No chats yet. Not all those who wander are lost — start one. New agent chat diff --git a/app/src/test/java/eu/llembas/android/ClientTest.kt b/app/src/test/java/eu/llembas/android/ClientTest.kt index 7ea7051..46a5ac2 100644 --- a/app/src/test/java/eu/llembas/android/ClientTest.kt +++ b/app/src/test/java/eu/llembas/android/ClientTest.kt @@ -5,7 +5,6 @@ import eu.llembas.android.api.ApiClient import eu.llembas.android.api.ApiException import eu.llembas.android.api.CardAnswer import eu.llembas.android.api.ShowCard -import eu.llembas.android.api.normaliseBase import eu.llembas.android.ui.unreachable import kotlinx.coroutines.test.runTest import okhttp3.mockwebserver.MockResponse @@ -33,12 +32,6 @@ class ClientTest { private fun client() = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test") - @Test - fun anAddressBecomesABase() { - assertEquals("https://llm.example.org", normaliseBase(" llm.example.org/ ")) - assertEquals("http://10.1.2.3:8080", normaliseBase("http://10.1.2.3:8080")) - } - @Test fun anAgentChatNamesItsDeviceAndFolder() = runTest { server.enqueue(MockResponse().setResponseCode(201).setBody("""{"chat":{"id":"c1","kind":"agent"}}""")) diff --git a/app/src/test/java/eu/llembas/android/ConnectionTest.kt b/app/src/test/java/eu/llembas/android/ConnectionTest.kt new file mode 100644 index 0000000..b74fc43 --- /dev/null +++ b/app/src/test/java/eu/llembas/android/ConnectionTest.kt @@ -0,0 +1,440 @@ +package eu.llembas.android + +import eu.llembas.android.api.Address +import eu.llembas.android.api.ApiClient +import eu.llembas.android.api.ApiException +import eu.llembas.android.api.Doorstep +import eu.llembas.android.api.Frame +import eu.llembas.android.api.LembasJson +import eu.llembas.android.api.NotLembas +import eu.llembas.android.api.Outcome +import eu.llembas.android.api.Reconnect +import eu.llembas.android.api.RefusedTokens +import eu.llembas.android.api.ServerFit +import eu.llembas.android.api.StreamClient +import eu.llembas.android.api.USER_AGENT +import eu.llembas.android.api.address +import eu.llembas.android.api.fit +import eu.llembas.android.api.refusedToken +import eu.llembas.android.api.reopened +import eu.llembas.android.api.retryAfterSeconds +import eu.llembas.android.api.userAgent +import eu.llembas.android.auth.Instance +import eu.llembas.android.auth.InstanceLogic +import eu.llembas.android.ui.Trouble +import eu.llembas.android.ui.signin.pollEnd +import eu.llembas.android.ui.signin.refusal +import eu.llembas.android.ui.trouble +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.test.currentTime +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.builtins.ListSerializer +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Before +import org.junit.Test +import java.io.IOException +import java.io.InterruptedIOException +import java.net.ConnectException +import java.net.SocketTimeoutException +import java.net.UnknownHostException +import java.net.UnknownServiceException +import java.security.cert.CertPathValidatorException +import java.util.concurrent.CopyOnWriteArrayList +import javax.net.ssl.SSLHandshakeException +import javax.net.ssl.SSLPeerUnverifiedException + +/** + * How this app connects to an instance, by the rules every LLeMbas client keeps: one way to read + * an address, one name on every request, one meaning of a refused token, one reconnect schedule, + * and a sentence of its own for each thing that can go wrong. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class ConnectionTest { + private lateinit var server: MockWebServer + private var heardBefore: ((String) -> Unit)? = null + + @Before + fun up() { + server = MockWebServer().apply { start() } + heardBefore = RefusedTokens.heard + } + + @After + fun down() { + RefusedTokens.heard = heardBefore + server.shutdown() + } + + private fun base() = server.url("/").toString().trimEnd('/') + + private fun client(token: String = "lmb_test") = ApiClient(base(), token) + + // --- The address --------------------------------------------------------------------------- + + @Test + fun anAddressIsReadByTheOneRule() { + val cases = listOf( + " Example.org " to Address.Base("https://example.org"), + "HTTPS://Example.org/" to Address.Base("https://example.org"), + "https://example.org/chat?x=1#y" to Address.Base("https://example.org"), + "example.org:8443/" to Address.Base("https://example.org:8443"), + "https://example.org:443" to Address.Base("https://example.org"), + "http://example.org" to Address.NeedsHttps, + "ftp://example.org" to Address.NotHttp, + "" to Address.Empty, + // The same rule, a little further: only blanks, an http address in capitals, no host, a port that is none. + " " to Address.Empty, + "HTTP://Example.org:8080/x" to Address.NeedsHttps, + "https://" to Address.Unreadable, + "example.org:port" to Address.Unreadable, + "llm.example.org/some/page/" to Address.Base("https://llm.example.org"), + ) + for ((typed, expected) in cases) assertEquals("\"$typed\"", expected, address(typed)) + } + + @Test + fun anAddressThatCannotBeUsedIsSaidAtTheAddressStep() { + assertEquals(R.string.address_needs_https, refusal(Address.NeedsHttps)) + assertEquals(R.string.address_unreadable, refusal(Address.NotHttp)) + assertEquals(R.string.address_unreadable, refusal(Address.Unreadable)) + assertNull(refusal(Address.Empty)) + assertNull(refusal(Address.Base("https://example.org"))) + } + + // --- Who asks ------------------------------------------------------------------------------ + + @Test + fun theAppNamesItselfWithItsVersion() { + assertEquals("llembas-android/1.2.3-beta.4", userAgent("1.2.3-beta.4")) + assertEquals(userAgent(BuildConfig.VERSION_NAME), USER_AGENT) + } + + @Test + fun everyRequestCarriesTheAppsName() = runTest { + server.enqueue(MockResponse().setBody("""{"api":2,"account":{"name":"Frodo","email":"f@shire.test"}}""")) + client().me() + assertEquals(USER_AGENT, server.takeRequest().getHeader("User-Agent")) + // The calls without a token too: finding the instance. + server.enqueue(MockResponse().setBody("""{"service":"lembas"}""")) + Doorstep().discover(base()) + assertEquals(USER_AGENT, server.takeRequest().getHeader("User-Agent")) + } + + @Test + fun theSignInNamesTheSameProgram() = runTest { + server.enqueue(MockResponse().setBody("""{"device_code":"d","user_code":"ABCD-EFGH"}""")) + Doorstep().deviceCode(server.url("/api/device/code").toString(), "LLeMbas for Android", "Maker Model") + val body = server.takeRequest().body.readUtf8() + assertTrue(body, body.contains("\"client_id\":\"$USER_AGENT\"")) + } + + // --- A refused token ------------------------------------------------------------------------- + + @Test + fun onlyTheInstancesOwnRefusalNamesAToken() { + val challenge = "Bearer realm=\"lembas\"" + assertEquals("lmb_a", refusedToken(401, challenge, "Bearer lmb_a")) + // Not allowed is not signed out; nor is "slow down", nor a server in trouble. + assertNull(refusedToken(403, challenge, "Bearer lmb_a")) + assertNull(refusedToken(429, challenge, "Bearer lmb_a")) + assertNull(refusedToken(500, challenge, "Bearer lmb_a")) + // A 401 passed on from elsewhere (a provider behind the instance) has no challenge of the instance's. + assertNull(refusedToken(401, null, "Bearer lmb_a")) + assertNull(refusedToken(401, "Basic realm=\"proxy\"", "Bearer lmb_a")) + assertNull(refusedToken(401, "Bearer realm=\"other\"", "Bearer lmb_a")) + // A request that carried no token signs nobody out. + assertNull(refusedToken(401, challenge, null)) + assertNull(refusedToken(401, challenge, "Bearer ")) + } + + @Test + fun aRefusedTokenIsHeardWithThatTokenOnAnyRequest() = runTest { + val heard = CopyOnWriteArrayList() + RefusedTokens.heard = { token -> heard += token } + val said = """{"detail":"That token is not valid, has expired or was revoked."}""" + server.enqueue(MockResponse().setResponseCode(401).setHeader("WWW-Authenticate", "Bearer realm=\"lembas\"").setBody(said)) + try { + client("lmb_revoked").me() + fail("a 401 must throw") + } catch (e: ApiException) { + assertEquals(401, e.status) + assertEquals("That token is not valid, has expired or was revoked.", e.message) + } + assertEquals(listOf("lmb_revoked"), heard.toList()) + // A 403 is the server's sentence and nothing more. + server.enqueue(MockResponse().setResponseCode(403).setBody("""{"detail":"This token was not given the app scope."}""")) + try { + client("lmb_narrow").me() + fail("a 403 must throw") + } catch (e: ApiException) { + assertEquals("This token was not given the app scope.", e.message) + } + // A 401 that is not the instance's own (no challenge) signs nobody out. + server.enqueue(MockResponse().setResponseCode(401).setBody("""{"error":{"message":"Incorrect API key provided."}}""")) + try { + client("lmb_fine").me() + fail("a 401 must throw") + } catch (e: ApiException) { + assertEquals(401, e.status) + } + assertEquals(listOf("lmb_revoked"), heard.toList()) + } + + @Test + fun aRefusalSignsOutThatInstanceAndTouchesNothingElse() { + val home = Instance(id = "alice@https://home.example", base = "https://home.example", name = "Home", email = "alice", sealedToken = "t1") + val work = Instance(id = "bob@https://work.example", base = "https://work.example", name = "Work", email = "bob", sealedToken = "t2") + val after = InstanceLogic.afterRefusal(listOf(home, work)) { it.sealedToken == "t2" } + assertEquals(listOf(home, work.copy(signedOut = true)), after) + // A token that is nobody's any more (signed in again meanwhile, or removed) changes nothing. + assertNull(InstanceLogic.afterRefusal(listOf(home, work)) { it.sealedToken == "gone" }) + // Said twice, written once. + assertNull(InstanceLogic.afterRefusal(after!!) { it.sealedToken == "t2" }) + // The signed-out one keeps its place as the one in use and as the default: nothing is promoted over it. + assertEquals(work.copy(signedOut = true), InstanceLogic.pickActive(after, work.id, work.id)) + // Signing in again replaces the entry under the same id, signed in, and the default stays whose it was. + val again = work.copy(sealedToken = "t9") + val (list, active, default) = InstanceLogic.afterAdd(after, again, home.id) + assertEquals(listOf(home, again), list) + assertFalse(list.last().signedOut) + assertEquals(work.id, active) + assertEquals(home.id, default) + } + + @Test + fun anInstanceStoredBeforeTheMarkIsSignedIn() { + val stored = """[{"id":"alice@https://home.example","base":"https://home.example","name":"Home","email":"alice","sealedToken":"t1"}]""" + val read = LembasJson.decodeFromString(ListSerializer(Instance.serializer()), stored) + assertFalse(read.single().signedOut) + val marked = LembasJson.encodeToString(ListSerializer(Instance.serializer()), listOf(read.single().copy(signedOut = true))) + assertTrue(LembasJson.decodeFromString(ListSerializer(Instance.serializer()), marked).single().signedOut) + } + + @Test + fun theEventsLineIsTheTokensNotOnlyTheInstances() { + assertEquals(eventsKey("alice@https://home.example", "sealed-a"), eventsKey("alice@https://home.example", "sealed-a")) + assertNotEquals(eventsKey("alice@https://home.example", "sealed-a"), eventsKey("alice@https://home.example", "sealed-b")) + assertNotEquals(eventsKey("alice@https://home.example", "sealed-a"), eventsKey("bob@https://home.example", "sealed-a")) + } + + // --- Streams --------------------------------------------------------------------------------- + + @Test + fun aSilentStreamCountsAsBrokenWithinAMinute() { + // The server's keepalive comes every 15 seconds: silence for three of them is a dead connection. + assertTrue(StreamClient.SILENCE_SECONDS in 45L..60L) + } + + @Test + fun thePauseDoublesFromOneSecondToSixty() { + val schedule = Reconnect { 0.5 } + val pauses = (1..9).map { schedule.pause(healthyMs = 0) } + assertEquals(listOf(1_000L, 2_000L, 4_000L, 8_000L, 16_000L, 32_000L, 60_000L, 60_000L, 60_000L), pauses) + } + + @Test + fun thePauseIsJitteredByAFifthEachWay() { + assertEquals(800L, Reconnect { 0.0 }.pause(healthyMs = 0)) + assertEquals(1_200L, Reconnect { 1.0 }.pause(healthyMs = 0)) + // A source that strays outside 0..1 does not stretch the pause further. + assertEquals(800L, Reconnect { -3.0 }.pause(healthyMs = 0)) + assertEquals(1_200L, Reconnect { 7.0 }.pause(healthyMs = 0)) + val drawn = Reconnect() + repeat(50) { + val pause = drawn.pause(healthyMs = Reconnect.HEALTHY_MS) + assertTrue("$pause", pause in 800L..1_200L) + } + } + + @Test + fun thePauseIsShortAgainOnlyAfterHalfAMinuteOfHealth() { + val schedule = Reconnect { 0.5 } + assertEquals(1_000L, schedule.pause(healthyMs = 0)) + assertEquals(2_000L, schedule.pause(healthyMs = 0)) + // It opened and said something, and broke again soon: the pause goes on growing. + assertEquals(4_000L, schedule.pause(healthyMs = 29_999)) + assertEquals(1_000L, schedule.pause(healthyMs = 30_000)) + assertEquals(2_000L, schedule.pause(healthyMs = 5)) + } + + @Test + fun aRetryAfterIsHonouredWhenItIsTheLongerWait() { + assertEquals(10_000L, Reconnect { 0.5 }.pause(healthyMs = 0, retryAfterMs = 10_000)) + // The schedule's own pause, when that is longer. + val grown = Reconnect { 0.5 } + repeat(5) { grown.pause(healthyMs = 0) } + assertEquals(32_000L, grown.pause(healthyMs = 0, retryAfterMs = 10_000)) + // An hour asked for is looked at again within five minutes. + assertEquals(Reconnect.MOST_ASKED_MS, Reconnect { 0.5 }.pause(healthyMs = 0, retryAfterMs = 3_600_000)) + assertEquals(30L, retryAfterSeconds("30")) + assertEquals(5L, retryAfterSeconds(" 5 ")) + assertNull(retryAfterSeconds(null)) + assertNull(retryAfterSeconds("-1")) + assertNull(retryAfterSeconds("Wed, 21 Oct 2015 07:28:00 GMT")) + } + + @Test + fun aStreamThatKeepsBreakingIsOpenedAgainEverMoreSlowly() = runTest { + var opened = 0 + val at = mutableListOf() + val frames = reopened(turn = {}, schedule = Reconnect { 0.5 }, clock = { 0L }) { + opened++ + at += currentTime + // One frame and gone, three times: by the clock no connection lasted at all. + if (opened <= 3) flow { emit(Outcome.Event(Frame("tail", "{}"))) } else flow { emit(Outcome.Event(Frame("close", "{}"))) } + }.toList() + assertEquals(listOf("tail", "tail", "tail", "close"), frames.map { it.event }) + assertEquals(listOf(0L, 1_000L, 3_000L, 7_000L), at) + } + + @Test + fun aStreamThatHeldIsOpenedAgainAfterOneSecond() = runTest { + var opened = 0 + var now = 0L + val at = mutableListOf() + reopened(turn = {}, schedule = Reconnect { 0.5 }, clock = { now }) { + opened++ + at += currentTime + when (opened) { + // Broke at once, twice: 1 second, then 2. + 1, 2 -> flow { emit(Outcome.Dropped) } + + // Then held for half a minute before it broke: 1 second again, not 4. + 3 -> flow { + emit(Outcome.Event(Frame("tail", "{}"))) + now += 30_000L + emit(Outcome.Dropped) + } + + // "Too many requests", come back in 7 seconds: that is the wait. + 4 -> flow { emit(Outcome.Slowed(7)) } + + else -> flow { emit(Outcome.Event(Frame("close", "{}"))) } + } + }.toList() + assertEquals(listOf(0L, 1_000L, 3_000L, 4_000L, 11_000L), at) + } + + // --- What went wrong, in its own words ----------------------------------------------------- + + @Test + fun eachKindOfTroubleIsToldApart() { + assertEquals(Trouble.UNREACHABLE, trouble(UnknownHostException("llm.example.org"))) + assertEquals(Trouble.UNREACHABLE, trouble(ConnectException("Connection refused"))) + assertEquals(Trouble.TIMEOUT, trouble(SocketTimeoutException("timeout"))) + assertEquals(Trouble.TIMEOUT, trouble(InterruptedIOException("timeout"))) + val untrusted = SSLHandshakeException("java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.") + untrusted.initCause(CertPathValidatorException("Trust anchor for certification path not found.")) + assertEquals(Trouble.NOT_TRUSTED, trouble(untrusted)) + assertEquals(Trouble.NOT_TRUSTED, trouble(SSLPeerUnverifiedException("Hostname llm.example.org not verified"))) + // A handshake that failed for another reason is not a matter of trust. + assertEquals(Trouble.OTHER, trouble(SSLHandshakeException("Handshake failed"))) + val cleartext = UnknownServiceException("CLEARTEXT communication to llm.example.org not permitted by network security policy") + assertEquals(Trouble.NEEDS_HTTPS, trouble(cleartext)) + assertEquals(Trouble.NOT_LEMBAS, trouble(NotLembas())) + // Whatever the server answered is the server's answer: never "unreachable", never "not LLeMbas". + assertEquals(Trouble.ANSWERED, trouble(ApiException(502, ""))) + assertEquals(Trouble.ANSWERED, trouble(ApiException(403, "This token was not given the app scope."))) + assertEquals(Trouble.OTHER, trouble(IOException("unexpected end of stream"))) + } + + @Test + fun anAddressWithoutTheDocumentIsNotLembasAndAServerInTroubleIsItsNumber() = runTest { + server.enqueue(MockResponse().setResponseCode(404).setBody("Not Found")) + try { + Doorstep().discover(base()) + fail("a 404 is not a LLeMbas instance") + } catch (e: NotLembas) { + // As it should be. + } + server.enqueue(MockResponse().setResponseCode(502).setBody("Bad Gateway")) + try { + Doorstep().discover(base()) + fail("a 502 must throw") + } catch (e: ApiException) { + assertEquals(502, e.status) + } + // A page where the document should be: something else answers there. + server.enqueue(MockResponse().setBody("Welcome")) + try { + Doorstep().discover(base()) + fail("a page is not a LLeMbas instance") + } catch (e: NotLembas) { + // As it should be. + } + // Another service's document is read, and refused by what it says. + server.enqueue(MockResponse().setBody("""{"service":"other"}""")) + assertEquals(ServerFit.NOT_LEMBAS, fit(Doorstep().discover(base()))) + } + + @Test + fun eachReasonAServerDoesNotFitHasItsOwnSentence() { + assertNull(refusal(ServerFit.FITS)) + assertEquals(R.string.signin_not_lembas, refusal(ServerFit.NOT_LEMBAS)) + // The direction is the sentence's whole point: an old server is not "update the app". + assertEquals(R.string.signin_too_old, refusal(ServerFit.TOO_OLD)) + assertEquals(R.string.signin_too_new, refusal(ServerFit.TOO_NEW)) + } + + @Test + fun aPollEndsByItsRealReason() { + assertNull(pollEnd("authorization_pending")) + assertNull(pollEnd("slow_down")) + assertEquals(R.string.signin_denied, pollEnd("access_denied")) + assertEquals(R.string.signin_expired, pollEnd("expired_token")) + // Anything else is not "the code expired". + assertEquals(R.string.signin_failed, pollEnd("invalid_grant")) + assertEquals(R.string.signin_failed, pollEnd(null)) + } + + @Test + fun aPollIsReadByWhatTheServerSaid() = runTest { + val url = server.url("/api/device/token").toString() + server.enqueue(MockResponse().setResponseCode(400).setBody("""{"error":"authorization_pending"}""")) + assertEquals("authorization_pending", Doorstep().deviceToken(url, "d").error) + server.enqueue(MockResponse().setBody("""{"access_token":"lmb_new","account":{"email":"frodo@example.org"}}""")) + assertEquals("lmb_new", Doorstep().deviceToken(url, "d").accessToken) + // A proxy's page while the server restarts: the server's number, to be asked again. + server.enqueue(MockResponse().setResponseCode(502).setBody("Bad Gateway")) + try { + Doorstep().deviceToken(url, "d") + fail("a 502 must throw") + } catch (e: ApiException) { + assertEquals(502, e.status) + assertNull(e.retryAfter) + } + // "Too many requests" carries how long to wait. + server.enqueue(MockResponse().setResponseCode(429).setHeader("Retry-After", "7").setBody("""{"detail":"Slow down."}""")) + try { + Doorstep().deviceToken(url, "d") + fail("a 429 must throw") + } catch (e: ApiException) { + assertEquals(429, e.status) + assertEquals(7L, e.retryAfter) + assertEquals("Slow down.", e.message) + } + } + + @Test + fun tooManySignInsIsTheServersOwnSentence() = runTest { + val said = """{"error":"slow_down","error_description":"Too many device logins from this address."}""" + server.enqueue(MockResponse().setResponseCode(429).setBody(said)) + try { + Doorstep().deviceCode(server.url("/api/device/code").toString(), "LLeMbas for Android", "Maker Model") + fail("a 429 must throw") + } catch (e: ApiException) { + assertEquals(429, e.status) + assertEquals("Too many device logins from this address.", e.message) + } + } +} diff --git a/scripts/strings.py b/scripts/strings.py index 5ac713e..307ad24 100755 --- a/scripts/strings.py +++ b/scripts/strings.py @@ -25,6 +25,19 @@ STRINGS: dict[str, str] = { "signin_expired": "The code expired before it was approved. Try again.", "signin_too_old": "This instance runs an older LLeMbas. This app needs LLeMbas 2.0 or newer.", "signin_too_new": "This instance speaks a newer app API than this app. Update the app.", + # What went wrong on the way to an instance, one sentence for each kind, and the way back in + # when an instance signed this phone out. + "signin_not_lembas": "There is no LLeMbas instance at that address.", + "signin_failed": "The sign-in could not be completed (%1$s). Try again.", + "address_needs_https": "This app needs an https:// address: plain http is not supported.", + "address_unreadable": "That is not an address this app can use. Type the instance's address, like llm.example.org.", + "server_answered": "The server answered %1$s.", + "timed_out": "The instance did not answer in time.", + "not_trusted": "This phone does not trust the instance's certificate: install its CA certificate among Android's user certificates (Settings, Security, Encryption & credentials, Install a certificate).", + "signed_out": "%1$s signed this phone out. Sign in again to go on: your chats and what you set up here are kept.", + "signed_out_again": "Sign in again", + "signed_out_use": "Use %1$s", + "signed_out_remove": "Remove this instance", # Chats "new_chat": "New chat", "empty_chats": "No chats yet. Not all those who wander are lost — start one.", diff --git a/scripts/strings_own.json b/scripts/strings_own.json index f5a3783..25be83c 100644 --- a/scripts/strings_own.json +++ b/scripts/strings_own.json @@ -434,7 +434,18 @@ "diff_show_less": "Zobrazit méně", "diff_more": "Další řádky, které se zde nezobrazují: %1$s.", "diff_endings": "Konce řádků se mění z %1$s na %2$s.", - "diff_cut": "Tato změna je příliš dlouhá na to, aby se zde porovnala. Zobrazen je jen její začátek." + "diff_cut": "Tato změna je příliš dlouhá na to, aby se zde porovnala. Zobrazen je jen její začátek.", + "signin_not_lembas": "Na této adrese není žádná instance LLeMbas.", + "signin_failed": "Přihlášení se nepodařilo dokončit (%1$s). Zkuste to znovu.", + "address_needs_https": "Tato aplikace potřebuje adresu https://: prosté http není podporováno.", + "address_unreadable": "Tuto adresu aplikace nedokáže použít. Zadejte adresu instance, například llm.example.org.", + "server_answered": "Server odpověděl %1$s.", + "timed_out": "Instance neodpověděla včas.", + "not_trusted": "Tento telefon nedůvěřuje certifikátu instance: nainstalujte certifikát její certifikační autority mezi uživatelské certifikáty Androidu (Nastavení, Zabezpečení, Šifrování a pověření, Instalovat certifikát).", + "signed_out": "%1$s tento telefon odhlásila. Přihlaste se znovu a pokračujte: vaše chaty i zdejší nastavení zůstávají.", + "signed_out_again": "Přihlásit se znovu", + "signed_out_use": "Použít %1$s", + "signed_out_remove": "Odebrat tuto instanci" }, "de": { "about_version": "LLeMbas für Android %1$s", @@ -872,7 +883,18 @@ "diff_show_less": "Weniger anzeigen", "diff_more": "%1$s weitere Zeilen werden hier nicht angezeigt.", "diff_endings": "Die Zeilenenden ändern sich von %1$s zu %2$s.", - "diff_cut": "Diese Änderung ist zu lang, um hier verglichen zu werden. Nur ihr Anfang wird angezeigt." + "diff_cut": "Diese Änderung ist zu lang, um hier verglichen zu werden. Nur ihr Anfang wird angezeigt.", + "signin_not_lembas": "Unter dieser Adresse gibt es keine LLeMbas-Instanz.", + "signin_failed": "Die Anmeldung konnte nicht abgeschlossen werden (%1$s). Versuchen Sie es erneut.", + "address_needs_https": "Diese App braucht eine https://-Adresse: einfaches http wird nicht unterstützt.", + "address_unreadable": "Diese Adresse kann die App nicht verwenden. Geben Sie die Adresse der Instanz ein, zum Beispiel llm.example.org.", + "server_answered": "Der Server hat mit %1$s geantwortet.", + "timed_out": "Die Instanz hat nicht rechtzeitig geantwortet.", + "not_trusted": "Dieses Telefon vertraut dem Zertifikat der Instanz nicht: Installieren Sie das Zertifikat ihrer Zertifizierungsstelle unter den Nutzerzertifikaten von Android (Einstellungen, Sicherheit, Verschlüsselung & Anmeldedaten, Zertifikat installieren).", + "signed_out": "%1$s hat dieses Telefon abgemeldet. Melden Sie sich erneut an, um fortzufahren: Ihre Chats und Ihre Einstellungen hier bleiben erhalten.", + "signed_out_again": "Erneut anmelden", + "signed_out_use": "%1$s verwenden", + "signed_out_remove": "Diese Instanz entfernen" }, "es": { "about_version": "LLeMbas para Android %1$s", @@ -1309,7 +1331,18 @@ "diff_show_less": "Mostrar menos", "diff_more": "Aquí no se muestran %1$s líneas más.", "diff_endings": "Los finales de línea cambian de %1$s a %2$s.", - "diff_cut": "Este cambio es demasiado largo para compararlo aquí. Solo se muestra su comienzo." + "diff_cut": "Este cambio es demasiado largo para compararlo aquí. Solo se muestra su comienzo.", + "signin_not_lembas": "No hay ninguna instancia de LLeMbas en esa dirección.", + "signin_failed": "No se pudo completar el inicio de sesión (%1$s). Inténtelo de nuevo.", + "address_needs_https": "Esta aplicación necesita una dirección https://: no se admite http sin cifrar.", + "address_unreadable": "La aplicación no puede usar esa dirección. Escriba la dirección de la instancia, por ejemplo llm.example.org.", + "server_answered": "El servidor respondió %1$s.", + "timed_out": "La instancia no respondió a tiempo.", + "not_trusted": "Este teléfono no confía en el certificado de la instancia: instale el certificado de su autoridad de certificación entre los certificados de usuario de Android (Ajustes, Seguridad, Cifrado y credenciales, Instalar un certificado).", + "signed_out": "%1$s cerró la sesión de este teléfono. Inicie sesión de nuevo para continuar: sus chats y lo que configuró aquí se conservan.", + "signed_out_again": "Iniciar sesión de nuevo", + "signed_out_use": "Usar %1$s", + "signed_out_remove": "Quitar esta instancia" }, "fr": { "about_version": "LLeMbas pour Android %1$s", @@ -1747,7 +1780,18 @@ "diff_show_less": "Afficher moins", "diff_more": "%1$s lignes de plus ne sont pas affichées ici.", "diff_endings": "Les fins de ligne passent de %1$s à %2$s.", - "diff_cut": "Cette modification est trop longue pour être comparée ici. Seul son début est affiché." + "diff_cut": "Cette modification est trop longue pour être comparée ici. Seul son début est affiché.", + "signin_not_lembas": "Il n'y a pas d'instance LLeMbas à cette adresse.", + "signin_failed": "La connexion n'a pas pu aboutir (%1$s). Réessayez.", + "address_needs_https": "Cette application a besoin d'une adresse https:// : le simple http n'est pas pris en charge.", + "address_unreadable": "L'application ne peut pas utiliser cette adresse. Saisissez l'adresse de l'instance, par exemple llm.example.org.", + "server_answered": "Le serveur a répondu %1$s.", + "timed_out": "L'instance n'a pas répondu à temps.", + "not_trusted": "Ce téléphone ne fait pas confiance au certificat de l'instance : installez le certificat de son autorité de certification parmi les certificats utilisateur d'Android (Paramètres, Sécurité, Chiffrement et identifiants, Installer un certificat).", + "signed_out": "%1$s a déconnecté ce téléphone. Reconnectez-vous pour continuer : vos discussions et vos réglages ici sont conservés.", + "signed_out_again": "Se reconnecter", + "signed_out_use": "Utiliser %1$s", + "signed_out_remove": "Retirer cette instance" }, "hu": { "about_version": "LLeMbas Androidra %1$s", @@ -2185,7 +2229,18 @@ "diff_show_less": "Kevesebb megjelenítése", "diff_more": "További %1$s sor itt nem látható.", "diff_endings": "A sorvégek megváltoznak: %1$s helyett %2$s.", - "diff_cut": "Ez a változás túl hosszú ahhoz, hogy itt össze lehessen hasonlítani. Csak az eleje látható." + "diff_cut": "Ez a változás túl hosszú ahhoz, hogy itt össze lehessen hasonlítani. Csak az eleje látható.", + "signin_not_lembas": "Ezen a címen nincs LLeMbas példány.", + "signin_failed": "A bejelentkezést nem sikerült befejezni (%1$s). Próbálja újra.", + "address_needs_https": "Ehhez az alkalmazáshoz https:// cím kell: a sima http nem támogatott.", + "address_unreadable": "Ezt a címet az alkalmazás nem tudja használni. Írja be a példány címét, például llm.example.org.", + "server_answered": "A kiszolgáló válasza: %1$s.", + "timed_out": "A példány nem válaszolt időben.", + "not_trusted": "Ez a telefon nem bízik a példány tanúsítványában: telepítse a hitelesítésszolgáltatója tanúsítványát az Android felhasználói tanúsítványai közé (Beállítások, Biztonság, Titkosítás és hitelesítési adatok, Tanúsítvány telepítése).", + "signed_out": "%1$s kijelentkeztette ezt a telefont. A folytatáshoz jelentkezzen be újra: a csevegései és az itteni beállításai megmaradnak.", + "signed_out_again": "Bejelentkezés újra", + "signed_out_use": "%1$s használata", + "signed_out_remove": "Példány eltávolítása" }, "it": { "about_version": "LLeMbas per Android %1$s", @@ -2622,7 +2677,18 @@ "diff_show_less": "Mostra meno", "diff_more": "Altre %1$s righe non sono mostrate qui.", "diff_endings": "I fine riga cambiano da %1$s a %2$s.", - "diff_cut": "Questa modifica è troppo lunga per essere confrontata qui. Ne è mostrato solo l’inizio." + "diff_cut": "Questa modifica è troppo lunga per essere confrontata qui. Ne è mostrato solo l’inizio.", + "signin_not_lembas": "Non c'è nessuna istanza LLeMbas a quell'indirizzo.", + "signin_failed": "Non è stato possibile completare l'accesso (%1$s). Riprova.", + "address_needs_https": "Questa app richiede un indirizzo https://: il semplice http non è supportato.", + "address_unreadable": "L'app non può usare questo indirizzo. Scrivi l'indirizzo dell'istanza, ad esempio llm.example.org.", + "server_answered": "Il server ha risposto %1$s.", + "timed_out": "L'istanza non ha risposto in tempo.", + "not_trusted": "Questo telefono non considera attendibile il certificato dell'istanza: installa il certificato della sua autorità di certificazione tra i certificati utente di Android (Impostazioni, Sicurezza, Crittografia e credenziali, Installa un certificato).", + "signed_out": "%1$s ha disconnesso questo telefono. Accedi di nuovo per continuare: le tue chat e le impostazioni fatte qui restano.", + "signed_out_again": "Accedi di nuovo", + "signed_out_use": "Usa %1$s", + "signed_out_remove": "Rimuovi questa istanza" }, "pl": { "about_version": "LLeMbas na Androida %1$s", @@ -3059,7 +3125,18 @@ "diff_show_less": "Pokaż mniej", "diff_more": "Dalsze wiersze, których tu nie pokazano: %1$s.", "diff_endings": "Końce wierszy zmieniają się z %1$s na %2$s.", - "diff_cut": "Ta zmiana jest zbyt długa, by ją tu porównać. Pokazano tylko jej początek." + "diff_cut": "Ta zmiana jest zbyt długa, by ją tu porównać. Pokazano tylko jej początek.", + "signin_not_lembas": "Pod tym adresem nie ma instancji LLeMbas.", + "signin_failed": "Nie udało się dokończyć logowania (%1$s). Spróbuj ponownie.", + "address_needs_https": "Ta aplikacja wymaga adresu https://: zwykłe http nie jest obsługiwane.", + "address_unreadable": "Aplikacja nie może użyć tego adresu. Wpisz adres instancji, na przykład llm.example.org.", + "server_answered": "Serwer odpowiedział: %1$s.", + "timed_out": "Instancja nie odpowiedziała na czas.", + "not_trusted": "Ten telefon nie ufa certyfikatowi instancji: zainstaluj certyfikat jej urzędu certyfikacji wśród certyfikatów użytkownika Androida (Ustawienia, Bezpieczeństwo, Szyfrowanie i dane logowania, Zainstaluj certyfikat).", + "signed_out": "%1$s wylogowała ten telefon. Zaloguj się ponownie, aby kontynuować: Twoje czaty i tutejsze ustawienia zostają.", + "signed_out_again": "Zaloguj się ponownie", + "signed_out_use": "Użyj %1$s", + "signed_out_remove": "Usuń tę instancję" }, "sk": { "about_version": "LLeMbas pre Android %1$s", @@ -3496,6 +3573,17 @@ "diff_show_less": "Zobraziť menej", "diff_more": "Ďalšie riadky, ktoré sa tu nezobrazujú: %1$s.", "diff_endings": "Konce riadkov sa menia z %1$s na %2$s.", - "diff_cut": "Táto zmena je príliš dlhá na to, aby sa tu porovnala. Zobrazený je len jej začiatok." + "diff_cut": "Táto zmena je príliš dlhá na to, aby sa tu porovnala. Zobrazený je len jej začiatok.", + "signin_not_lembas": "Na tejto adrese nie je žiadna inštancia LLeMbas.", + "signin_failed": "Prihlásenie sa nepodarilo dokončiť (%1$s). Skúste to znova.", + "address_needs_https": "Táto aplikácia potrebuje adresu https://: obyčajné http nie je podporované.", + "address_unreadable": "Túto adresu aplikácia nevie použiť. Zadajte adresu inštancie, napríklad llm.example.org.", + "server_answered": "Server odpovedal %1$s.", + "timed_out": "Inštancia neodpovedala včas.", + "not_trusted": "Tento telefón nedôveruje certifikátu inštancie: nainštalujte certifikát jej certifikačnej autority medzi používateľské certifikáty Androidu (Nastavenia, Zabezpečenie, Šifrovanie a poverenia, Inštalovať certifikát).", + "signed_out": "%1$s tento telefón odhlásila. Prihláste sa znova a pokračujte: vaše chaty aj tunajšie nastavenia zostávajú.", + "signed_out_again": "Prihlásiť sa znova", + "signed_out_use": "Použiť %1$s", + "signed_out_remove": "Odstrániť túto inštanciu" } }