Compare commits

...
Author SHA1 Message Date
HomerandClaude Fable 5.2 1e32868d36 CI: run again (the run on the commit before this ended in the build step with nothing changed but the changelog)
CI / check (push) Canceled after 0s
Release / release (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 22:00:00 +00:00
HomerandClaude Fable 5.2 da2c5891ed Changelog: the 1.0.0-beta.17 heading in the file's own form
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 21:48:50 +00:00
HomerandClaude Fable 5.2 f8d122d409 1.0.0-beta.17: connecting as the other LLeMbas clients do
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 21:48:43 +00:00
HomerandClaude Fable 5.2 827f57839f Keep the typed address, know an instance signed in to before, heed min_clients
CI / check (push) Canceled after 0s
- A new sign-in stores the normalised typed address; the instance's own base_url is not stored
  and is looked at only to recognise an instance already on the phone (same account, stored
  base equal to the typed address or to what the instance says): that entry is refreshed under
  its id, no twin is added. Existing entries are not migrated: ids are opaque keys.
- The device-code endpoints of the discovery document are used only on the typed address's
  origin; otherwise the sign-in says so.
- min_clients.android in the discovery document, above this app's version (by numbers,
  beta-aware, a build's suffix left off), is "update the app" with both versions, at sign-in
  and at the drawer's check. Any other shape of the field is read as nothing said.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 19:26:14 +00:00
HomerandClaude Fable 5.2 71b2e847cf Connect as the other LLeMbas clients do: address, identity, refused token, streams, words
- 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/<version> 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 <noreply@anthropic.com>
2026-12-01 19:22:40 +00:00
HomerandClaude Opus 5.5 cf092ef1a1 hygiene: let the output decide, not xargs' exit status
CI / check (push) Canceled after 0s
`if … | xargs -0 grep` read a match as clean whenever any one batch of
files had none (xargs answers 123) or grep met an error (2). Today every
file fits one batch, so nothing slipped through; it would once the
repository grows. Same form as the server's and the CLI's check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01H1bF3XAshtCGhF7TeLGcDk
2026-11-28 00:06:29 +00:00
30 changed files with 1595 additions and 115 deletions

No files matched your search

+50
View File
@@ -3,6 +3,56 @@
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
## [1.0.0-beta.17] — 2026-12-01
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.
- **The address you typed is the one kept.** A new sign-in stores the address as it was typed
(read by the rule above), not the one the instance says of itself, and the sign-in itself goes
only to that address: an instance whose proxy makes it name another host says so in words.
Instances already on the phone are untouched -- same entry, same token, same settings, same
notifications -- and signing in again to one of them, by either address, refreshes that entry
rather than adding a second one.
- **An instance can say the app is too old.** Where an instance names the oldest version of
the app it works with (`min_clients` in its discovery document) and this one is older, the app
says so with both versions and does not go on.
- **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/<version>`, 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
+1 -1
View File
@@ -31,7 +31,7 @@ android {
// The one source of the version. versionCode is derived from it, so the two cannot
// drift, and a beta sorts below its release: 1.0.0-beta.1 -> 1000001,
// 1.0.0-beta.2 -> 1000002, 1.0.0 -> 1000099, 1.2.3 -> 1020399.
versionName = "1.0.0-beta.16"
versionName = "1.0.0-beta.17"
versionCode = versionName!!.split("-beta.").let { parts ->
val (a, b, c) = parts[0].split(".").map { it.toInt() }
val pre = if (parts.size == 2) parts[1].toInt() else 99
@@ -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<Frame>? {
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()
@@ -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)
}
},
)
}
}
}
@@ -0,0 +1,71 @@
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
}
}
/**
* Whether two stored or said bases name one instance: compared as [address] reads them, so that
* a capital, a trailing slash or the scheme's own port makes no difference. One that the rule
* does not read (an `http://` base a server once said of itself) is compared as it stands.
*/
fun sameBase(one: String, other: String): Boolean = canonical(one) == canonical(other)
private fun canonical(base: String): String = (address(base) as? Address.Base)?.url ?: base.trim().trimEnd('/').lowercase()
/**
* Whether [url] is on the origin of [base]: the same scheme, host and port. An endpoint a
* discovery document names is used only then -- the token and the sign-in go to the address the
* person typed and to no other host, whatever the document says.
*/
fun onOrigin(base: String, url: String): Boolean {
val home = base.toHttpUrlOrNull() ?: return false
val there = url.toHttpUrlOrNull() ?: return false
return home.scheme == there.scheme && home.host == there.host && home.port == there.port
}
@@ -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()
/**
@@ -1,5 +1,8 @@
package eu.llembas.android.api
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
/**
* The app API this app reads: 2, the server's 2.0 (no canvas, no `knowledge_bases`, the `show`
* card and its route, and the person's files). A server with a newer one is told about, not
@@ -29,3 +32,38 @@ fun fit(found: Discovery): ServerFit {
else -> ServerFit.FITS
}
}
/** This app's name among the products a discovery document's `min_clients` lists. */
const val PRODUCT = "android"
/** The oldest version of [product] the instance says it works with, or null: nothing said, or not in words this app reads. */
fun Discovery.minClient(product: String = PRODUCT): String? {
val said = (minClients as? JsonObject)?.get(product) as? JsonPrimitive ?: return null
return said.takeIf { it.isString }?.content?.trim()?.ifEmpty { null }
}
private val VERSION = Regex("""^v?(\d+)\.(\d+)\.(\d+)(?:-beta\.(\d+))?""")
/**
* A version as numbers that compare: `1.2.3` or `1.2.3-beta.4`, a release above every beta of
* itself. Whatever follows is a build's own mark (`-debug.12`, a flavour) and is left off. Null
* for what is no such version.
*/
fun versionNumbers(text: String): List<Int>? {
val match = VERSION.find(text.trim()) ?: return null
val (major, minor, patch, beta) = match.destructured
val parts = listOf(major.toIntOrNull(), minor.toIntOrNull(), patch.toIntOrNull(), if (beta.isEmpty()) Int.MAX_VALUE else beta.toIntOrNull())
return if (parts.any { it == null }) null else parts.filterNotNull()
}
/**
* Whether the version [mine] is older than [needed]. By numbers, never as text: `1.0.0-beta.10`
* is newer than `1.0.0-beta.9`, and `1.0.0` newer than both. False when either cannot be read:
* a document that says nonsense locks nobody out.
*/
fun olderThan(mine: String, needed: String): Boolean {
val own = versionNumbers(mine) ?: return false
val least = versionNumbers(needed) ?: return false
for (i in own.indices) if (own[i] != least[i]) return own[i] < least[i]
return false
}
@@ -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
}
}
@@ -33,6 +33,12 @@ data class Discovery(
@SerialName("app_api") val appApi: Int = 0,
val login: Login = Login(),
val scopes: List<String> = emptyList(),
/**
* The oldest version of each client the instance works with, by product (`{"android": "1.0.0"}`).
* Kept as whatever the document says -- read through [minClient], so that a shape this app
* does not expect is "says nothing", never "not a LLeMbas instance".
*/
@SerialName("min_clients") val minClients: JsonElement? = null,
) {
@Serializable
data class Login(val device: DeviceLogin = DeviceLogin())
@@ -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<Frame> = 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<Frame> = 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<Outcome>): Flow<Frame> = flow {
var wait = 1_000L
fun reopened(turn: suspend () -> Unit, schedule: Reconnect = Reconnect(), clock: () -> Long = ::monotonicMs, open: () -> Flow<Outcome>): Flow<Frame> = 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()
}
}
@@ -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()
@@ -9,6 +9,7 @@ import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import eu.llembas.android.api.ApiClient
import eu.llembas.android.api.LembasJson
import eu.llembas.android.api.sameBase
import eu.llembas.android.wake.WakeAttempt
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
@@ -21,9 +22,18 @@ 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.
* [base] is the address the person typed, as the address rule reads it; what the instance says
* of its own address is not kept. [id] is a key and nothing more: whatever it was made from, it
* is never taken apart or made again -- the choices kept for the instance, its notifications and
* its push registration all hang on it.
* [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
@@ -88,6 +98,21 @@ object InstanceLogic {
fun pickActive(instances: List<Instance>, activeId: String?, defaultId: String?): Instance? =
instances.firstOrNull { it.id == activeId } ?: pickDefault(instances, defaultId)
/**
* The entry a finished sign-in is kept as. An instance already here for the same account --
* its stored base is the address just typed, or the one the instance says of itself
* ([said], which older versions of the app stored) -- is that same instance: it keeps its
* id, and so everything kept under it, and gets the new token and the typed address. Only an
* instance that is not here yet is a new entry, its id made from the typed address.
*/
fun signedIn(instances: List<Instance>, typed: String, said: String, name: String, email: String, sealedToken: String): Instance {
val twin = instances.firstOrNull {
it.email.equals(email, ignoreCase = true) && (sameBase(it.base, typed) || (said.isNotBlank() && sameBase(it.base, said)))
}
return twin?.copy(base = typed, name = name, sealedToken = sealedToken, signedOut = false)
?: Instance(id = "$email@$typed", base = typed, name = name, email = email, sealedToken = sealedToken)
}
/** Adding [added] replaces any existing entry with the same id, makes it active, and sets it
* as default only when no surviving default exists yet. */
fun afterAdd(instances: List<Instance>, added: Instance, currentDefault: String?): Triple<List<Instance>, String, String> {
@@ -96,6 +121,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<Instance>, refused: (Instance) -> Boolean): List<Instance>? {
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<Instance>, removedId: String, currentActive: String?, currentDefault: String?): Triple<List<Instance>, String?, String?> {
@@ -216,28 +252,42 @@ 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))
suspend fun add(base: String, name: String, email: String, token: String): Instance {
val instance = Instance(
id = "$email@$base",
base = base,
name = name,
email = email,
sealedToken = TokenCipher.seal(token),
)
/**
* A sign-in finished: at [base], the address the person typed as the address rule reads it,
* which is the one kept. [said] is the instance's own word for its address -- never stored,
* and looked at only to know an instance signed in to before ([InstanceLogic.signedIn]).
*/
suspend fun add(base: String, said: String, name: String, email: String, token: String) {
val locked = TokenCipher.seal(token)
context.store.edit { prefs ->
val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
val instance = InstanceLogic.signedIn(all, base, said, name, email, locked)
val (next, activeId, defaultId) = InstanceLogic.afterAdd(all, instance, prefs[DEFAULT])
prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, next)
prefs[ACTIVE] = activeId
prefs[DEFAULT] = defaultId
}
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) {
@@ -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
}
@@ -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<Application>().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<Application>().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<Application>().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.
@@ -90,11 +90,10 @@ import eu.llembas.android.api.LembasJson
import eu.llembas.android.api.ReplyFrame
import eu.llembas.android.api.ReportsFrame
import eu.llembas.android.api.SearchHit
import eu.llembas.android.api.fit
import eu.llembas.android.auth.Instance
import eu.llembas.android.lembas
import eu.llembas.android.ui.explain
import eu.llembas.android.ui.signin.refusal
import eu.llembas.android.ui.signin.unfit
import eu.llembas.android.ui.theme.LocalPalette
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
@@ -200,7 +199,7 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
val state = _state.asStateFlow()
/** Why this instance is refused, once it was asked what it is; null while it fits. */
private var refused: Int? = null
private var refused: String? = null
private var checked = false
/** Read the list; the rows already shown stay while it is read again. */
@@ -214,11 +213,11 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
if (!checked) {
runCatching { Doorstep().discover(api.base) }.onSuccess {
checked = true
refused = refusal(fit(it))
refused = getApplication<Application>().unfit(it)
}
}
refused?.let { said ->
_state.value = ChatsState(error = getApplication<Application>().getString(said))
_state.value = ChatsState(error = said)
return@launch
}
val told = reportsTold
@@ -3,6 +3,7 @@
package eu.llembas.android.ui.signin
import android.app.Application
import android.content.Context
import android.net.Uri
import android.os.Build
import androidx.browser.customtabs.CustomTabsIntent
@@ -19,11 +20,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
@@ -46,18 +49,28 @@ import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.llembas.android.BuildConfig
import eu.llembas.android.R
import eu.llembas.android.api.Address
import eu.llembas.android.api.ApiException
import eu.llembas.android.api.Discovery
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.api.minClient
import eu.llembas.android.api.olderThan
import eu.llembas.android.api.onOrigin
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,28 +81,84 @@ 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
}
/**
* Whether the instance [found] describes asks for a newer app than [version]: the version it
* needs, or null. Asked only of a LLeMbas instance -- what another service says is not a rule.
*/
fun newerAppNeeded(found: Discovery, version: String): String? = found.minClient()?.takeIf { found.service == "lembas" && olderThan(version, it) }
/**
* Why this app will not work with the instance [found] describes, in words, or null when it
* will. An instance that names an oldest version for this app, above [version], says so with
* both versions -- "update the app" -- before anything else is asked of it.
*/
fun Context.unfit(found: Discovery, version: String = BuildConfig.VERSION_NAME): String? {
newerAppNeeded(found, version)?.let { needed -> return getString(R.string.signin_app_too_old, needed, version) }
return refusal(fit(found))?.let { getString(it) }
}
/** 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>(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<Application>().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<Application>().getString(said))
getApplication<Application>().unfit(found)?.let { said ->
_state.value = SignInState.Failed(said)
return@launch
}
// The sign-in goes to the address that was typed and to no other host: where the
// document names its doors elsewhere (a proxy that does not pass the address on),
// that is said, rather than a code asked of a host the person never named.
val doors = found.login.device
if (!onOrigin(base, doors.code) || !onOrigin(base, doors.token)) {
val named = doors.code.ifBlank { found.baseUrl }
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_other_origin, named))
return@launch
}
val device = getApplication<Application>().getString(R.string.device_name)
@@ -97,14 +166,34 @@ 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
getApplication<Application>().lembas.instances.add(
base = found.baseUrl.ifEmpty { base }.trimEnd('/'),
base = base,
said = found.baseUrl,
name = found.name,
email = account?.email.orEmpty(),
token = answer.accessToken,
@@ -115,20 +204,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<Application>().getString(R.string.signin_denied))
return@launch
}
else -> {
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_expired))
else -> pollEnd(answer.error)?.let { said ->
_state.value = SignInState.Failed(getApplication<Application>().getString(said, answer.error.orEmpty()))
return@launch
}
}
}
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_expired))
val last = trouble
_state.value = SignInState.Failed(
if (last != null) getApplication<Application>().explain(last) else getApplication<Application>().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<Application>().explain(e))
}
@@ -139,12 +227,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 +294,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<Instance>,
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() })
}
}
}
+13
View File
@@ -13,6 +13,19 @@
<string name="signin_expired">Kód vypršel, než byl schválen. Zkuste to znovu.</string>
<string name="signin_too_old">Tato instance používá starší LLeMbas. Tato aplikace potřebuje LLeMbas 2.0 nebo novější.</string>
<string name="signin_too_new">Tato instance používá novější rozhraní API pro aplikace než tato aplikace. Aktualizujte aplikaci.</string>
<string name="signin_not_lembas">Na této adrese není žádná instance LLeMbas.</string>
<string name="signin_failed">Přihlášení se nepodařilo dokončit (%1$s). Zkuste to znovu.</string>
<string name="signin_app_too_old">Tato instance potřebuje LLeMbas pro Android %1$s nebo novější, a toto je %2$s. Aktualizujte aplikaci.</string>
<string name="signin_other_origin">Tato instance uvádí pro přihlášení jinou adresu (%1$s), než jakou jste zadali. Její proxy musí předávat adresu, na které je dostupná.</string>
<string name="address_needs_https">Tato aplikace potřebuje adresu https://: prosté http není podporováno.</string>
<string name="address_unreadable">Tuto adresu aplikace nedokáže použít. Zadejte adresu instance, například llm.example.org.</string>
<string name="server_answered">Server odpověděl %1$s.</string>
<string name="timed_out">Instance neodpověděla včas.</string>
<string name="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).</string>
<string name="signed_out">%1$s tento telefon odhlásila. Přihlaste se znovu a pokračujte: vaše chaty i zdejší nastavení zůstávají.</string>
<string name="signed_out_again">Přihlásit se znovu</string>
<string name="signed_out_use">Použít %1$s</string>
<string name="signed_out_remove">Odebrat tuto instanci</string>
<string name="new_chat">Nová konverzace</string>
<string name="empty_chats">Zatím žádné konverzace. Ne všichni, kdo bloudí, jsou ztraceni — založte jednu.</string>
<string name="new_agent_chat">Nová konverzace s agentem</string>
+13
View File
@@ -13,6 +13,19 @@
<string name="signin_expired">Der Code ist abgelaufen, bevor er bestätigt wurde. Versuchen Sie es erneut.</string>
<string name="signin_too_old">Auf dieser Instanz läuft ein älteres LLeMbas. Diese App braucht LLeMbas 2.0 oder neuer.</string>
<string name="signin_too_new">Diese Instanz spricht eine neuere App-API als diese App. Aktualisieren Sie die App.</string>
<string name="signin_not_lembas">Unter dieser Adresse gibt es keine LLeMbas-Instanz.</string>
<string name="signin_failed">Die Anmeldung konnte nicht abgeschlossen werden (%1$s). Versuchen Sie es erneut.</string>
<string name="signin_app_too_old">Diese Instanz braucht LLeMbas für Android %1$s oder neuer, und dies ist %2$s. Aktualisieren Sie die App.</string>
<string name="signin_other_origin">Diese Instanz nennt für die Anmeldung eine andere Adresse (%1$s) als die eingegebene. Ihr Proxy muss die Adresse weitergeben, unter der sie erreicht wird.</string>
<string name="address_needs_https">Diese App braucht eine https://-Adresse: einfaches http wird nicht unterstützt.</string>
<string name="address_unreadable">Diese Adresse kann die App nicht verwenden. Geben Sie die Adresse der Instanz ein, zum Beispiel llm.example.org.</string>
<string name="server_answered">Der Server hat mit %1$s geantwortet.</string>
<string name="timed_out">Die Instanz hat nicht rechtzeitig geantwortet.</string>
<string name="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 &amp; Anmeldedaten, Zertifikat installieren).</string>
<string name="signed_out">%1$s hat dieses Telefon abgemeldet. Melden Sie sich erneut an, um fortzufahren: Ihre Chats und Ihre Einstellungen hier bleiben erhalten.</string>
<string name="signed_out_again">Erneut anmelden</string>
<string name="signed_out_use">%1$s verwenden</string>
<string name="signed_out_remove">Diese Instanz entfernen</string>
<string name="new_chat">Neuer Chat</string>
<string name="empty_chats">Noch keine Chats. Nicht jeder, der wandert, ist verloren — fangen Sie einen an.</string>
<string name="new_agent_chat">Neuer Agent-Chat</string>
+13
View File
@@ -13,6 +13,19 @@
<string name="signin_expired">El código caducó antes de ser aprobado. Inténtelo de nuevo.</string>
<string name="signin_too_old">Esta instancia usa una versión anterior de LLeMbas. Esta aplicación necesita LLeMbas 2.0 o posterior.</string>
<string name="signin_too_new">Esta instancia habla una API de aplicaciones más reciente que esta aplicación. Actualice la aplicación.</string>
<string name="signin_not_lembas">No hay ninguna instancia de LLeMbas en esa dirección.</string>
<string name="signin_failed">No se pudo completar el inicio de sesión (%1$s). Inténtelo de nuevo.</string>
<string name="signin_app_too_old">Esta instancia necesita LLeMbas para Android %1$s o posterior, y esta es la %2$s. Actualice la aplicación.</string>
<string name="signin_other_origin">Esta instancia indica para iniciar sesión otra dirección (%1$s) que la que escribió. Su proxy debe transmitir la dirección por la que se accede a ella.</string>
<string name="address_needs_https">Esta aplicación necesita una dirección https://: no se admite http sin cifrar.</string>
<string name="address_unreadable">La aplicación no puede usar esa dirección. Escriba la dirección de la instancia, por ejemplo llm.example.org.</string>
<string name="server_answered">El servidor respondió %1$s.</string>
<string name="timed_out">La instancia no respondió a tiempo.</string>
<string name="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).</string>
<string name="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.</string>
<string name="signed_out_again">Iniciar sesión de nuevo</string>
<string name="signed_out_use">Usar %1$s</string>
<string name="signed_out_remove">Quitar esta instancia</string>
<string name="new_chat">Nuevo chat</string>
<string name="empty_chats">Aún no hay chats. No todos los que vagan están perdidos — empiece uno.</string>
<string name="new_agent_chat">Nuevo chat de agente</string>
+13
View File
@@ -13,6 +13,19 @@
<string name="signin_expired">Le code a expiré avant d\'être approuvé. Réessayez.</string>
<string name="signin_too_old">Cette instance utilise une version plus ancienne de LLeMbas. Cette application nécessite LLeMbas 2.0 ou plus récent.</string>
<string name="signin_too_new">Cette instance utilise une API d\'application plus récente que cette application. Mettez à jour l\'application.</string>
<string name="signin_not_lembas">Il n\'y a pas d\'instance LLeMbas à cette adresse.</string>
<string name="signin_failed">La connexion n\'a pas pu aboutir (%1$s). Réessayez.</string>
<string name="signin_app_too_old">Cette instance nécessite LLeMbas pour Android %1$s ou plus récent, et ceci est la version %2$s. Mettez à jour l\'application.</string>
<string name="signin_other_origin">Cette instance indique pour la connexion une autre adresse (%1$s) que celle que vous avez saisie. Son proxy doit transmettre l\'adresse par laquelle elle est jointe.</string>
<string name="address_needs_https">Cette application a besoin d\'une adresse https:// : le simple http n\'est pas pris en charge.</string>
<string name="address_unreadable">L\'application ne peut pas utiliser cette adresse. Saisissez l\'adresse de l\'instance, par exemple llm.example.org.</string>
<string name="server_answered">Le serveur a répondu %1$s.</string>
<string name="timed_out">L\'instance n\'a pas répondu à temps.</string>
<string name="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).</string>
<string name="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.</string>
<string name="signed_out_again">Se reconnecter</string>
<string name="signed_out_use">Utiliser %1$s</string>
<string name="signed_out_remove">Retirer cette instance</string>
<string name="new_chat">Nouvelle conversation</string>
<string name="empty_chats">Pas encore de conversation. Tous ceux qui errent ne sont pas perdus — commencez-en une.</string>
<string name="new_agent_chat">Nouvelle conversation d\'agent</string>
+13
View File
@@ -13,6 +13,19 @@
<string name="signin_expired">A kód lejárt, mielőtt jóváhagyták volna. Próbálja újra.</string>
<string name="signin_too_old">Ezen a példányon régebbi LLeMbas fut. Ehhez az alkalmazáshoz LLeMbas 2.0 vagy újabb kell.</string>
<string name="signin_too_new">Ez a példány újabb alkalmazás-API-t használ, mint ez az alkalmazás. Frissítse az alkalmazást.</string>
<string name="signin_not_lembas">Ezen a címen nincs LLeMbas példány.</string>
<string name="signin_failed">A bejelentkezést nem sikerült befejezni (%1$s). Próbálja újra.</string>
<string name="signin_app_too_old">Ehhez a példányhoz az Androidos LLeMbas %1$s vagy újabb verziója kell, ez pedig a %2$s. Frissítse az alkalmazást.</string>
<string name="signin_other_origin">Ez a példány más címet ad meg a bejelentkezéshez (%1$s), mint amit beírt. A proxyjának tovább kell adnia azt a címet, amelyen elérik.</string>
<string name="address_needs_https">Ehhez az alkalmazáshoz https:// cím kell: a sima http nem támogatott.</string>
<string name="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.</string>
<string name="server_answered">A kiszolgáló válasza: %1$s.</string>
<string name="timed_out">A példány nem válaszolt időben.</string>
<string name="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).</string>
<string name="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.</string>
<string name="signed_out_again">Bejelentkezés újra</string>
<string name="signed_out_use">%1$s használata</string>
<string name="signed_out_remove">Példány eltávolítása</string>
<string name="new_chat">Új csevegés</string>
<string name="empty_chats">Még nincs csevegés. Nem mindenki van elveszve, aki bolyong — kezdjen el egyet.</string>
<string name="new_agent_chat">Új ügynök-csevegés</string>
+13
View File
@@ -13,6 +13,19 @@
<string name="signin_expired">Il codice è scaduto prima di essere approvato. Riprova.</string>
<string name="signin_too_old">Questa istanza usa una versione precedente di LLeMbas. Questa app richiede LLeMbas 2.0 o successivo.</string>
<string name="signin_too_new">Questa istanza usa un\'API per l\'app più recente di questa app. Aggiorna l\'app.</string>
<string name="signin_not_lembas">Non c\'è nessuna istanza LLeMbas a quell\'indirizzo.</string>
<string name="signin_failed">Non è stato possibile completare l\'accesso (%1$s). Riprova.</string>
<string name="signin_app_too_old">Questa istanza richiede LLeMbas per Android %1$s o successivo, e questa è la %2$s. Aggiorna l\'app.</string>
<string name="signin_other_origin">Questa istanza indica per l\'accesso un indirizzo diverso (%1$s) da quello che hai scritto. Il suo proxy deve inoltrare l\'indirizzo con cui viene raggiunta.</string>
<string name="address_needs_https">Questa app richiede un indirizzo https://: il semplice http non è supportato.</string>
<string name="address_unreadable">L\'app non può usare questo indirizzo. Scrivi l\'indirizzo dell\'istanza, ad esempio llm.example.org.</string>
<string name="server_answered">Il server ha risposto %1$s.</string>
<string name="timed_out">L\'istanza non ha risposto in tempo.</string>
<string name="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).</string>
<string name="signed_out">%1$s ha disconnesso questo telefono. Accedi di nuovo per continuare: le tue chat e le impostazioni fatte qui restano.</string>
<string name="signed_out_again">Accedi di nuovo</string>
<string name="signed_out_use">Usa %1$s</string>
<string name="signed_out_remove">Rimuovi questa istanza</string>
<string name="new_chat">Nuova chat</string>
<string name="empty_chats">Ancora nessuna chat. Non tutti quelli che vagano sono perduti — iniziane una.</string>
<string name="new_agent_chat">Nuova chat agente</string>
+13
View File
@@ -13,6 +13,19 @@
<string name="signin_expired">Kod wygasł, zanim został zatwierdzony. Spróbuj ponownie.</string>
<string name="signin_too_old">Ta instancja działa na starszym LLeMbas. Ta aplikacja wymaga LLeMbas 2.0 lub nowszego.</string>
<string name="signin_too_new">Ta instancja używa nowszego API aplikacji niż ta aplikacja. Zaktualizuj aplikację.</string>
<string name="signin_not_lembas">Pod tym adresem nie ma instancji LLeMbas.</string>
<string name="signin_failed">Nie udało się dokończyć logowania (%1$s). Spróbuj ponownie.</string>
<string name="signin_app_too_old">Ta instancja wymaga LLeMbas dla Androida %1$s lub nowszego, a to jest %2$s. Zaktualizuj aplikację.</string>
<string name="signin_other_origin">Ta instancja podaje do logowania inny adres (%1$s) niż wpisany. Jej proxy musi przekazywać adres, pod którym jest dostępna.</string>
<string name="address_needs_https">Ta aplikacja wymaga adresu https://: zwykłe http nie jest obsługiwane.</string>
<string name="address_unreadable">Aplikacja nie może użyć tego adresu. Wpisz adres instancji, na przykład llm.example.org.</string>
<string name="server_answered">Serwer odpowiedział: %1$s.</string>
<string name="timed_out">Instancja nie odpowiedziała na czas.</string>
<string name="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).</string>
<string name="signed_out">%1$s wylogowała ten telefon. Zaloguj się ponownie, aby kontynuować: Twoje czaty i tutejsze ustawienia zostają.</string>
<string name="signed_out_again">Zaloguj się ponownie</string>
<string name="signed_out_use">Użyj %1$s</string>
<string name="signed_out_remove">Usuń tę instancję</string>
<string name="new_chat">Nowy czat</string>
<string name="empty_chats">Nie ma jeszcze czatów. Nie każdy, kto błądzi, jest zgubiony — zacznij jeden.</string>
<string name="new_agent_chat">Nowy czat agenta</string>
+13
View File
@@ -13,6 +13,19 @@
<string name="signin_expired">Kód vypršal skôr, než bol schválený. Skúste to znova.</string>
<string name="signin_too_old">Táto inštancia beží na staršom LLeMbas. Táto aplikácia potrebuje LLeMbas 2.0 alebo novší.</string>
<string name="signin_too_new">Táto inštancia používa novšie API pre aplikácie než táto aplikácia. Aktualizujte aplikáciu.</string>
<string name="signin_not_lembas">Na tejto adrese nie je žiadna inštancia LLeMbas.</string>
<string name="signin_failed">Prihlásenie sa nepodarilo dokončiť (%1$s). Skúste to znova.</string>
<string name="signin_app_too_old">Táto inštancia potrebuje LLeMbas pre Android %1$s alebo novší, a toto je %2$s. Aktualizujte aplikáciu.</string>
<string name="signin_other_origin">Táto inštancia uvádza na prihlásenie inú adresu (%1$s), než akú ste zadali. Jej proxy musí odovzdávať adresu, na ktorej je dostupná.</string>
<string name="address_needs_https">Táto aplikácia potrebuje adresu https://: obyčajné http nie je podporované.</string>
<string name="address_unreadable">Túto adresu aplikácia nevie použiť. Zadajte adresu inštancie, napríklad llm.example.org.</string>
<string name="server_answered">Server odpovedal %1$s.</string>
<string name="timed_out">Inštancia neodpovedala včas.</string>
<string name="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).</string>
<string name="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ú.</string>
<string name="signed_out_again">Prihlásiť sa znova</string>
<string name="signed_out_use">Použiť %1$s</string>
<string name="signed_out_remove">Odstrániť túto inštanciu</string>
<string name="new_chat">Nová konverzácia</string>
<string name="empty_chats">Zatiaľ žiadne konverzácie. Nie všetci, čo blúdia, sú stratení — začnite jednu.</string>
<string name="new_agent_chat">Nová konverzácia s agentom</string>
+13
View File
@@ -14,6 +14,19 @@
<string name="signin_expired">The code expired before it was approved. Try again.</string>
<string name="signin_too_old">This instance runs an older LLeMbas. This app needs LLeMbas 2.0 or newer.</string>
<string name="signin_too_new">This instance speaks a newer app API than this app. Update the app.</string>
<string name="signin_not_lembas">There is no LLeMbas instance at that address.</string>
<string name="signin_failed">The sign-in could not be completed (%1$s). Try again.</string>
<string name="signin_app_too_old">This instance needs LLeMbas for Android %1$s or newer, and this is %2$s. Update the app.</string>
<string name="signin_other_origin">This instance names another address for signing in (%1$s) than the one you typed. Its proxy has to pass on the address it is reached by.</string>
<string name="address_needs_https">This app needs an https:// address: plain http is not supported.</string>
<string name="address_unreadable">That is not an address this app can use. Type the instance\'s address, like llm.example.org.</string>
<string name="server_answered">The server answered %1$s.</string>
<string name="timed_out">The instance did not answer in time.</string>
<string name="not_trusted">This phone does not trust the instance\'s certificate: install its CA certificate among Android\'s user certificates (Settings, Security, Encryption &amp; credentials, Install a certificate).</string>
<string name="signed_out">%1$s signed this phone out. Sign in again to go on: your chats and what you set up here are kept.</string>
<string name="signed_out_again">Sign in again</string>
<string name="signed_out_use">Use %1$s</string>
<string name="signed_out_remove">Remove this instance</string>
<string name="new_chat">New chat</string>
<string name="empty_chats">No chats yet. Not all those who wander are lost — start one.</string>
<string name="new_agent_chat">New agent chat</string>
@@ -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"}}"""))
@@ -0,0 +1,595 @@
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.Discovery
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.minClient
import eu.llembas.android.api.olderThan
import eu.llembas.android.api.onOrigin
import eu.llembas.android.api.refusedToken
import eu.llembas.android.api.reopened
import eu.llembas.android.api.retryAfterSeconds
import eu.llembas.android.api.sameBase
import eu.llembas.android.api.userAgent
import eu.llembas.android.api.versionNumbers
import eu.llembas.android.auth.Instance
import eu.llembas.android.auth.InstanceLogic
import eu.llembas.android.auth.Prefs
import eu.llembas.android.ui.Trouble
import eu.llembas.android.ui.signin.newerAppNeeded
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")))
}
// --- Which address is kept, and which instance a sign-in is ---------------------------------
private val listed = ListSerializer(Instance.serializer())
/** What a version of the app before this one stored: the instance's own word for its address, and an id made of it. */
private val stored = """[
{"id":"alice@https://home.example","base":"https://home.example","name":"Home","email":"alice","sealedToken":"t1"},
{"id":"bob@https://Work.example:8443","base":"https://Work.example:8443","name":"Work","email":"bob","sealedToken":"t2"}
]"""
@Test
fun anInstanceFromBeforeIsUntouchedByTheUpgrade() {
val read = LembasJson.decodeFromString(listed, stored)
// Nothing is made again on reading: the id, the base and the token are what was stored, to the letter.
assertEquals(listOf("alice@https://home.example", "bob@https://Work.example:8443"), read.map { it.id })
assertEquals(listOf("https://home.example", "https://Work.example:8443"), read.map { it.base })
assertEquals(listOf("t1", "t2"), read.map { it.sealedToken })
assertTrue(read.none { it.signedOut })
// Which one is in use and which is the default are found by those same ids.
assertEquals(read[1], InstanceLogic.pickActive(read, "bob@https://Work.example:8443", "alice@https://home.example"))
assertEquals(read[0], InstanceLogic.pickDefault(read, "alice@https://home.example"))
// And what is kept per instance is still found under them.
val prefs = Prefs().withInstance(read[1].id) { it.copy(assistantModel = "fast-work") }
assertEquals("fast-work", prefs.forInstance(LembasJson.decodeFromString(listed, stored)[1].id).assistantModel)
}
@Test
fun aSignInToAnInstanceAlreadyHereRefreshesItAndAddsNoTwin() {
val before = LembasJson.decodeFromString(listed, stored)
// Typed by another name than the one stored; the instance still says the old one of itself.
val again = InstanceLogic.signedIn(
before,
typed = "https://home.example.net",
said = "https://home.example/",
name = "Home",
email = "Alice",
sealedToken = "t9",
)
assertEquals("alice@https://home.example", again.id)
assertEquals("https://home.example.net", again.base)
assertEquals("t9", again.sealedToken)
assertEquals("alice", again.email)
val (list, active, default) = InstanceLogic.afterAdd(before, again, "bob@https://Work.example:8443")
assertEquals(2, list.size)
assertEquals(setOf("alice@https://home.example", "bob@https://Work.example:8443"), list.map { it.id }.toSet())
assertEquals("alice@https://home.example", active)
assertEquals("bob@https://Work.example:8443", default)
// Another account at the same address is another instance, as it always was.
val carol = InstanceLogic.signedIn(
before,
typed = "https://home.example",
said = "https://home.example",
name = "Home",
email = "carol",
sealedToken = "t3",
)
assertEquals("carol@https://home.example", carol.id)
assertEquals(3, InstanceLogic.afterAdd(before, carol, null).first.size)
// And the same account somewhere else is a new one too: its id is made of the typed address.
val elsewhere = InstanceLogic.signedIn(before, typed = "https://other.example", said = "", name = "Other", email = "alice", sealedToken = "t4")
assertEquals("alice@https://other.example", elsewhere.id)
assertEquals("https://other.example", elsewhere.base)
}
@Test
fun aSignedOutInstanceSignedInToAgainIsItselfAgain() {
val before = LembasJson.decodeFromString(listed, stored).map { it.copy(signedOut = true) }
val again = InstanceLogic.signedIn(before, typed = "https://home.example", said = "", name = "Home", email = "alice", sealedToken = "t9")
assertEquals("alice@https://home.example", again.id)
assertFalse(again.signedOut)
assertTrue(InstanceLogic.afterAdd(before, again, null).first.single { it.id == "bob@https://Work.example:8443" }.signedOut)
}
@Test
fun anAddressTypedInItsVariantsIsOneInstance() {
val before = LembasJson.decodeFromString(listed, stored)
val variants = listOf("work.example:8443", "HTTPS://WORK.example:8443/", "https://work.example:8443/chat?x=1#y", " https://Work.Example:8443 ")
for (typed in variants) {
val base = (address(typed) as Address.Base).url
assertEquals(typed, "https://work.example:8443", base)
val again = InstanceLogic.signedIn(before, typed = base, said = "", name = "Work", email = "bob", sealedToken = "t9")
// The entry stored with a capital in its base is found, and keeps its id as it was stored.
assertEquals(typed, "bob@https://Work.example:8443", again.id)
assertEquals(typed, 2, InstanceLogic.afterAdd(before, again, null).first.size)
}
assertTrue(sameBase("https://example.org", "https://EXAMPLE.org:443/"))
assertFalse(sameBase("https://example.org", "https://example.org:8443"))
assertFalse(sameBase("https://example.org", "https://www.example.org"))
// A base the rule does not read (an older version stored what the instance said) is compared as it stands.
assertTrue(sameBase("http://inside.example:8000", "http://Inside.example:8000/"))
assertFalse(sameBase("http://inside.example:8000", "https://inside.example:8000"))
}
@Test
fun theSignInGoesOnlyToTheAddressThatWasTyped() {
assertTrue(onOrigin("https://llm.example.org", "https://llm.example.org/api/device/code"))
assertTrue(onOrigin("https://llm.example.org", "https://LLM.example.org:443/api/device/token"))
assertFalse(onOrigin("https://llm.example.org", "https://other.example.org/api/device/code"))
assertFalse(onOrigin("https://llm.example.org", "http://llm.example.org/api/device/code"))
assertFalse(onOrigin("https://llm.example.org", "https://llm.example.org:8443/api/device/code"))
assertFalse(onOrigin("https://llm.example.org", ""))
}
// --- An instance that needs a newer app ------------------------------------------------------
private fun found(json: String) = LembasJson.decodeFromString(Discovery.serializer(), json)
@Test
fun versionsCompareByTheirNumbers() {
assertTrue(olderThan("1.0.0-beta.9", "1.0.0-beta.10"))
assertFalse(olderThan("1.0.0-beta.10", "1.0.0-beta.9"))
assertTrue(olderThan("1.0.0-beta.16", "1.0.0"))
assertFalse(olderThan("1.0.0", "1.0.0-beta.99"))
assertFalse(olderThan("1.0.0-beta.16", "1.0.0-beta.16"))
assertTrue(olderThan("1.9.9", "1.10.0"))
assertTrue(olderThan("1.0.0", "2.0.0-beta.1"))
assertFalse(olderThan("2.0.0-beta.1", "1.99.99"))
// A build's own mark is left off: a test build of beta.16 is beta.16.
assertFalse(olderThan("1.0.0-beta.16-debug.412", "1.0.0-beta.16"))
assertTrue(olderThan("1.0.0-beta.16-debug.412", "1.0.0-beta.17"))
assertFalse(olderThan("1.0.0-notifications", "1.0.0"))
assertEquals(versionNumbers("1.0.0"), versionNumbers("v1.0.0"))
// Nonsense locks nobody out.
assertFalse(olderThan("1.0.0", "newest"))
assertFalse(olderThan("dev", "9.9.9"))
assertNull(versionNumbers("1.0"))
}
@Test
fun anInstanceMaySayWhichAppIsTooOld() {
val says = found("""{"service":"lembas","min_clients":{"android":"1.0.0","desktop":"1.2.0"},"something_new":{"a":[1,2]}}""")
assertEquals("1.0.0", says.minClient())
assertEquals("1.0.0", newerAppNeeded(says, "1.0.0-beta.16"))
assertNull(newerAppNeeded(says, "1.0.0"))
assertNull(newerAppNeeded(says, "1.0.1-debug.3"))
// Said of other products only, or not at all: nothing is asked of this app.
assertNull(found("""{"service":"lembas","min_clients":{"desktop":"9.0.0"}}""").minClient())
assertNull(found("""{"service":"lembas"}""").minClient())
// A shape this app does not expect is "says nothing" -- the document is still read.
assertNull(found("""{"service":"lembas","min_clients":["android"]}""").minClient())
assertNull(found("""{"service":"lembas","min_clients":{"android":7}}""").minClient())
assertNull(found("""{"service":"lembas","min_clients":{"android":null}}""").minClient())
assertNull(found("""{"service":"lembas","min_clients":null}""").minClient())
// Another service's rule is not a rule.
assertNull(newerAppNeeded(found("""{"service":"other","min_clients":{"android":"9.0.0"}}"""), "1.0.0"))
}
// --- 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<String>()
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<Long>()
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<Outcome> { emit(Outcome.Event(Frame("tail", "{}"))) } else flow<Outcome> { 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<Long>()
reopened(turn = {}, schedule = Reconnect { 0.5 }, clock = { now }) {
opened++
at += currentTime
when (opened) {
// Broke at once, twice: 1 second, then 2.
1, 2 -> flow<Outcome> { emit(Outcome.Dropped) }
// Then held for half a minute before it broke: 1 second again, not 4.
3 -> flow<Outcome> {
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<Outcome> { emit(Outcome.Slowed(7)) }
else -> flow<Outcome> { 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("<html>Bad Gateway</html>"))
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("<html>Welcome</html>"))
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("<html>Bad Gateway</html>"))
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)
}
}
}
+5 -1
View File
@@ -20,7 +20,11 @@ patterns=(
)
found=0
for pattern in "${patterns[@]}"; do
if git ls-files -z | grep -zv '^scripts/hygiene.sh$' | xargs -0 grep -nIEi -- "$pattern" ; then
# The output decides, not the exit status: xargs answers 123 when any one batch of files has no
# match, and grep 2 on an error -- either would have read as "clean" around real matches.
hits=$(git ls-files -z | grep -zv '^scripts/hygiene.sh$' | xargs -0 grep -nIEi -- "$pattern" 2>/dev/null || true)
if [ -n "$hits" ]; then
printf '%s\n' "$hits"
echo "hygiene: the lines above match /$pattern/" >&2
found=1
fi
+15
View File
@@ -25,6 +25,21 @@ 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.",
"signin_app_too_old": "This instance needs LLeMbas for Android %1$s or newer, and this is %2$s. Update the app.",
"signin_other_origin": "This instance names another address for signing in (%1$s) than the one you typed. Its proxy has to pass on the address it is reached by.",
"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.",
+112 -8
View File
@@ -434,7 +434,20 @@
"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",
"signin_app_too_old": "Tato instance potřebuje LLeMbas pro Android %1$s nebo novější, a toto je %2$s. Aktualizujte aplikaci.",
"signin_other_origin": "Tato instance uvádí pro přihlášení jinou adresu (%1$s), než jakou jste zadali. Její proxy musí předávat adresu, na které je dostupná."
},
"de": {
"about_version": "LLeMbas für Android %1$s",
@@ -872,7 +885,20 @@
"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",
"signin_app_too_old": "Diese Instanz braucht LLeMbas für Android %1$s oder neuer, und dies ist %2$s. Aktualisieren Sie die App.",
"signin_other_origin": "Diese Instanz nennt für die Anmeldung eine andere Adresse (%1$s) als die eingegebene. Ihr Proxy muss die Adresse weitergeben, unter der sie erreicht wird."
},
"es": {
"about_version": "LLeMbas para Android %1$s",
@@ -1309,7 +1335,20 @@
"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",
"signin_app_too_old": "Esta instancia necesita LLeMbas para Android %1$s o posterior, y esta es la %2$s. Actualice la aplicación.",
"signin_other_origin": "Esta instancia indica para iniciar sesión otra dirección (%1$s) que la que escribió. Su proxy debe transmitir la dirección por la que se accede a ella."
},
"fr": {
"about_version": "LLeMbas pour Android %1$s",
@@ -1747,7 +1786,20 @@
"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",
"signin_app_too_old": "Cette instance nécessite LLeMbas pour Android %1$s ou plus récent, et ceci est la version %2$s. Mettez à jour l'application.",
"signin_other_origin": "Cette instance indique pour la connexion une autre adresse (%1$s) que celle que vous avez saisie. Son proxy doit transmettre l'adresse par laquelle elle est jointe."
},
"hu": {
"about_version": "LLeMbas Androidra %1$s",
@@ -2185,7 +2237,20 @@
"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",
"signin_app_too_old": "Ehhez a példányhoz az Androidos LLeMbas %1$s vagy újabb verziója kell, ez pedig a %2$s. Frissítse az alkalmazást.",
"signin_other_origin": "Ez a példány más címet ad meg a bejelentkezéshez (%1$s), mint amit beírt. A proxyjának tovább kell adnia azt a címet, amelyen elérik."
},
"it": {
"about_version": "LLeMbas per Android %1$s",
@@ -2622,7 +2687,20 @@
"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",
"signin_app_too_old": "Questa istanza richiede LLeMbas per Android %1$s o successivo, e questa è la %2$s. Aggiorna l'app.",
"signin_other_origin": "Questa istanza indica per l'accesso un indirizzo diverso (%1$s) da quello che hai scritto. Il suo proxy deve inoltrare l'indirizzo con cui viene raggiunta."
},
"pl": {
"about_version": "LLeMbas na Androida %1$s",
@@ -3059,7 +3137,20 @@
"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ę",
"signin_app_too_old": "Ta instancja wymaga LLeMbas dla Androida %1$s lub nowszego, a to jest %2$s. Zaktualizuj aplikację.",
"signin_other_origin": "Ta instancja podaje do logowania inny adres (%1$s) niż wpisany. Jej proxy musi przekazywać adres, pod którym jest dostępna."
},
"sk": {
"about_version": "LLeMbas pre Android %1$s",
@@ -3496,6 +3587,19 @@
"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",
"signin_app_too_old": "Táto inštancia potrebuje LLeMbas pre Android %1$s alebo novší, a toto je %2$s. Aktualizujte aplikáciu.",
"signin_other_origin": "Táto inštancia uvádza na prihlásenie inú adresu (%1$s), než akú ste zadali. Jej proxy musí odovzdávať adresu, na ktorej je dostupná."
}
}