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
Homer 549ce17645 1.0.0-beta.16: default instance, drawer switcher, and per-instance prefs
CI / check (push) Canceled after 0s
Release / release (push) Canceled after 0s
2026-11-26 10:50:02 +00:00
Homer 4e1a16a351 Format Kotlin function signatures for ktlint
CI / check (push) Canceled after 0s
2026-11-26 09:58:48 +00:00
Homer 864bdc6b6e Add default instance selection, drawer switcher, and per-instance prefs
CI / check (push) Canceled after 0s
2026-11-26 09:55:36 +00:00
HomerandClaude Fable 5.2 79cd9f3804 1.0.0-beta.15: files an agent shows, an edit's diff on its approval, the app's own icon; pinned to LLeMbas 2.0.0-beta.19
CI / check (push) Canceled after 0s
Release / release (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 15:50:46 +00:00
HomerandClaude Fable 5.2 08a720465e A session that ends without being hidden leaves the gate shut
CI / check (push) Canceled after 0s
The sheet's flag at the gate is cleared when the session is destroyed and
when its service is, not only when it hides: Android may tear a session
down without hiding it, and the gate would have stayed open with nothing of
the app in front.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 14:10:27 +00:00
HomerandClaude Fable 5.2 bac89b5e68 A review of the shown files and the diff card: the sheet opens the gate, the diff is bounded first
CI / check (push) Canceled after 0s
The assistant's sheet is a session's window and no activity, so the gate a
reply's picture now waits at never opened for it: the session says when it
shows and hides, and the lock still keeps the gate shut.

An edit's diff is worked out off the main thread, one file after another,
and each text is cut to 2000 lines and 200000 characters before anything is
split or compared; a change that was cut says so. Lines are compared
without the carriage return before their newline, and a change of line
endings is said once. Invisible, direction-changing and line-breaking
characters in a line or a path are written as their code point. The call's
arguments stay on the card when the diffs say nothing.

"Open with" takes the type from the copy's first bytes, else from its
name's extension, and no longer from the instance's word.

Tests: the too-long case now shares lines out of order and can fail; the
device file fixtures are checked by field; the gate with the session; the
bounds, the line endings, the escaping, the arguments and the type.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 13:52:03 +00:00
HomerandClaude Fable 5.2 5e5e63353a A file an agent shows is in the chat by its kind; an edit's diff is on its approval card
CI / check (push) Canceled after 0s
A tool call's `media` with `shown` is drawn where generated media is: a
picture with its name under it, audio and video with Play, a PDF with Open
(its pages over the chat, by node id), and a 3D model, an archive, a text
file, a binary and any kind the app does not know as a row with the name,
the kind in words and the size. Every card keeps Open in Files, Download,
Share and Open with. `audio` plays as `music` does.

An approval item's `diffs` are worked out on the phone line by line
(api/Diff.kt: shared head and tail, the longest shared run in between up to
a bounded size, three lines of context) and drawn as one plain monospaced
text per file in a sideways scroller of its own, folded past twelve lines
and laid out to four hundred. The diff stands where the call's arguments
did; Allow and Deny are unchanged.

A picture in a chat now waits at the gate before it is fetched. Parsed and
not drawn: a device's files, files_writable and files_that_run_code, and
the editor's two models.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 13:31:30 +00:00
HomerandClaude Fable 5.2 660ff90b3a Pinned to the server's dev at 809b87b: shown files, an edit's diff, a computer's files
Seventeen new contract files: tool_media_shown, event_ask_edit, editor,
editor_unset, message_editor and the twelve device_fs_* shapes. devices.json
gained files, files_writable and files_that_run_code per device. Tokens are
read at the same commit (the colours did not move, only the commit they name).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 13:31:22 +00:00
HomerandClaude Fable 5.2 9610a8a9d8 The launcher icon is the app's own: the leaf with a phone beside it
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 11:44:59 +00:00
77 changed files with 4281 additions and 272 deletions

No files matched your search

+110
View File
@@ -3,6 +3,116 @@
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
- **Default instance and quick drawer switcher.** Choose a **Default** account
or instance in Settings → Instances (marked with a badge and opened on cold
starts, as well as used by Assistant, Widget, and Share actions). Switch
between saved accounts and instances directly from the navigation drawer or
add another account with quick-pick chips for existing servers.
- **Per-account actions in Settings.** Every saved account row now offers
*Set as default* and *Sign out* from its overflow menu (not only the active
account).
### Changed
- **Per-instance preferences isolation.** Assistant model, last assistant chat,
and account language are now stored per instance rather than leaking across
accounts when switching.
## [1.0.0-beta.15] — 2026-11-24
What is said here of shown files and of an edit's diff needs an instance newer than LLeMbas
2.0.0-beta.18. On an older one the app behaves as before.
### Added
- **A file an agent shows is in the chat, whatever it is.** When an agent puts a file in front
of you that is not text -- a screenshot it took, a recording, a report -- the reply holds it
where generated media is: a picture is drawn, with its name under it; sound and video have
Play and the app's own player; a PDF has Open, which lays its pages out over the chat. A 3D
model, an archive, a text file that came this way and any other file are a row with the
file's name, what it is in words and its size. A kind the app has not heard of is a "File",
never an empty place. Every one of them has Open in Files, Download, Share and Open with.
Whether a file is shown does not depend on what the model itself can read.
- **An edit's approval card shows what would change.** Where a linked computer asks before an
edit, the card lists each file with the lines that go and the lines that come, marked by a
sign and by colour, with a little unchanged text around them; a new file and a deleted one
say so. Long lines scroll sideways inside their own box; a long change is folded to its first
lines with "Show all". Both texts are drawn as plain text. Allow and Deny are as they were.
A character that cannot be seen or that changes the direction of a line, in a line or in a
path, is written as its code point (`<U+202E>`), so what the card shows is what is written. A
file whose line endings change says so once instead of showing every line twice. A very long
change is compared only at its beginning and says so, and is worked out beside the screen,
not in it. The call's arguments stay in view when there is no change to show.
### Changed
- **A picture in a chat is fetched only while the app is in front of an unlocked phone**, like
every other file of the account; one that comes into view behind the lock waits. The
assistant's sheet counts as the app in front, so a picture in it is fetched as before.
- **"Open with" offers a file as what it is.** The type handed to the other app is read from the
file's own first bytes, or from its name's extension where the bytes carry no mark, and no
longer taken from what the instance said of it.
- Pinned to the server's `dev` at `809b87b`. A linked computer's files and the editor's two
models are read from the instance and not shown anywhere yet: this app has no browser for a
computer's files and no screen for the editor's settings.
- **The launcher icon is the app's own**: the LLeMbas leaf with a small phone beside it, so the app
is told apart from the other LLeMbas products. The notification icon stays the leaf.
## [1.0.0-beta.14] — 2026-11-24
What is said here of replies that start by themselves needs an instance newer than LLeMbas
+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.14"
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
@@ -11,6 +11,7 @@ import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
/**
@@ -20,11 +21,13 @@ import java.util.concurrent.atomic.AtomicInteger
* is not touched, so what the person started finishes; the next one waits here, and goes on by
* itself when the app is in front of an unlocked phone again.
*
* The process has one ([LembasApp.gate]). It hears of the app's activities starting and stopping
* and of the screen going off and the phone being unlocked; [locked] is asked each time.
* The process has one ([LembasApp.gate]). It hears of the app's activities starting and stopping,
* of the assistant's sheet showing and hiding (a session's window, which is no activity), and of
* the screen going off and the phone being unlocked; [locked] is asked each time.
*/
class InstanceGate(private val locked: () -> Boolean) {
private val started = AtomicInteger(0)
private val sheet = AtomicBoolean(false)
private val state = MutableStateFlow(false)
/** Whether a request may start now, as it was last looked at. */
@@ -40,9 +43,25 @@ class InstanceGate(private val locked: () -> Boolean) {
look()
}
/**
* The assistant's sheet is up. It is a window of the system's session and no activity, so it
* says so itself: the app is in front while it shows, as while an activity is started. Told
* once however often the system shows a sheet that is already up. The lock still shuts the
* gate: a sheet over the lock screen asks the instance for nothing.
*/
fun sessionShown() {
sheet.set(true)
look()
}
fun sessionHidden() {
sheet.set(false)
look()
}
/** Looks again (the screen went off, the phone was unlocked) and says whether a request may start. */
fun look(): Boolean {
val now = started.get() > 0 && !locked()
val now = (started.get() > 0 || sheet.get()) && !locked()
state.value = now
return now
}
@@ -118,3 +137,16 @@ suspend fun <T> sendFrom(items: List<T>, from: Int, turn: suspend () -> Unit, do
done(i + 1)
}
}
/**
* The assistant's sheet as the gate hears of it: every way the session's window can go says so.
* Android may show a sheet that is up again, hide it once, or tear the session down without
* hiding it at all -- [gone] is for each of those ends, so the sheet can never be left counted
* as the app in front when nothing of the app is.
*/
class SheetAtGate(private val gate: InstanceGate) {
fun shown() = gate.sessionShown()
/** Hidden, destroyed, or its service gone: whichever comes, and however many of them. */
fun gone() = gate.sessionHidden()
}
@@ -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
@@ -45,6 +48,7 @@ import eu.llembas.android.auth.Prefs
import eu.llembas.android.push.Notifications
import eu.llembas.android.push.Push
import eu.llembas.android.ui.chat.ChatScreen
import eu.llembas.android.ui.files.FileCache
import eu.llembas.android.ui.files.FilesScreen
import eu.llembas.android.ui.home.ArchivedScreen
import eu.llembas.android.ui.home.ChatsViewModel
@@ -61,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
@@ -85,6 +90,9 @@ class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
if (savedInstanceState == null && intent?.getStringExtra(Notifications.EXTRA_INSTANCE).isNullOrBlank()) {
lifecycleScope.launch { lembas.instances.resetToDefault() }
}
take(intent)
followLanguage()
// At most once a day, and only while Settings › About says so (update/ReleaseCheck.kt).
@@ -172,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)
}
},
)
}
}
}
@@ -189,6 +235,8 @@ class MainActivity : ComponentActivity() {
val scope = rememberCoroutineScope()
val chats: ChatsViewModel = viewModel()
val list by chats.state.collectAsStateWithLifecycle()
val instances by lembas.instances.instances.collectAsState(initial = emptyList())
val defaultInstance by lembas.instances.defaultInstance.collectAsState(initial = null)
val entry by nav.currentBackStackEntryAsState()
val route = entry?.destination?.route
val current = entry?.arguments?.getString("id")?.takeIf { route == "chat/{id}" }
@@ -206,8 +254,16 @@ class MainActivity : ComponentActivity() {
// The account's language, which the app follows unless Settings › Language says
// otherwise. Read once per instance in use; kept, so the next start has it at once.
LaunchedEffect(instance.id) {
val cached = lembas.instances.prefs.first().forInstance(instance.id).accountLanguage
if (cached.isNotBlank()) {
lembas.instances.savePrefs { it.copy(accountLanguage = cached) }
}
runCatching { lembas.instances.clientFor(instance).me() }.onSuccess { me ->
me.accountLanguage?.let { language -> lembas.instances.savePrefs { it.copy(accountLanguage = language) } }
me.accountLanguage?.let { language ->
lembas.instances.savePrefs { p ->
p.withInstance(instance.id) { it.copy(accountLanguage = language) }.copy(accountLanguage = language)
}
}
}
}
// The list is read again each time the drawer opens, so a new title or a finished
@@ -276,6 +332,16 @@ class MainActivity : ComponentActivity() {
override fun settings() = over("settings")
override fun useInstance(instance: Instance) {
scope.launch {
drawer.close()
lembas.instances.use(instance.id)
FileCache.clear(this@MainActivity)
}
}
override fun addInstance() = over("add")
override fun more() = chats.more()
override fun retry() = chats.load()
@@ -292,7 +358,15 @@ class MainActivity : ComponentActivity() {
// The drawer opens by a swipe only from a chat: elsewhere the swipe is Back's.
gesturesEnabled = drawer.isOpen || route == "new" || route == "new-agent" || route == "chat/{id}",
drawerContent = {
DrawerContent(list, current, listOf(instance.name, instance.email).filter { it.isNotBlank() }.joinToString(" · "), actions)
DrawerContent(
list,
current,
listOf(instance.name, instance.email).filter { it.isNotBlank() }.joinToString(" · "),
actions,
instances = instances,
activeInstance = instance,
defaultInstanceId = defaultInstance?.id,
)
},
) {
NavHost(nav, startDestination = "new") {
@@ -403,7 +477,7 @@ class MainActivity : ComponentActivity() {
}
// Signing in to one more instance makes it the one in use, which starts a
// fresh navigation for it (the `key` above).
composable("add") { SignInScreen(onDone = { nav.popBackStack() }) }
composable("add") { SignInScreen(onDone = { nav.popBackStack() }, onCancel = { nav.popBackStack() }) }
}
}
}
@@ -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,199 @@
package eu.llembas.android.api
// An edit's diff on its approval card, worked out on the phone from the two texts the card
// carries (`contract/event_ask_edit.json`). Lines only: what is drawn is text with a sign, and
// every step is bounded before it is taken, because both texts are a model's and a file's words
// of any size.
/** What a line of a diff is: in both texts, only in the new one, only in the old one, or the mark of lines left out between two changes. */
enum class DiffSign { Same, Added, Removed, Gap }
data class DiffLine(val sign: DiffSign, val text: String)
/**
* One file's change as the card draws it: the changed lines with a little around them, and how
* many were added and removed. [endings] says a change of line endings (`"LF" to "CRLF"`), which
* is said once instead of as every line going and coming. [cut]: the texts were longer than what
* a phone compares, and only their beginning was.
*/
data class DiffView(val lines: List<DiffLine>, val added: Int, val removed: Int, val endings: Pair<String, String>? = null, val cut: Boolean = false) {
/** The lines drawn: the first [DIFF_FOLD] until the person opens it, and never more than [DIFF_MOST]. */
fun shown(open: Boolean): List<DiffLine> = lines.take(if (open) DIFF_MOST else DIFF_FOLD)
/** Whether there is more than the folded card shows. */
val folds: Boolean get() = lines.size > DIFF_FOLD
/** The lines not drawn even when open. */
val beyond: Int get() = (lines.size - DIFF_MOST).coerceAtLeast(0)
/** Whether the block says anything of the change at all; a card whose diffs say nothing keeps its arguments in view. */
val says: Boolean get() = lines.isNotEmpty() || endings != null || cut
}
/** How many lines of a file's diff the card shows before it is opened. */
const val DIFF_FOLD = 12
/** The most lines of one file's diff the card lays out: a card is for deciding, not for reading a megabyte. */
const val DIFF_MOST = 400
/** The lines kept around a change. */
const val DIFF_CONTEXT = 3
/** Past this many pairs of lines the two middles are not compared: the old one is shown going and the new one coming. */
private const val DIFF_CELLS = 1_000_000L
/** The most lines of one text that are compared, and the most characters: what is past either is left out before any work is done. */
const val DIFF_TEXT_LINES = 2_000
const val DIFF_TEXT_CHARS = 200_000
/** A text's lines as they are compared, and whether the text went on past what is. */
data class TextLines(val lines: List<String>, val cut: Boolean)
/**
* The lines of [text], at most [mostLines] of them from at most its first [mostChars]
* characters: nothing past either bound is read, split or kept. The newline that ends the last
* line starts no empty one, and a line is compared without the `\r` before its newline, so a
* file whose line endings change is not a file whose every line changes.
*/
fun textLines(text: String, mostLines: Int = DIFF_TEXT_LINES, mostChars: Int = DIFF_TEXT_CHARS): TextLines {
val end = minOf(text.length, mostChars)
val lines = ArrayList<String>()
var from = 0
while (from < end && lines.size < mostLines) {
val newline = text.indexOf('\n', from).let { if (it < 0 || it >= end) -1 else it }
val to = if (newline < 0) end else newline
lines += text.substring(from, if (to > from && text[to - 1] == '\r') to - 1 else to)
from = if (newline < 0) end else newline + 1
}
return TextLines(lines, cut = from < text.length)
}
/** How [text]'s lines end, where it has any: `CRLF` when its first newline follows a `\r`, else `LF`; null for a text of one line. */
internal fun lineEnding(text: String): String? {
val newline = text.indexOf('\n')
return when {
newline < 0 -> null
newline > 0 && text[newline - 1] == '\r' -> "CRLF"
else -> "LF"
}
}
/**
* [old] turned into [new], line by line: what both begin and end with is the same without being
* compared, and the middle is the longest run of lines the two share -- or, where the middles
* are too long to compare on a phone, the old middle removed and the new one added.
*/
fun diffLines(old: List<String>, new: List<String>): List<DiffLine> {
var head = 0
while (head < old.size && head < new.size && old[head] == new[head]) head++
var tail = 0
while (tail < old.size - head && tail < new.size - head && old[old.size - 1 - tail] == new[new.size - 1 - tail]) tail++
val a = old.subList(head, old.size - tail)
val b = new.subList(head, new.size - tail)
val out = ArrayList<DiffLine>(old.size + b.size)
for (i in 0 until head) out += DiffLine(DiffSign.Same, old[i])
if (a.isEmpty() || b.isEmpty() || a.size.toLong() * b.size > DIFF_CELLS) {
a.forEach { out += DiffLine(DiffSign.Removed, it) }
b.forEach { out += DiffLine(DiffSign.Added, it) }
} else {
// shared[i][j]: how many lines the rest of a from i and the rest of b from j have in common, in order.
val shared = Array(a.size + 1) { IntArray(b.size + 1) }
for (i in a.size - 1 downTo 0) {
for (j in b.size - 1 downTo 0) {
shared[i][j] = if (a[i] == b[j]) shared[i + 1][j + 1] + 1 else maxOf(shared[i + 1][j], shared[i][j + 1])
}
}
var i = 0
var j = 0
while (i < a.size && j < b.size) {
when {
a[i] == b[j] -> {
out += DiffLine(DiffSign.Same, a[i])
i++
j++
}
shared[i + 1][j] >= shared[i][j + 1] -> out += DiffLine(DiffSign.Removed, a[i++])
else -> out += DiffLine(DiffSign.Added, b[j++])
}
}
while (i < a.size) out += DiffLine(DiffSign.Removed, a[i++])
while (j < b.size) out += DiffLine(DiffSign.Added, b[j++])
}
for (i in old.size - tail until old.size) out += DiffLine(DiffSign.Same, old[i])
return out
}
/** The changed lines of [lines] with [context] unchanged ones around each, and one [DiffSign.Gap] where lines between two changes are left out. */
fun hunks(lines: List<DiffLine>, context: Int = DIFF_CONTEXT): List<DiffLine> {
val keep = BooleanArray(lines.size)
lines.forEachIndexed { at, line ->
if (line.sign != DiffSign.Same) for (k in maxOf(0, at - context)..minOf(lines.size - 1, at + context)) keep[k] = true
}
val out = ArrayList<DiffLine>()
var left = false
lines.forEachIndexed { at, line ->
if (keep[at]) {
if (left && out.isNotEmpty()) out += DiffLine(DiffSign.Gap, "")
left = false
out += line
} else {
left = true
}
}
return out
}
/**
* This file's change for the card: a file that is made is all added, one that goes is all
* removed. Bounded before it starts ([textLines]) and while it runs ([diffLines]); it is still
* work for a background thread, never for a frame.
*/
fun FileDiff.view(): DiffView {
val before = oldText.orEmpty()
val after = if (deleted) "" else newText
val old = textLines(before)
val new = textLines(after)
val all = diffLines(old.lines, new.lines)
val from = lineEnding(before)
val to = lineEnding(after)
return DiffView(
hunks(all),
added = all.count { it.sign == DiffSign.Added },
removed = all.count { it.sign == DiffSign.Removed },
endings = if (from != null && to != null && from != to) from to to else null,
cut = old.cut || new.cut,
)
}
/** Whether an approval's item shows its `detail` (the call's arguments): always without diffs, and with them when none of them says anything. [views] is null while they are worked out. */
fun showsDetail(item: CardItem, views: List<DiffView>?): Boolean = item.diffs.isEmpty() || (views != null && views.none { it.says })
// Characters a person cannot see, or that would move or break a line: on a card where somebody
// decides, each is written as its code point.
private fun unseen(c: Char): Boolean = when (c.code) {
in 0x00..0x1F, in 0x7F..0x9F -> true
0x00AD, 0x061C, 0x180E, 0xFEFF -> true
in 0x200B..0x200F, in 0x2028..0x202E, in 0x2060..0x206F -> true
in 0xFFF9..0xFFFB -> true
else -> false
}
/**
* [text] with every invisible, direction-changing or line-breaking character written as
* `<U+202E>`: a bidi override, a zero-width space, a line separator, a control. A tab is four
* spaces. What is drawn reads as what is written.
*/
fun visibly(text: String): String {
if (text.none { it == '\t' || unseen(it) }) return text
return buildString(text.length + 16) {
for (c in text) {
when {
c == '\t' -> append(" ")
unseen(c) -> append("<U+").append(c.code.toString(16).uppercase().padStart(4, '0')).append('>')
else -> append(c)
}
}
}
}
@@ -365,3 +365,52 @@ class RangeReader(private val length: Long, private val block: Int = BLOCK, priv
const val BLOCK = 512 * 1024
}
}
/** How much of a file's beginning says what it is. */
const val SNIFF_BYTES = 16
private fun ByteArray.begins(at: Int, vararg bytes: Int): Boolean =
size >= at + bytes.size && bytes.indices.all { (this[at + it].toInt() and 0xFF) == bytes[it] }
private fun ByteArray.says(at: Int, word: String): Boolean = size >= at + word.length && word.indices.all { this[at + it].toInt() == word[it].code }
/**
* What a file is by its first bytes ([head], [SNIFF_BYTES] of them are enough), for the kinds a
* chat hands out: pictures, sound, video, a PDF, a 3D model, the archives. Null for anything
* else -- text has no mark, and a guess is worse than none.
*/
fun sniffType(head: ByteArray): String? = when {
head.begins(0, 0x89, 0x50, 0x4E, 0x47) -> "image/png"
head.begins(0, 0xFF, 0xD8, 0xFF) -> "image/jpeg"
head.says(0, "GIF8") -> "image/gif"
head.says(0, "RIFF") && head.says(8, "WEBP") -> "image/webp"
head.says(0, "RIFF") && head.says(8, "WAVE") -> "audio/wav"
head.says(0, "BM") -> "image/bmp"
head.says(0, "%PDF-") -> "application/pdf"
head.says(0, "OggS") -> "audio/ogg"
head.says(0, "fLaC") -> "audio/flac"
head.says(0, "ID3") || head.begins(0, 0xFF, 0xFB) || head.begins(0, 0xFF, 0xF3) -> "audio/mpeg"
head.says(4, "ftyp") -> "video/mp4"
head.begins(0, 0x1A, 0x45, 0xDF, 0xA3) -> "video/webm"
head.says(0, "glTF") -> "model/gltf-binary"
head.says(0, "PK\u0003\u0004") -> "application/zip"
head.begins(0, 0x1F, 0x8B) -> "application/gzip"
head.says(0, "7z") && head.begins(2, 0xBC, 0xAF) -> "application/x-7z-compressed"
else -> null
}
/**
* The type a copy is offered to another app as ("Open with"): what its bytes say, else what its
* name's extension says ([named], the platform's table), else anything. A zip is the one mark
* that many kinds of document carry inside, so there a known extension is the better word. The
* type the instance said is not asked: it is not the phone's own reading.
*/
fun openType(head: ByteArray, named: String?): String {
val sniffed = sniffType(head)
val byName = named?.ifBlank { null }
return when {
sniffed == null -> byName ?: "*/*"
sniffed == "application/zip" && byName != null -> byName
else -> sniffed
}
}
@@ -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
}
}
@@ -12,6 +12,11 @@ import kotlinx.serialization.Serializable
* `model3d`), and the file is in the person's Files at [path] -- a moment's truth, since they may
* move it; [nodeId] names it wherever it is. Its bytes are `GET /files/raw?node=`. [width],
* [height] and [seconds] are 0 where the server did not know them.
*
* With [shown] it is a file an agent put in front of the person (`contract/tool_media_shown.json`)
* and [kind] is what the file is, read from its bytes: `image`, `audio`, `video`, `pdf`,
* `model3d`, `archive`, `binary`, `text`, or a word this app does not know yet. Whatever it is,
* its card names it and leads to the file; what the phone can draw is drawn as well.
*/
@Serializable
data class GeneratedMedia(
@@ -25,16 +30,22 @@ data class GeneratedMedia(
val width: Int = 0,
val height: Int = 0,
val seconds: Double = 0.0,
/** An agent showed this file (the `show` tool on a file that is not text); it did not make it. */
val shown: Boolean = false,
) {
/** How the card shows it, by what was asked for: an unknown kind is its details, never a player. */
/** How the card shows it, by its kind: an unknown kind is its details, never a player. */
val view: MediaView
get() = when (kind) {
"image", "image_edit" -> MediaView.Picture
"video" -> MediaView.Video
"music" -> MediaView.Sound
"music", "audio" -> MediaView.Sound
"pdf" -> MediaView.Document
else -> MediaView.Details
}
/** The kinds this app has a word for; anything else is said as "File" when shown, never as nothing. */
val knownKind: Boolean get() = kind in KINDS
/** What to call it: its name, else the last name of its path. */
val title: String get() = name.ifBlank { FileKinds.name(path) }
@@ -43,10 +54,18 @@ data class GeneratedMedia(
/** The folder of the person's Files it was written to. */
val folder: String get() = FileKinds.parent(path)
companion object {
val KINDS = setOf("image", "image_edit", "video", "music", "audio", "model3d", "pdf", "archive", "binary", "text")
}
}
/** What a generated file's card is: a picture drawn, a player, or (a 3D model, anything unknown) the file's details. */
enum class MediaView { Picture, Video, Sound, Details }
/**
* What a file's card is: a picture drawn, a player, a document with pages the phone can lay out
* (a PDF), or -- a 3D model, an archive, anything unknown -- the file's details. Every one of
* them names the file and has the ways to it.
*/
enum class MediaView { Picture, Video, Sound, Document, Details }
/** The job a tool call started (`media_job`): [state] as it was when the call returned. */
@Serializable
@@ -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())
@@ -385,6 +391,12 @@ data class LinkedDevice(
@SerialName("max_mode") val maxMode: String = "",
/** Whether the device remembers the model last used in a directory (spec 3.9.0). */
@SerialName("directory_model") val directoryModel: Boolean = false,
/** Whether the device hands its files over the link at all (spec 3.11.0, `fs`). Parsed; no screen reads it yet. */
val files: Boolean = false,
/** False where its highest mode is plan: its files can be read and not changed. */
@SerialName("files_writable") val filesWritable: Boolean = false,
/** Whether the device lets files that run code (git's own, an agent's configuration) be changed from here. */
@SerialName("files_that_run_code") val filesThatRunCode: Boolean = false,
) {
/** What to call it: its name, else its host. */
val label: String get() = name.ifBlank { host.ifBlank { id } }
@@ -765,8 +777,40 @@ data class CardItem(
* action's own fields, as the server checked them. Carried out by `actions/ActionRunner`.
*/
val phone: JsonObject? = null,
/** An edit's changes, one per file (`contract/event_ask_edit.json`); empty on a card without them. */
val diffs: List<FileDiff> = emptyList(),
)
/**
* What an edit would do to one file, on its approval card: [oldText] is null for a file that is
* made, [deleted] marks one that goes. Both texts are a model's and a file's words: drawn as
* text by the app's own diff view (`api/Diff.kt`), never rendered.
*/
@Serializable
data class FileDiff(
val path: String = "",
@SerialName("old_text") val oldText: String? = null,
@SerialName("new_text") val newText: String = "",
val deleted: Boolean = false,
) {
/** A file that does not exist yet. */
val made: Boolean get() = oldText == null && !deleted
}
/**
* A person's two models for an editor (`GET /editor`, `contract/editor.json`): parsed so the
* shape is pinned; this app has no screen for them.
*/
@Serializable
data class EditorModels(val autocomplete: Autocomplete = Autocomplete(), val main: Main = Main()) {
/** [source]: `person`, `instance` or null with no model. [allowed]: the refs an administrator allows, null for any. */
@Serializable
data class Autocomplete(val model: String? = null, val source: String? = null, val allowed: List<String>? = null)
@Serializable
data class Main(val model: String? = null)
}
@Serializable
data class CardSubagent(val id: String = "", val name: String = "", val position: String = "")
@@ -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()
}
}
@@ -181,6 +181,9 @@ class AssistController(
private var screenText: String? = null
private var stt: Boolean? = null
/** The instance this assistant sheet speaks to (the default instance). */
private var targetId: String? = null
/** The account's own default model, as the instance said it: what "Instance default" means. */
private var accountDefault: String? = null
@@ -214,7 +217,7 @@ class AssistController(
scope.launch { speaker.playing.collect { on -> _state.update { it.copy(speaking = on) } } }
// Settings changed the assistant's model while this sheet lives: the next new chat has it.
scope.launch {
context.lembas.instances.prefs.map { it.assistantModel }.distinctUntilChanged().drop(1).collect { chosen ->
context.lembas.instances.prefs.map { it.forInstance(targetId).assistantModel }.distinctUntilChanged().drop(1).collect { chosen ->
ready()
newChatModel = assistantModelFor(chosen, accountDefault, _state.value.models) ?: chosen.ifBlank { null }
_state.update { if (it.chatId == null) it.copy(modelId = newChatModel, modelIsRef = false) else it }
@@ -234,34 +237,41 @@ class AssistController(
/** The choices kept in Settings, and which instance: nothing here leaves the phone. */
private suspend fun loadLocal() {
val store = context.lembas.instances
val instance = store.current()
val instance = store.default()
targetId = instance?.id
val prefs = store.prefs.first()
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),
last = prefs.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary }
?.let { id -> LastAssist(id, prefs.lastAssistTitle, prefs.lastAssistAt) },
last = own.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary }
?.let { id -> LastAssist(id, own.lastAssistTitle, own.lastAssistAt) },
)
}
// Until the instance has said what it has, the choice in Settings stands as it is: a
// question asked while the list could not be read still goes to the chosen model.
newChatModel = prefs.assistantModel.ifBlank { null }
newChatModel = own.assistantModel.ifBlank { null }
}
/** The instance's models and what it offers this account. */
private suspend fun loadRemote() {
val store = context.lembas.instances
val prefs = store.prefs.first()
val api = store.current()?.let { store.clientFor(it) } ?: return
val instance = store.default()?.takeUnless { it.signedOut } ?: return
targetId = instance.id
val api = store.clientFor(instance)
val own = prefs.forInstance(instance.id)
try {
val me = api.me()
val models = api.models()
stt = me.speechToText
accountDefault = me.defaultModel
val chosen = assistantModelFor(prefs.assistantModel, me.defaultModel, models)
val chosen = assistantModelFor(own.assistantModel, me.defaultModel, models)
newChatModel = chosen
_state.update {
it.copy(
@@ -338,7 +348,7 @@ class AssistController(
scope.launch {
try {
_state.update { it.copy(busy = true, error = null) }
val text = context.lembas.instances.client()?.transcribe(wav, media = mediaFor())?.text.orEmpty()
val text = context.lembas.instances.defaultClient()?.transcribe(wav, media = mediaFor())?.text.orEmpty()
_state.update { it.copy(busy = false) }
if (text.isNotBlank()) ask(text, spoken = true)
} catch (e: CancellationException) {
@@ -450,7 +460,7 @@ class AssistController(
* while the phone is locked: the recording stays on the phone until it is unlocked.
*/
private suspend fun writeDownAsSaid() {
val api = context.lembas.instances.client() ?: return
val api = context.lembas.instances.defaultClient() ?: return
var sent = 0f
while (scope.isActive) {
delay(PARTIAL_EVERY_MS)
@@ -552,7 +562,7 @@ class AssistController(
}
try {
_state.update { it.copy(busy = true) }
val text = context.lembas.instances.client()?.transcribe(wav, media = mediaFor())?.text.orEmpty()
val text = context.lembas.instances.defaultClient()?.transcribe(wav, media = mediaFor())?.text.orEmpty()
_state.update { it.copy(busy = false, heard = "") }
if (text.isNotBlank()) askOrStop(text) else endConversation()
} catch (e: Exception) {
@@ -614,7 +624,9 @@ class AssistController(
_state.update { it.copy(conversation = talking) }
try {
val store = context.lembas.instances
val api = store.client() ?: 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()
// A question typed the moment the sheet opened: the model is known first.
ready()
@@ -651,8 +663,10 @@ class AssistController(
replyId = made.reply?.id ?: return@launch
_state.update { it.copy(chatId = inChat) }
if (!prefs.assistantTemporary) {
store.savePrefs {
it.copy(lastAssistChat = inChat, lastAssistTitle = question.take(120), lastAssistAt = System.currentTimeMillis())
store.savePrefs { p ->
p.withInstance(targetId) {
it.copy(lastAssistChat = inChat, lastAssistTitle = question.take(120), lastAssistAt = System.currentTimeMillis())
}
}
}
}
@@ -697,7 +711,13 @@ class AssistController(
delay(TITLE_ASK_MS)
val title = runCatching { api.chat(chatId).chat.title }.getOrNull().orEmpty()
if (title.isNotBlank() && title != provisional) {
context.lembas.instances.savePrefs { if (it.lastAssistChat == chatId) it.copy(lastAssistTitle = title.take(120)) else it }
context.lembas.instances.savePrefs { p ->
if (p.forInstance(targetId).lastAssistChat == chatId) {
p.withInstance(targetId) { it.copy(lastAssistTitle = title.take(120)) }
} else {
p
}
}
_state.update { s -> s.copy(last = s.last?.let { l -> if (l.chatId == chatId) l.copy(title = title.take(120)) else l }) }
break
}
@@ -712,7 +732,7 @@ class AssistController(
scope.launch {
_state.update { it.copy(busy = true, error = null) }
try {
val api = context.lembas.instances.client() ?: return@launch
val api = context.lembas.instances.defaultClient() ?: return@launch
val detail = api.chat(last.chatId)
val question = detail.messages.lastOrNull { it.isUser }
val answer = detail.messages.lastOrNull { !it.isUser }
@@ -730,7 +750,9 @@ class AssistController(
} catch (e: Exception) {
// A chat deleted since is simply not offered again.
if (e is ApiException && e.status == 404) {
context.lembas.instances.savePrefs { it.copy(lastAssistChat = "", lastAssistTitle = "", lastAssistAt = 0) }
context.lembas.instances.savePrefs { p ->
p.withInstance(targetId) { it.copy(lastAssistChat = "", lastAssistTitle = "", lastAssistAt = 0) }
}
_state.update { it.copy(last = null) }
} else {
_state.update { it.copy(error = context.explain(e)) }
@@ -746,7 +768,7 @@ class AssistController(
val chat = _state.value.chatId ?: return
scope.launch {
try {
context.lembas.instances.client()?.answer(chat, card.id, answer)
context.lembas.instances.defaultClient()?.answer(chat, card.id, answer)
} catch (e: ApiException) {
// First answer wins: a 409 is somebody answering elsewhere already.
if (e.status != 409) _state.update { it.copy(error = context.explain(e)) }
@@ -779,9 +801,9 @@ class AssistController(
newChatModel = id
_state.update { it.copy(modelId = id, modelIsRef = false) }
scope.launch {
context.lembas.instances.savePrefs { it.copy(assistantModel = id) }
context.lembas.instances.savePrefs { p -> p.withInstance(targetId) { it.copy(assistantModel = id) } }
val chat = _state.value.chatId ?: return@launch
runCatching { context.lembas.instances.client()?.updateChat(chat, JsonObject(mapOf("model" to JsonPrimitive(id)))) }
runCatching { context.lembas.instances.defaultClient()?.updateChat(chat, JsonObject(mapOf("model" to JsonPrimitive(id)))) }
.onFailure { e -> _state.update { it.copy(error = context.explain(e)) } }
}
}
@@ -813,7 +835,7 @@ class AssistController(
// Never aloud over the lock screen: an answer is the account's.
if (words.isBlank() || locked()) return false
return try {
val api = context.lembas.instances.client() ?: return false
val api = context.lembas.instances.defaultClient() ?: return false
speaker.playToEnd(api.speech(words, mediaFor()).audio)
} catch (e: Exception) {
_state.update { it.copy(error = context.explain(e)) }
@@ -825,7 +847,10 @@ class AssistController(
* start activities differently. */
fun appIntent(): Intent = Intent(context, MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
.apply { _state.value.chatId?.let { putExtra(Notifications.EXTRA_CHAT, it) } }
.apply {
_state.value.chatId?.let { putExtra(Notifications.EXTRA_CHAT, it) }
targetId?.let { putExtra(Notifications.EXTRA_INSTANCE, it) }
}
fun close() {
following?.cancel()
@@ -28,6 +28,7 @@ import androidx.savedstate.SavedStateRegistryController
import androidx.savedstate.SavedStateRegistryOwner
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import eu.llembas.android.AppLanguage
import eu.llembas.android.SheetAtGate
import eu.llembas.android.lembas
import eu.llembas.android.ui.theme.LembasTheme
import eu.llembas.android.wake.AssistLink
@@ -79,6 +80,8 @@ class LembasAssistService : VoiceInteractionService() {
override fun onDestroy() {
AssistLink.destroyed(System.currentTimeMillis())
// With the service gone no sheet of it is up, whatever its session managed to say.
lembas.gate.sessionHidden()
super.onDestroy()
}
@@ -143,6 +146,7 @@ class LembasAssistSession(context: Context) :
/** Whether this session's sheet is up, as far as the wake word's pause is concerned. */
private var up = false
private val atGate = SheetAtGate(context.lembas.gate)
/** Over the lock screen: waiting for what is heard, to hand it to the sheet's activity. */
private var handing: Job? = null
@@ -201,6 +205,9 @@ class LembasAssistSession(context: Context) :
up = true
AssistPresence.shown()
}
// The sheet is the app in front: what it draws of the account (a reply's picture) may be
// asked for, unless the phone is locked. Said each time; the gate keeps it as one.
atGate.shown()
AssistLink.sheetShown(SystemClock.elapsedRealtime())
// One sheet, never two: a sheet the wake word opened as a screen of the app, because
// this one was slow to come, goes now that this one is here.
@@ -230,6 +237,7 @@ class LembasAssistSession(context: Context) :
up = false
AssistPresence.hidden()
}
atGate.gone()
controller.close()
scope.cancel()
scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
@@ -240,6 +248,8 @@ class LembasAssistSession(context: Context) :
override fun onDestroy() {
super.onDestroy()
// A session torn down without being hidden must not leave the gate open behind it.
atGate.gone()
controller.close()
scope.cancel()
registry.currentState = Lifecycle.State.DESTROYED
@@ -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
@@ -65,8 +75,76 @@ object TokenCipher {
private val Context.store by preferencesDataStore(name = "instances")
private val INSTANCES = stringPreferencesKey("instances")
private val ACTIVE = stringPreferencesKey("active")
private val DEFAULT = stringPreferencesKey("default")
private val PREFS = stringPreferencesKey("prefs")
/** Choices kept per instance (assistant model, last assistant chat, account language). */
@Serializable
data class PerInstancePrefs(
val assistantModel: String = "",
val lastAssistChat: String = "",
val lastAssistTitle: String = "",
val lastAssistAt: Long = 0,
val accountLanguage: String = "",
)
/**
* Pure selection and mutation rules for [InstanceStore]: kept free of Android types so unit
* tests exercise default fallback, multi-account ids and removal directly.
*/
object InstanceLogic {
fun pickDefault(instances: List<Instance>, defaultId: String?): Instance? = instances.firstOrNull { it.id == defaultId } ?: instances.firstOrNull()
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> {
val next = instances.filter { it.id != added.id } + added
val keptDefault = next.firstOrNull { it.id == currentDefault }?.id ?: added.id
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?> {
val remaining = instances.filter { it.id != removedId }
val nextDefault = remaining.firstOrNull { it.id == currentDefault }?.id
?: remaining.firstOrNull { it.id == currentActive }?.id
?: remaining.firstOrNull()?.id
val nextActive = remaining.firstOrNull { it.id == currentActive }?.id
?: nextDefault
return Triple(remaining, nextActive, nextDefault)
}
}
/**
* What the person chose in Settings, for this phone. [language]: "" the account's language (the
* default), "system" the phone's, or a language's code -- see [eu.llembas.android.AppLanguage].
@@ -115,7 +193,34 @@ data class Prefs(
val updateCheckedAt: Long = 0,
/** The last version a notification announced, so it is announced once. */
val updateNotified: String = "",
/** Per-instance choices, keyed by [Instance.id]. */
val perInstance: Map<String, PerInstancePrefs> = emptyMap(),
) {
fun forInstance(id: String?): PerInstancePrefs = id?.let { perInstance[it] } ?: PerInstancePrefs(
assistantModel = assistantModel,
lastAssistChat = lastAssistChat,
lastAssistTitle = lastAssistTitle,
lastAssistAt = lastAssistAt,
accountLanguage = accountLanguage,
)
fun withInstance(id: String?, change: (PerInstancePrefs) -> PerInstancePrefs): Prefs {
val updated = change(forInstance(id))
return if (id == null) {
copy(
assistantModel = updated.assistantModel,
lastAssistChat = updated.lastAssistChat,
lastAssistTitle = updated.lastAssistTitle,
lastAssistAt = updated.lastAssistAt,
accountLanguage = updated.accountLanguage,
)
} else {
copy(perInstance = perInstance + (id to updated))
}
}
fun withoutInstance(id: String): Prefs = if (id in perInstance) copy(perInstance = perInstance - id) else this
companion object {
const val VOICE_LEMBAS = "lembas"
const val VOICE_PHONE = "phone"
@@ -129,9 +234,14 @@ class InstanceStore(private val context: Context) {
prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
}
val defaultInstance: Flow<Instance?> = context.store.data.map { prefs ->
val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
InstanceLogic.pickDefault(all, prefs[DEFAULT])
}
val active: Flow<Instance?> = context.store.data.map { prefs ->
val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
all.firstOrNull { it.id == prefs[ACTIVE] } ?: all.firstOrNull()
InstanceLogic.pickActive(all, prefs[ACTIVE], prefs[DEFAULT])
}
val prefs: Flow<Prefs> = context.store.data.map { p ->
@@ -140,35 +250,77 @@ class InstanceStore(private val context: Context) {
suspend fun current(): Instance? = active.first()
suspend fun client(): ApiClient? = current()?.let { clientFor(it) }
suspend fun default(): Instance? = defaultInstance.first()
/** 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()?.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 { LembasJson.decodeFromString(listSerializer, it) } ?: emptyList()
prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, all.filter { it.id != instance.id } + instance)
prefs[ACTIVE] = instance.id
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
}
}
/**
* 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)
}
return instance
}
suspend fun use(id: String) {
context.store.edit { it[ACTIVE] = id }
}
suspend fun setDefault(id: String) {
context.store.edit { prefs ->
val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
if (all.any { it.id == id }) prefs[DEFAULT] = id
}
}
/** On a cold start with no notification target, switch active back to the default instance. */
suspend fun resetToDefault() {
context.store.edit { prefs ->
val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
InstanceLogic.pickDefault(all, prefs[DEFAULT])?.let { prefs[ACTIVE] = it.id }
}
}
suspend fun remove(id: String) {
context.store.edit { prefs ->
val all = prefs[INSTANCES]?.let { LembasJson.decodeFromString(listSerializer, it) } ?: emptyList()
prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, all.filter { it.id != id })
if (prefs[ACTIVE] == id) prefs.remove(ACTIVE)
val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
val (remaining, nextActive, nextDefault) = InstanceLogic.afterRemove(all, id, prefs[ACTIVE], prefs[DEFAULT])
prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, remaining)
if (nextActive != null) prefs[ACTIVE] = nextActive else prefs.remove(ACTIVE)
if (nextDefault != null) prefs[DEFAULT] = nextDefault else prefs.remove(DEFAULT)
prefs[PREFS]?.let { raw ->
runCatching { LembasJson.decodeFromString(Prefs.serializer(), raw) }.getOrNull()?.let { current ->
prefs[PREFS] = LembasJson.encodeToString(Prefs.serializer(), current.withoutInstance(id))
}
}
}
}
@@ -91,12 +91,14 @@ class ShareActivity :
}
lifecycleScope.launch {
val store = lembas.instances
val instance = store.default()
val prefs = store.prefs.first()
val own = prefs.forInstance(instance?.id)
state.update {
it.copy(
signedIn = store.current() != null,
last = prefs.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary }
?.let { id -> LastAssist(id, prefs.lastAssistTitle, prefs.lastAssistAt) },
signedIn = instance != null,
last = own.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary }
?.let { id -> LastAssist(id, own.lastAssistTitle, own.lastAssistAt) },
)
}
}
@@ -142,7 +144,7 @@ class ShareActivity :
lifecycleScope.launch {
try {
turn()
val home = lembas.instances.client()?.files("/")?.path ?: return@launch
val home = lembas.instances.defaultClient()?.files("/")?.path ?: return@launch
state.update { it.copy(folder = it.folder ?: home) }
} catch (e: CancellationException) {
throw e
@@ -167,7 +169,7 @@ class ShareActivity :
state.update { it.copy(sending = true, error = null) }
lifecycleScope.launch {
try {
val api = lembas.instances.client() ?: run {
val api = lembas.instances.defaultClient() ?: run {
startActivity(Intent(this@ShareActivity, MainActivity::class.java))
finish()
return@launch
@@ -199,11 +201,12 @@ class ShareActivity :
lifecycleScope.launch {
try {
val store = lembas.instances
val api = store.client() ?: run {
val instance = store.default() ?: run {
startActivity(Intent(this@ShareActivity, MainActivity::class.java))
finish()
return@launch
}
val api = store.clientFor(instance)
val now = state.value
val into = if (toLast) now.last?.chatId else null
// What a first try already uploaded for this chat is not uploaded again.
@@ -223,23 +226,26 @@ class ShareActivity :
val prefs = store.prefs.first()
// The assistant's model while the instance still has it; a model that is
// gone is not asked for (the instance's default answers instead).
val chosen = prefs.assistantModel
val chosen = prefs.forInstance(instance.id).assistantModel
val gone = chosen.isNotBlank() && runCatching { api.models() }.getOrNull()?.let { it.named(chosen) == null } == true
turn()
val made = api.createChat(message, sent, model = chosen.takeIf { it.isNotBlank() && !gone })
store.savePrefs {
it.copy(
lastAssistChat = made.chat.id,
lastAssistTitle = ask.ifBlank { now.text.ifBlank { now.files.firstOrNull()?.name.orEmpty() } }.take(120),
lastAssistAt = System.currentTimeMillis(),
)
store.savePrefs { p ->
p.withInstance(instance.id) {
it.copy(
lastAssistChat = made.chat.id,
lastAssistTitle = ask.ifBlank { now.text.ifBlank { now.files.firstOrNull()?.name.orEmpty() } }.take(120),
lastAssistAt = System.currentTimeMillis(),
)
}
}
made.chat.id
}
startActivity(
Intent(this@ShareActivity, MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
.putExtra(Notifications.EXTRA_CHAT, chatId),
.putExtra(Notifications.EXTRA_CHAT, chatId)
.putExtra(Notifications.EXTRA_INSTANCE, instance.id),
)
finish()
} catch (e: CancellationException) {
@@ -247,7 +253,10 @@ class ShareActivity :
} catch (e: Exception) {
// The last chat deleted since: it is not offered again.
if (e is ApiException && e.status == 404 && toLast) {
lembas.instances.savePrefs { it.copy(lastAssistChat = "", lastAssistTitle = "", lastAssistAt = 0) }
val id = lembas.instances.default()?.id
lembas.instances.savePrefs { p ->
p.withInstance(id) { it.copy(lastAssistChat = "", lastAssistTitle = "", lastAssistAt = 0) }
}
state.update { it.copy(last = null) }
}
state.update { it.copy(sending = false, error = if (e is SharedRefused) filesSay(e) else explain(e)) }
@@ -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
}
@@ -37,6 +37,7 @@ import eu.llembas.android.api.CardAnswer
import eu.llembas.android.api.CardItem
import eu.llembas.android.api.LembasJson
import eu.llembas.android.api.Plan
import eu.llembas.android.api.showsDetail
import eu.llembas.android.ui.theme.LocalPalette
/** The sentinel the web card's "Something else" row submits (`interaction.OTHER`). */
@@ -73,6 +74,7 @@ private fun Approval(card: Card, onAnswer: (CardAnswer) -> Unit) {
var refusing by remember { mutableStateOf(false) }
Text(stringResource(R.string.card_approval), style = MaterialTheme.typography.titleMedium)
card.items.forEach { item ->
val views = diffViews(item.diffs)
// A subagent asks, not the chat's own turn: said first, as the page says it.
val subagent = item.subagent
if (subagent != null) {
@@ -100,9 +102,12 @@ private fun Approval(card: Card, onAnswer: (CardAnswer) -> Unit) {
if (approvalTexts(listOf(item), edits).isNotEmpty()) {
Text(stringResource(R.string.card_edit_runs), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
}
} else if (item.detail.isNotBlank()) {
} else if (item.detail.isNotBlank() && showsDetail(item, views)) {
Text(item.detail, fontFamily = FontFamily.Monospace)
}
// An edit says what it would change: the diff stands where the call's arguments would,
// as text. Diffs that say nothing (the same text twice) leave the arguments in view.
if (item.diffs.isNotEmpty()) CardDiffs(item.diffs, views)
if (item.reason.isNotBlank()) Text(item.reason, style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
}
// A corrected command goes with an allow, never with a refusal, and only when it was corrected.
@@ -111,9 +111,11 @@ import eu.llembas.android.ui.files.TransferHost
import eu.llembas.android.ui.files.TransferViewModel
import eu.llembas.android.ui.files.rememberSaver
import eu.llembas.android.ui.theme.LocalPalette
import eu.llembas.android.ui.viewer.DocumentDialog
import eu.llembas.android.ui.viewer.FileViewer
import eu.llembas.android.ui.viewer.PlayerDialog
import eu.llembas.android.ui.viewer.Playing
import eu.llembas.android.ui.viewer.Reading
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.launch
@@ -175,6 +177,7 @@ fun ChatScreen(
val transfers: TransferViewModel = viewModel(key = "chat-transfers")
val saveTo = rememberSaver(transfers)
var playing by remember { mutableStateOf<Playing?>(null) }
var reading by remember { mutableStateOf<Reading?>(null) }
val media = remember(model, transfers) {
object : MediaActions {
override fun play(media: GeneratedMedia) {
@@ -185,6 +188,10 @@ fun ChatScreen(
playing = Playing(Raw.Attached(attachment.id), attachment.name, attachment.size, video = attachment.kind == "video")
}
override fun view(media: GeneratedMedia) {
reading = Reading(media.raw, media.title, media.size)
}
// Where the file is now, by its id: it may have been renamed or moved since it was made.
override fun openInFiles(media: GeneratedMedia) = model.whereIs(media, onFiles)
@@ -192,7 +199,7 @@ fun ChatScreen(
override fun share(media: GeneratedMedia) = transfers.share(media.raw, media.title, media.mime)
override fun openWith(media: GeneratedMedia) = transfers.openWith(media.raw, media.title, media.mime)
override fun openWith(media: GeneratedMedia) = transfers.openWith(media.raw, media.title)
override fun cancel(job: MediaJob) = model.cancelJob(job)
}
@@ -238,6 +245,7 @@ fun ChatScreen(
state.chat?.id?.let { id -> FileViewer(id, file, onClose = { showing = null }) }
}
playing?.let { PlayerDialog(it, onClose = { playing = null }, gone = stringResource(R.string.media_gone)) }
reading?.let { DocumentDialog(it, onClose = { reading = null }, gone = stringResource(R.string.media_gone)) }
TransferHost(transfers)
}
@@ -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.
@@ -0,0 +1,187 @@
package eu.llembas.android.ui.chat
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import eu.llembas.android.R
import eu.llembas.android.api.DiffLine
import eu.llembas.android.api.DiffSign
import eu.llembas.android.api.DiffView
import eu.llembas.android.api.FileDiff
import eu.llembas.android.api.view
import eu.llembas.android.api.visibly
import eu.llembas.android.ui.theme.LocalPalette
import eu.llembas.android.ui.theme.Palette
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
// An edit's diff on its approval card: per file its path, how many lines come and go, and the
// changed lines as text -- a sign before each and the theme's colour behind it, in one width of
// letter. The lines scroll sideways in a box of their own, so the card never does. Both texts
// are a model's and a file's words: one plain Text draws them, and nothing in them is rendered.
/** The most of one line that is drawn: a line of a megabyte is still one line of the card. */
internal const val DIFF_LINE_MOST = 400
private val DiffShape = RoundedCornerShape(12.dp)
/**
* A line as the card writes it: its sign, then its text cut at [DIFF_LINE_MOST], with whatever
* a person could not see in it -- a direction override, a zero-width space, a line separator --
* written as its code point ([visibly]).
*/
internal fun diffRow(line: DiffLine): String {
val sign = when (line.sign) {
DiffSign.Added -> "+ "
DiffSign.Removed -> "- "
DiffSign.Same -> " "
DiffSign.Gap -> return "⋯"
}
val long = line.text.length > DIFF_LINE_MOST
return sign + visibly(if (long) line.text.take(DIFF_LINE_MOST) else line.text) + if (long) "…" else ""
}
private fun diffText(lines: List<DiffLine>, palette: Palette): AnnotatedString = buildAnnotatedString {
lines.forEachIndexed { at, line ->
val style = when (line.sign) {
DiffSign.Added -> SpanStyle(color = palette.success, background = palette.successSoft)
DiffSign.Removed -> SpanStyle(color = palette.danger, background = palette.dangerSoft)
DiffSign.Same -> SpanStyle(color = palette.ink)
DiffSign.Gap -> SpanStyle(color = palette.inkFaint)
}
withStyle(style) { append(diffRow(line)) }
if (at < lines.lastIndex) append('\n')
}
}
/**
* The diffs of an item, worked out: null until they are. Off the main thread -- two texts of a
* megabyte are not compared inside a frame -- and one file after another, so fifty files hold
* one comparison's memory at a time. A screenshot has no later frame: there it is done at once.
*/
@Composable
fun diffViews(diffs: List<FileDiff>): List<DiffView>? {
if (diffs.isEmpty()) return emptyList()
if (LocalInspectionMode.current) return remember(diffs) { diffs.map { it.view() } }
val views by produceState<List<DiffView>?>(null, diffs) {
value = withContext(Dispatchers.Default) {
diffs.map {
ensureActive()
it.view()
}
}
}
return views
}
/** The diffs of one item of an approval card, a block per file; [views] as [diffViews] gave them. */
@Composable
fun CardDiffs(diffs: List<FileDiff>, views: List<DiffView>?, modifier: Modifier = Modifier) {
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
diffs.forEachIndexed { at, diff -> key(at, diff.path) { FileDiffBlock(diff, views?.getOrNull(at)) } }
}
}
/**
* One file's change. The path gives (it wraps) and the two counts keep their width. The lines
* are folded to the first few; "Show all" opens them, up to what a card lays out. Until [view]
* is worked out the block is its path alone.
*/
@Composable
private fun FileDiffBlock(diff: FileDiff, view: DiffView?) {
val palette = LocalPalette.current
var open by rememberSaveable(diff.path) { mutableStateOf(false) }
val path = remember(diff.path) { visibly(diff.path) }
Column(Modifier.fillMaxWidth().clip(DiffShape).background(palette.codeBg).border(1.dp, palette.codeBorder, DiffShape)) {
Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text(path, style = MaterialTheme.typography.bodySmall, fontFamily = FontFamily.Monospace, color = palette.ink)
val state = when {
diff.deleted -> stringResource(R.string.diff_deleted)
diff.made -> stringResource(R.string.files_new_file)
else -> null
}
if (state != null) Text(state, style = MaterialTheme.typography.labelSmall, color = palette.inkMuted)
}
if (view != null) {
Spacer(Modifier.width(12.dp))
val counts = stringResource(R.string.diff_counts, view.added.toString(), view.removed.toString())
Row(Modifier.clearAndSetSemantics { contentDescription = counts }, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text("+${view.added}", style = MaterialTheme.typography.labelMedium, fontFamily = FontFamily.Monospace, color = palette.success)
Text("−${view.removed}", style = MaterialTheme.typography.labelMedium, fontFamily = FontFamily.Monospace, color = palette.danger)
}
}
}
if (view != null) {
// Said once, where every line would otherwise go and come with the same words.
view.endings?.let { (from, to) -> DiffNote(stringResource(R.string.diff_endings, from, to)) }
val lines = view.shown(open)
if (lines.isNotEmpty()) {
val text = remember(lines, palette) { diffText(lines, palette) }
Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())) {
Text(
text,
style = MaterialTheme.typography.bodySmall,
fontFamily = FontFamily.Monospace,
softWrap = false,
modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp),
)
}
}
if (open && view.beyond > 0) DiffNote(stringResource(R.string.diff_more, view.beyond.toString()))
if (view.cut) DiffNote(stringResource(R.string.diff_cut))
if (view.folds) {
TextButton(onClick = { open = !open }, modifier = Modifier.heightIn(min = 48.dp).padding(horizontal = 4.dp)) {
Text(if (open) stringResource(R.string.diff_show_less) else stringResource(R.string.diff_show_all, view.lines.size.toString()))
}
}
}
}
}
/** A sentence of the block's own, under its lines. */
@Composable
private fun DiffNote(text: String) {
Text(
text,
style = MaterialTheme.typography.bodySmall,
color = LocalPalette.current.inkMuted,
modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp),
)
}
@@ -75,6 +75,8 @@ private object Pictures {
cache.get(key)?.let { return it }
if (key in failed) return null
val api = context.lembas.instances.client() ?: return null
// A picture that comes into view behind the lock, or with the app not in front, waits there.
context.lembas.gate.passLater()
val bytes = try {
fetch(api).takeIf { it.size <= MAX_BYTES }
} catch (e: CancellationException) {
@@ -15,14 +15,18 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
import androidx.compose.material.icons.automirrored.filled.OpenInNew
import androidx.compose.material.icons.filled.Description
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material.icons.filled.FolderOpen
import androidx.compose.material.icons.filled.FolderZip
import androidx.compose.material.icons.filled.HourglassEmpty
import androidx.compose.material.icons.filled.Image
import androidx.compose.material.icons.filled.Movie
import androidx.compose.material.icons.filled.MusicNote
import androidx.compose.material.icons.filled.PictureAsPdf
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.ViewInAr
@@ -59,8 +63,9 @@ import eu.llembas.android.ui.theme.LocalPalette
import eu.llembas.android.ui.viewer.playTime
import kotlinx.coroutines.delay
// What a model made, in the reply: a card for a file (a picture drawn, a video or a track with
// Play, a 3D model or anything else as what it is) and a card for a generation still under way.
// What a model made or an agent showed, in the reply: a card for a file (a picture drawn, a video
// or a track with Play, a PDF with Open, a 3D model or anything else as what it is) and a card for
// a generation still under way.
// The file is one of the person's Files, so each card leads there, and out of the app the ways
// a file leaves it: saved where the person chooses, shared, or opened with another app. The
// cards are drawn only where a chat provides [LocalChatMedia] -- the chat's own screen, which
@@ -74,6 +79,9 @@ interface MediaActions {
/** Play sound or video the person attached. */
fun play(attachment: Attachment) {}
/** Lay a document's pages out over the chat (a PDF). */
fun view(media: GeneratedMedia) {}
/** The folder of the person's Files the file is in. */
fun openInFiles(media: GeneratedMedia) {}
@@ -96,21 +104,39 @@ val LocalChatMedia = compositionLocalOf<ChatMedia?> { null }
private val CardShape = RoundedCornerShape(16.dp)
/** The word for what was asked for: a picture, a video, music, a 3D model; the server's own word for anything else. */
@Composable
internal fun mediaKind(kind: String): String = when (kind) {
"image", "image_edit" -> stringResource(R.string.media_image)
"video" -> stringResource(R.string.media_video)
"music" -> stringResource(R.string.media_music)
"model3d" -> stringResource(R.string.media_model)
else -> kind
/** The string for a kind this app has a word for; null for any other. */
internal fun mediaKindWord(kind: String): Int? = when (kind) {
"image", "image_edit" -> R.string.media_image
"video" -> R.string.media_video
"music" -> R.string.media_music
"audio" -> R.string.media_audio
"model3d" -> R.string.media_model
"pdf" -> R.string.media_pdf
"archive" -> R.string.media_archive
"text" -> R.string.media_text
"binary" -> R.string.media_binary
else -> null
}
private fun mediaIcon(kind: String): ImageVector = when (kind) {
/**
* The word for what a file is: a picture, a video, music, audio, a 3D model, a PDF, an archive,
* a text file, a file. A kind this app does not know is the server's own word for a generated
* file and "File" for one an agent showed ([shown]): a shown file always says what it is.
*/
@Composable
internal fun mediaKind(kind: String, shown: Boolean = false): String =
mediaKindWord(kind)?.let { stringResource(it) } ?: if (shown) stringResource(R.string.media_binary) else kind
/** The mark of a kind; `binary` and a kind this app does not know are a file. */
internal fun mediaIcon(kind: String): ImageVector = when (kind) {
"image", "image_edit" -> Icons.Filled.Image
"video" -> Icons.Filled.Movie
"music" -> Icons.Filled.MusicNote
else -> Icons.Filled.ViewInAr
"music", "audio" -> Icons.Filled.MusicNote
"model3d" -> Icons.Filled.ViewInAr
"pdf" -> Icons.Filled.PictureAsPdf
"archive" -> Icons.Filled.FolderZip
"text" -> Icons.Filled.Description
else -> Icons.AutoMirrored.Filled.InsertDriveFile
}
/** What is known of a file, in one line: what it is, how long, how large, its size in pixels. */
@@ -118,7 +144,7 @@ private fun mediaIcon(kind: String): ImageVector = when (kind) {
internal fun mediaFacts(media: GeneratedMedia): String {
val context = LocalContext.current
return listOfNotNull(
mediaKind(media.kind).ifBlank { null },
mediaKind(media.kind, media.shown).ifBlank { null },
media.seconds.takeIf { it > 0 }?.let { playTime((it * 1000).toInt()) },
media.size.takeIf { it > 0 }?.let { Formatter.formatShortFileSize(context, it) },
if (media.width > 0 && media.height > 0) "${media.width} × ${media.height}" else null,
@@ -126,45 +152,33 @@ internal fun mediaFacts(media: GeneratedMedia): String {
}
/**
* A file a tool call made. A picture is drawn -- from its attachment where the call has one
* ([image]), else from the file itself; a video or a track is its name with Play (48 dp), which
* opens the player over the chat; a 3D model and anything this app does not know is what it is.
* Under each, four buttons of one size: Open in Files, Download, Share, Open with.
* A file a tool call made, or one an agent showed. A picture is drawn -- from its attachment
* where the call has one ([image]), else from the file itself; a video or a track is its name
* with Play (48 dp), which opens the player over the chat; a PDF is its name with Open, which
* lays its pages out over the chat; a 3D model, an archive and anything this app does not know
* is its name and what it is. Under each, four buttons of one size: Open in Files, Download,
* Share, Open with.
*
* A file that was shown is always named: its picture has its name and facts under it, so one
* that cannot be drawn on this phone (too large, a format the phone does not read) is still a
* name, a kind in words and the ways to the file.
*/
@Composable
fun MediaCard(media: GeneratedMedia, image: GeneratedImage?, actions: MediaActions, modifier: Modifier = Modifier) {
val palette = LocalPalette.current
Column(modifier.widthIn(max = 480.dp).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) {
when (media.view) {
MediaView.Picture -> if (image != null && image.id.isNotBlank()) GeneratedPicture(image) else GeneratedPicture(media)
MediaView.Video, MediaView.Sound, MediaView.Details -> Row(
Modifier.fillMaxWidth().border(1.dp, palette.border, CardShape).padding(horizontal = 12.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
if (media.view == MediaView.Details) {
Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) {
Icon(mediaIcon(media.kind), contentDescription = null, tint = palette.inkMuted)
}
} else {
FilledIconButton(
onClick = { actions.play(media) },
colors = IconButtonDefaults.filledIconButtonColors(containerColor = palette.accent, contentColor = palette.accentInk),
modifier = Modifier.size(48.dp),
) { Icon(Icons.Filled.PlayArrow, contentDescription = stringResource(R.string.play)) }
}
Spacer(Modifier.width(12.dp))
Column(Modifier.weight(1f)) {
Text(media.title, style = MaterialTheme.typography.bodyLarge, color = palette.ink, maxLines = 1, overflow = TextOverflow.MiddleEllipsis)
Text(
mediaFacts(media),
style = MaterialTheme.typography.bodySmall,
color = palette.inkMuted,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
MediaView.Picture -> {
// A result that names no node has no picture to ask for: its row stands in, so the card is never empty.
val drawable = (image != null && image.id.isNotBlank()) || media.nodeId.isNotBlank()
if (image != null && image.id.isNotBlank()) GeneratedPicture(image) else GeneratedPicture(media)
if (media.shown && drawable) {
Column(Modifier.fillMaxWidth().padding(horizontal = 4.dp)) { MediaWords(media) }
} else if (!drawable) {
MediaRow(media, actions)
}
}
MediaView.Video, MediaView.Sound, MediaView.Document, MediaView.Details -> MediaRow(media, actions)
}
// Four buttons of 48 dp: nothing here depends on how long a word is in any language.
Row {
@@ -176,6 +190,44 @@ fun MediaCard(media: GeneratedMedia, image: GeneratedImage?, actions: MediaActio
}
}
/** The file's name on one line (its middle gives) and what is known of it on the next. */
@Composable
private fun MediaWords(media: GeneratedMedia) {
val palette = LocalPalette.current
Text(media.title, style = MaterialTheme.typography.bodyLarge, color = palette.ink, maxLines = 1, overflow = TextOverflow.MiddleEllipsis)
Text(mediaFacts(media), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
/**
* A file as a row: a mark of 48 dp -- Play for sound and video, Open for a PDF, else the kind's
* icon -- and the file's words, which give.
*/
@Composable
private fun MediaRow(media: GeneratedMedia, actions: MediaActions) {
val palette = LocalPalette.current
Row(
Modifier.fillMaxWidth().border(1.dp, palette.border, CardShape).padding(horizontal = 12.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
val filled = IconButtonDefaults.filledIconButtonColors(containerColor = palette.accent, contentColor = palette.accentInk)
when (media.view) {
MediaView.Video, MediaView.Sound -> FilledIconButton(onClick = { actions.play(media) }, colors = filled, modifier = Modifier.size(48.dp)) {
Icon(Icons.Filled.PlayArrow, contentDescription = stringResource(R.string.play))
}
MediaView.Document -> FilledIconButton(onClick = { actions.view(media) }, colors = filled, modifier = Modifier.size(48.dp)) {
Icon(mediaIcon(media.kind), contentDescription = stringResource(R.string.viewer_open))
}
MediaView.Picture, MediaView.Details -> Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) {
Icon(mediaIcon(media.kind), contentDescription = null, tint = palette.inkMuted)
}
}
Spacer(Modifier.width(12.dp))
Column(Modifier.weight(1f)) { MediaWords(media) }
}
}
@Composable
private fun CardButton(icon: ImageVector, label: Int, onClick: () -> Unit) {
IconButton(onClick = onClick) { Icon(icon, contentDescription = stringResource(label), tint = LocalPalette.current.inkMuted) }
@@ -439,7 +439,7 @@ fun FilesScreen(onBack: () -> Unit, start: String? = null, model: FilesViewModel
model.clearSelection()
}
override fun openWith(entry: FileEntry) = transfers.openWith(entry.path, entry.name, entry.mime)
override fun openWith(entry: FileEntry) = transfers.openWith(entry.path, entry.name)
}
}
@@ -91,13 +91,14 @@ class TransferViewModel(app: Application) : AndroidViewModel(app) {
_state.update { it.copy(notice = app.getString(R.string.files_downloaded)) }
}
fun openWith(path: String, name: String, mime: String) = openWith(Raw.Path(path), name, mime)
fun openWith(path: String, name: String) = openWith(Raw.Path(path), name)
fun openWith(what: Raw, name: String, mime: String) = start { api, progress ->
/** A copy for another app to open; its type is read from the copy ([Handover.view]), not taken from the instance. */
fun openWith(what: Raw, name: String) = start { api, progress ->
FileCache.sweepShared(app)
turn()
val copy = api.copyInto(api.raw(what), FileCache.shared(app, name), progress = progress)
_state.update { it.copy(launch = Handover.view(app, copy, mime)) }
_state.update { it.copy(launch = Handover.view(app, copy)) }
}
/** One thing that is not named by a path (a generated file by its id), shared as itself. */
@@ -8,12 +8,15 @@ import android.content.Intent
import android.net.Uri
import android.provider.DocumentsContract
import android.provider.OpenableColumns
import android.webkit.MimeTypeMap
import androidx.activity.result.contract.ActivityResultContract
import androidx.core.content.FileProvider
import eu.llembas.android.api.ApiClient
import eu.llembas.android.api.ApiException
import eu.llembas.android.api.FileKinds
import eu.llembas.android.api.FileListing
import eu.llembas.android.api.SNIFF_BYTES
import eu.llembas.android.api.openType
import eu.llembas.android.share.SharedSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@@ -185,9 +188,24 @@ suspend fun ApiClient.copyInto(request: okhttp3.Request, file: File, most: Long
/** Hand [files] (cache copies) to another app: "Open with" for one, Share for one or several. Read-only, for this one grant. */
object Handover {
fun view(context: Context, file: File, mime: String): Intent {
/**
* "Open with" for the copy [file]. What it is offered as is read from the copy itself
* ([openType]: its first bytes, else its name's extension) -- never the type the instance
* said, which for a file an agent showed is one more thing a model had a hand in.
*/
fun view(context: Context, file: File): Intent {
val uri = FileCache.uri(context, file)
val intent = Intent(Intent.ACTION_VIEW).setDataAndType(uri, mime.ifBlank { "*/*" }).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
// A copy that cannot be read again is offered by its name alone.
val head = try {
file.inputStream().use { stream ->
val bytes = ByteArray(SNIFF_BYTES)
bytes.copyOf(stream.read(bytes).coerceAtLeast(0))
}
} catch (e: IOException) {
ByteArray(0)
}
val named = MimeTypeMap.getSingleton().getMimeTypeFromExtension(file.extension.lowercase())
val intent = Intent(Intent.ACTION_VIEW).setDataAndType(uri, openType(head, named)).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
return Intent.createChooser(intent, null)
}
@@ -1,3 +1,5 @@
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
package eu.llembas.android.ui.home
import android.app.Application
@@ -7,6 +9,7 @@ import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
@@ -22,7 +25,9 @@ import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.DriveFileMove
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Archive
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.CreateNewFolder
import androidx.compose.material.icons.filled.Delete
@@ -39,6 +44,7 @@ import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Summarize
import androidx.compose.material.icons.filled.Terminal
import androidx.compose.material.icons.filled.UnfoldMore
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
@@ -46,6 +52,7 @@ import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
@@ -53,6 +60,7 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
@@ -82,10 +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
@@ -191,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. */
@@ -205,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
@@ -490,6 +498,8 @@ interface DrawerActions {
fun archived() {}
fun memory() {}
fun settings() {}
fun useInstance(instance: Instance) {}
fun addInstance() {}
fun more() {}
fun retry() {}
fun search(query: String) {}
@@ -511,9 +521,13 @@ fun DrawerContent(
today: LocalDate = LocalDate.now(),
zone: ZoneId = ZoneId.systemDefault(),
initialQuery: String = "",
instances: List<Instance> = emptyList(),
activeInstance: Instance? = null,
defaultInstanceId: String? = null,
) {
val palette = LocalPalette.current
var query by rememberSaveable { mutableStateOf(initialQuery) }
var switchingInstance by remember { mutableStateOf(false) }
LaunchedEffect(query) { actions.search(query) }
val groups = remember(state.chats, state.folders, query, today) { groupChats(state.chats, query, today, zone, state.folders) }
// The one dialog open at a time: a chat to file, a folder to name (new or renamed), one to delete.
@@ -617,10 +631,74 @@ fun DrawerContent(
}
}
HorizontalDivider(color = palette.border)
DrawerItem(Icons.Filled.Settings, stringResource(R.string.settings), subtitle = account.ifBlank { null }, onClick = actions::settings)
if (instances.isNotEmpty() && activeInstance != null) {
Row(
Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 4.dp)
.clip(RoundedCornerShape(20.dp))
.clickable { switchingInstance = true }
.heightIn(min = 52.dp)
.padding(horizontal = 14.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text(
activeInstance.name.ifBlank { activeInstance.base },
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.Medium,
color = palette.ink,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
if (activeInstance.email.isNotBlank()) {
Text(
activeInstance.email,
style = MaterialTheme.typography.bodySmall,
color = palette.inkMuted,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
Spacer(Modifier.width(8.dp))
Icon(
Icons.Filled.UnfoldMore,
contentDescription = stringResource(R.string.instance_switch),
tint = palette.inkMuted,
modifier = Modifier.size(20.dp),
)
}
}
DrawerItem(
Icons.Filled.Settings,
stringResource(R.string.settings),
subtitle = if (instances.isEmpty()) account.ifBlank { null } else null,
onClick = actions::settings,
)
Spacer(Modifier.size(8.dp))
}
}
if (switchingInstance) {
ModalBottomSheet(
onDismissRequest = { switchingInstance = false },
sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),
) {
InstanceSwitcherSheet(
instances = instances,
activeId = activeInstance?.id,
defaultId = defaultInstanceId,
onPick = { picked ->
switchingInstance = false
if (picked.id != activeInstance?.id) actions.useInstance(picked)
},
onAdd = {
switchingInstance = false
actions.addInstance()
},
)
}
}
moving?.let { chat ->
MoveDialog(
chat,
@@ -700,6 +778,95 @@ private data class FolderNaming(val folder: Folder? = null, val then: Chat? = nu
/** What a chat's row can do: open it, and from its long-press menu Pin, Move to folder, Archive. */
private class ChatRowActions(val open: (String) -> Unit, val archive: (Chat) -> Unit, val pin: (Chat, Boolean) -> Unit, val move: (Chat) -> Unit)
@Composable
private fun InstanceSwitcherSheet(instances: List<Instance>, activeId: String?, defaultId: String?, onPick: (Instance) -> Unit, onAdd: () -> Unit) {
val palette = LocalPalette.current
LazyColumn(Modifier.fillMaxWidth(), contentPadding = PaddingValues(bottom = 24.dp)) {
item {
Text(
stringResource(R.string.settings_instances),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(start = 24.dp, end = 24.dp, bottom = 8.dp),
)
}
items(instances, key = { it.id }) { item ->
val inUse = item.id == activeId
val isDefault = item.id == defaultId
Row(
Modifier
.fillMaxWidth()
.clickable { onPick(item) }
.heightIn(min = 64.dp)
.padding(horizontal = 24.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
item.name.ifBlank { item.base },
style = MaterialTheme.typography.bodyLarge,
color = palette.ink,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f, fill = false),
)
if (isDefault) {
Spacer(Modifier.width(8.dp))
Surface(color = palette.accentSoft, shape = RoundedCornerShape(8.dp)) {
Text(
stringResource(R.string.instance_default),
style = MaterialTheme.typography.labelSmall,
color = palette.accent,
modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
)
}
}
}
if (item.email.isNotBlank()) {
Text(
item.email,
style = MaterialTheme.typography.bodyMedium,
color = palette.inkMuted,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
Text(
item.base,
style = MaterialTheme.typography.bodySmall,
color = palette.inkFaint,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
if (inUse) {
Spacer(Modifier.width(12.dp))
Icon(
Icons.Filled.CheckCircle,
contentDescription = stringResource(R.string.instance_in_use),
tint = palette.accent,
)
}
}
}
item {
HorizontalDivider(color = palette.border, modifier = Modifier.padding(horizontal = 24.dp, vertical = 4.dp))
Row(
Modifier
.fillMaxWidth()
.clickable(onClick = onAdd)
.heightIn(min = 56.dp)
.padding(horizontal = 24.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(Icons.Filled.Add, contentDescription = null, tint = palette.accent)
Spacer(Modifier.width(16.dp))
Text(stringResource(R.string.add_instance), style = MaterialTheme.typography.bodyLarge, color = palette.ink)
}
}
}
}
private fun LazyListScope.section(title: Int, chats: List<Chat>, current: String?, actions: ChatRowActions, key: String = "c") {
if (chats.isEmpty()) return
item(key = "h$title") {
@@ -43,6 +43,7 @@ import androidx.compose.material.icons.filled.Hearing
import androidx.compose.material.icons.filled.History
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Mic
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.MyLocation
import androidx.compose.material.icons.filled.Navigation
import androidx.compose.material.icons.filled.Notifications
@@ -54,11 +55,14 @@ import androidx.compose.material.icons.filled.RecordVoiceOver
import androidx.compose.material.icons.filled.Science
import androidx.compose.material.icons.filled.ScreenLockPortrait
import androidx.compose.material.icons.filled.Security
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.SystemUpdate
import androidx.compose.material.icons.filled.Timer
import androidx.compose.material.icons.filled.Translate
import androidx.compose.material.icons.filled.Tune
import androidx.compose.material.icons.filled.Update
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
@@ -135,6 +139,7 @@ import kotlinx.coroutines.launch
/** What the settings page does; every action has a do-nothing default for the screenshots. */
interface SettingsActions {
fun use(instance: Instance) {}
fun setDefault(instance: Instance) {}
fun add() {}
/** The instance's MCP servers and their sign-ins. */
@@ -176,6 +181,7 @@ data class WakeTestShown(val running: Boolean = false, val done: Boolean = false
data class SettingsState(
val instances: List<Instance> = emptyList(),
val active: Instance? = null,
val defaultInstance: Instance? = null,
val prefs: Prefs = Prefs(),
val hasDistributor: Boolean = false,
val pushNote: String? = null,
@@ -217,6 +223,7 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit, onMcp: () -> U
val scope = rememberCoroutineScope()
val instances by store.instances.collectAsState(initial = emptyList())
val active by store.active.collectAsState(initial = null)
val defaultInstance by store.defaultInstance.collectAsState(initial = null)
val prefs by store.prefs.collectAsState(initial = Prefs())
val wakeState by WakeStatus.state.collectAsState()
val assistantConnected by AssistLink.connected.collectAsState()
@@ -231,11 +238,12 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit, onMcp: () -> U
}
clock = SystemClock.elapsedRealtime()
}
// The instance's models, for the assistant's: asked for each time Settings opens on an instance.
// The default instance's models, for the assistant's: asked for each time Settings opens on an instance.
val assistInstance = defaultInstance ?: active
var models by remember { mutableStateOf(emptyList<ModelInfo>()) }
LaunchedEffect(active?.id) {
LaunchedEffect(assistInstance?.id) {
models = try {
store.client()?.models().orEmpty()
assistInstance?.let { store.clientFor(it).models() }.orEmpty()
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
@@ -267,6 +275,10 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit, onMcp: () -> U
}
}
override fun setDefault(instance: Instance) {
scope.launch { store.setDefault(instance.id) }
}
override fun add() = onAddInstance()
override fun mcpServers() = onMcp()
@@ -313,7 +325,10 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit, onMcp: () -> U
}
override fun assistantModel(id: String) {
scope.launch { store.savePrefs { it.copy(assistantModel = id) } }
scope.launch {
val target = (store.default() ?: store.current())?.id
store.savePrefs { p -> p.withInstance(target) { it.copy(assistantModel = id) } }
}
}
override fun voiceInput(value: String) {
@@ -437,6 +452,7 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit, onMcp: () -> U
SettingsState(
instances = instances,
active = active,
defaultInstance = defaultInstance,
prefs = prefs,
hasDistributor = distributors.isNotEmpty(),
pushNote = pushNote,
@@ -517,21 +533,41 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
state.instances.forEachIndexed { i, instance ->
if (i > 0) Rule()
val inUse = instance.id == state.active?.id
val isDefault = instance.id == (state.defaultInstance?.id ?: state.instances.firstOrNull()?.id)
var menuOpen by remember(instance.id) { mutableStateOf(false) }
Row(
Modifier.fillMaxWidth().clickable { actions.use(instance) }.heightIn(min = 72.dp).padding(horizontal = 16.dp, vertical = 12.dp),
Modifier
.fillMaxWidth()
.clickable { actions.use(instance) }
.heightIn(min = 72.dp)
.padding(start = 16.dp, end = 4.dp, top = 12.dp, bottom = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Initial(instance.name.ifBlank { instance.base })
Spacer(Modifier.width(16.dp))
Column(Modifier.weight(1f)) {
Text(
instance.name.ifBlank {
instance.base
},
style = MaterialTheme.typography.bodyLarge,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
instance.name.ifBlank {
instance.base
},
style = MaterialTheme.typography.bodyLarge,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f, fill = false),
)
if (isDefault) {
Spacer(Modifier.width(8.dp))
Surface(color = palette.accentSoft, shape = RoundedCornerShape(8.dp)) {
Text(
stringResource(R.string.instance_default),
style = MaterialTheme.typography.labelSmall,
color = palette.accent,
modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
)
}
}
}
Text(
instance.email,
style = MaterialTheme.typography.bodyMedium,
@@ -548,9 +584,34 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
)
}
if (inUse) {
Spacer(Modifier.width(12.dp))
Spacer(Modifier.width(8.dp))
Icon(Icons.Filled.CheckCircle, contentDescription = stringResource(R.string.instance_in_use), tint = palette.accent)
}
Box {
IconButton(onClick = { menuOpen = true }) {
Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.more), tint = palette.inkMuted)
}
DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) {
if (!isDefault) {
DropdownMenuItem(
text = { Text(stringResource(R.string.instance_set_default)) },
leadingIcon = { Icon(Icons.Filled.Star, contentDescription = null) },
onClick = {
menuOpen = false
actions.setDefault(instance)
},
)
}
DropdownMenuItem(
text = { Text(stringResource(R.string.sign_out), color = palette.danger) },
leadingIcon = { Icon(Icons.AutoMirrored.Filled.Logout, contentDescription = null, tint = palette.danger) },
onClick = {
menuOpen = false
actions.signOut(instance)
},
)
}
}
}
}
if (state.instances.isNotEmpty()) Rule()
@@ -1207,7 +1268,8 @@ fun WakeChoices(which: WakeChoice, prefs: Prefs, onPick: ((SettingsActions) -> U
*/
@Composable
private fun assistantModelLabel(state: SettingsState): String {
val chosen = state.prefs.assistantModel
val target = (state.defaultInstance ?: state.active)?.id
val chosen = state.prefs.forInstance(target).assistantModel
val model = state.assistantModels.named(chosen)
// While the list is not read yet, or could not be: the choice as it was saved.
return when {
@@ -1226,7 +1288,8 @@ private fun assistantModelLabel(state: SettingsState): String {
@Composable
fun AssistantModelChoices(state: SettingsState, onPick: (String) -> Unit) {
// A choice saved before models had refs is an id: it still finds its model.
val chosen = state.assistantModels.named(state.prefs.assistantModel)?.key.orEmpty()
val target = (state.defaultInstance ?: state.active)?.id
val chosen = state.assistantModels.named(state.prefs.forInstance(target).assistantModel)?.key.orEmpty()
val choices = listOf(
Choice(INSTANCE_DEFAULT, stringResource(R.string.assistant_model_default), stringResource(R.string.assistant_model_default_line), chosen.isEmpty()),
) + state.assistantModels.distinctBy { it.key }.map { Choice(it.key, it.titleAmong(state.assistantModels), null, it.key == chosen) }
@@ -3,27 +3,35 @@
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
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
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
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
@@ -41,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 {
@@ -63,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)
@@ -92,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,
@@ -110,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))
}
@@ -134,14 +227,22 @@ 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 = {}, model: SignInViewModel = viewModel()) {
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())
val distinctBases = knownBases.map { it.base }.distinct()
Column(
modifier = Modifier.fillMaxSize().safeDrawingPadding().imePadding().padding(24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
@@ -166,24 +267,98 @@ fun SignInScreen(onDone: () -> Unit = {}, model: SignInViewModel = viewModel())
keyboardActions = KeyboardActions(onGo = { if (address.isNotBlank()) model.start(address) }),
modifier = Modifier.fillMaxWidth().widthIn(max = 420.dp),
)
if (distinctBases.isNotEmpty() && onCancel != null) {
Row(
modifier = Modifier.widthIn(max = 420.dp).horizontalScroll(rememberScrollState()),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
distinctBases.forEach { base ->
OutlinedButton(onClick = { address = base }) {
Text(base.removePrefix("https://").removePrefix("http://"))
}
}
}
}
if (s is SignInState.Failed) {
Text(s.message, color = MaterialTheme.colorScheme.error, modifier = Modifier.widthIn(max = 420.dp))
}
Button(onClick = { model.start(address) }, enabled = address.isNotBlank()) {
Text(stringResource(R.string.signin_continue))
Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) {
if (onCancel != null) {
TextButton(onClick = onCancel) { Text(stringResource(R.string.cancel)) }
}
Button(onClick = { model.start(address) }, enabled = address.isNotBlank()) {
Text(stringResource(R.string.signin_continue))
}
}
}
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() })
}
}
}
@@ -1,4 +1,4 @@
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.18. Do not edit.
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.19. Do not edit.
package eu.llembas.android.ui.theme
import androidx.compose.ui.graphics.Color
@@ -228,9 +228,19 @@ class PdfPages(private val copy: File) {
}
}
/** A PDF, page by page, as wide as the screen. */
/** A PDF of the tree, page by page, as wide as the screen. */
@Composable
fun PdfBody(path: String, name: String, size: Long, fallback: @Composable (String?) -> Unit) {
fun PdfBody(path: String, name: String, size: Long, fallback: @Composable (String?) -> Unit) =
PdfBody(Raw.Path(path), name, size, gone = null, fallback = fallback)
/**
* The same for any [Raw]: a file a chat names by its node id is copied and laid out as one of
* the tree is. [gone] is what to say of a file that is no longer there, where the instance's own
* refusal would name an id.
*/
@Composable
fun PdfBody(what: Raw, name: String, size: Long, gone: String? = null, fallback: @Composable (String?) -> Unit) {
val path = what
val context = LocalContext.current
var pages by remember(path) { mutableStateOf<Fetched<PdfPages>>(Fetched.Loading()) }
DisposableEffect(path) {
@@ -248,7 +258,7 @@ fun PdfBody(path: String, name: String, size: Long, fallback: @Composable (Strin
pages = try {
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
context.lembas.gate.pass()
api.copyInto(api.rawFile(path), copy, PDF_MAX_BYTES, stepped { done, total -> pages = Fetched.Loading(done, total) })
api.copyInto(api.raw(what), copy, PDF_MAX_BYTES, stepped { done, total -> pages = Fetched.Loading(done, total) })
withContext(Dispatchers.IO) { made = PdfPages(copy) }
Fetched.Ready(checkNotNull(made))
} catch (e: CancellationException) {
@@ -259,7 +269,13 @@ fun PdfBody(path: String, name: String, size: Long, fallback: @Composable (Strin
made?.closeLater()
copy.delete()
// A password, or not a PDF after all: the renderer's own words are for a developer.
Fetched.Failed(if (e is ApiException || unreachable(e)) viewerSays(context, e) else null)
Fetched.Failed(
when {
gone != null && e is ApiException && e.status == 404 -> gone
e is ApiException || unreachable(e) -> viewerSays(context, e)
else -> null
},
)
}
}
when (val now = pages) {
@@ -469,6 +485,40 @@ fun MediaBody(what: Raw, size: Long, video: Boolean, fallback: @Composable (Stri
/** What a player opened over a chat plays: which bytes, what it is called, how large, and whether there is a picture. */
data class Playing(val what: Raw, val title: String, val size: Long, val video: Boolean)
/** A document a chat names, to be laid out over it: a PDF an agent showed. */
data class Reading(val what: Raw, val title: String, val size: Long)
/**
* A PDF over the whole screen, for a file a chat names by its node id: its pages as the tree's
* viewer lays them out, from a copy in the private cache. One that is no longer there says so
* ([gone]); one this phone cannot lay out says that it can still be downloaded. Back or the cross
* closes it.
*/
@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
@Composable
fun DocumentDialog(reading: Reading, onClose: () -> Unit, gone: String) {
val palette = LocalPalette.current
val unreadable: @Composable (String?) -> Unit = { note ->
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(note ?: stringResource(R.string.files_not_shown), color = palette.inkMuted, modifier = Modifier.padding(32.dp))
}
}
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
Scaffold(
topBar = {
TopAppBar(
navigationIcon = { IconButton(onClick = onClose) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
title = { Text(reading.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
)
},
) { padding ->
Box(Modifier.padding(padding).fillMaxSize()) {
PdfBody(reading.what, reading.title, reading.size, gone = gone, fallback = unreadable)
}
}
}
}
/** How a player's file was found before it was handed to the player. */
private sealed interface Probed {
data object Asking : Probed
@@ -182,7 +182,7 @@ fun TreeFileViewer(path: String, onClose: () -> Unit, startEditing: Boolean = fa
object : FileActions {
override fun download() = saveTo.launch(CreateFile.Ask(name, file?.mime.orEmpty()))
override fun openWith() = transfers.openWith(path, name, file?.mime.orEmpty())
override fun openWith() = transfers.openWith(path, name)
override fun share() = transfers.share(listOf(FileEntry(name = name, path = path, mime = file?.mime.orEmpty())))
}
@@ -3,11 +3,12 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp" android:height="108dp"
android:viewportWidth="108" android:viewportHeight="108">
<group android:translateX="26" android:translateY="26" android:scaleX="3.5" android:scaleY="3.5">
<path android:fillColor="#0B0D10" android:pathData="M10,0h5v1h-5z M8,1h2v1h-2z M15,1h1v1h-1z M6,2h2v1h-2z M15,2h1v1h-1z M5,3h1v1h-1z M15,3h1v1h-1z M5,4h1v1h-1z M14,4h1v1h-1z M4,5h1v1h-1z M14,5h1v1h-1z M4,6h1v1h-1z M14,6h1v1h-1z M3,7h1v1h-1z M13,7h1v1h-1z M3,8h1v1h-1z M12,8h1v1h-1z M3,9h1v1h-1z M11,9h1v1h-1z M3,10h1v1h-1z M10,10h1v1h-1z M3,11h1v1h-1z M7,11h3v1h-3z M2,12h1v1h-1z M4,12h3v1h-3z M1,13h1v1h-1z M3,13h1v1h-1z M0,14h1v1h-1z M2,14h1v1h-1z M1,15h1v1h-1z"/>
<path android:fillColor="#4FAE5A" android:pathData="M14,2h1v1h-1z M13,3h2v1h-2z M12,4h2v1h-2z M11,5h3v1h-3z M10,6h4v1h-4z M9,7h4v1h-4z M8,8h4v1h-4z M7,9h4v1h-4z M6,10h4v1h-4z M5,11h2v1h-2z M3,12h1v1h-1z M2,13h1v1h-1z M1,14h1v1h-1z"/>
<path android:fillColor="#7EE081" android:pathData="M11,1h4v1h-4z M10,2h2v1h-2z M9,3h2v1h-2z M8,4h2v1h-2z M7,5h2v1h-2z M6,6h2v1h-2z M5,7h2v1h-2z M4,8h2v1h-2z M4,9h1v1h-1z M4,11h1v1h-1z"/>
<path android:fillColor="#B6F2A6" android:pathData="M10,1h1v1h-1z M8,2h2v1h-2z M6,3h3v1h-3z M6,4h2v1h-2z M5,5h2v1h-2z M5,6h1v1h-1z M4,7h1v1h-1z"/>
<path android:fillColor="#D8FFD0" android:pathData="M12,2h2v1h-2z M11,3h2v1h-2z M10,4h2v1h-2z M9,5h2v1h-2z M8,6h2v1h-2z M7,7h2v1h-2z M6,8h2v1h-2z M5,9h2v1h-2z M4,10h2v1h-2z"/>
<group android:translateX="21" android:translateY="21" android:scaleX="2.75" android:scaleY="2.75">
<path android:fillColor="#0B0D10" android:pathData="M12,2h5v1h-5z M10,3h2v1h-2z M17,3h1v1h-1z M8,4h2v1h-2z M17,4h1v1h-1z M7,5h1v1h-1z M17,5h1v1h-1z M7,6h1v1h-1z M16,6h1v1h-1z M6,7h1v1h-1z M16,7h1v1h-1z M6,8h1v1h-1z M16,8h1v1h-1z M5,9h1v1h-1z M15,9h1v1h-1z M5,10h1v1h-1z M14,10h1v1h-1z M5,11h1v1h-1z M13,11h1v1h-1z M5,12h1v1h-1z M12,12h1v1h-1z M5,13h1v1h-1z M9,13h3v1h-3z M4,14h1v1h-1z M6,14h3v1h-3z M3,15h1v1h-1z M5,15h1v1h-1z M2,16h1v1h-1z M4,16h1v1h-1z M3,17h1v1h-1z"/>
<path android:fillColor="#4FAE5A" android:pathData="M16,4h1v1h-1z M15,5h2v1h-2z M14,6h2v1h-2z M13,7h3v1h-3z M12,8h4v1h-4z M11,9h4v1h-4z M10,10h4v1h-4z M9,11h4v1h-4z M8,12h4v1h-4z M7,13h2v1h-2z M5,14h1v1h-1z M4,15h1v1h-1z M3,16h1v1h-1z"/>
<path android:fillColor="#7EE081" android:pathData="M13,3h4v1h-4z M12,4h2v1h-2z M11,5h2v1h-2z M10,6h2v1h-2z M9,7h2v1h-2z M8,8h2v1h-2z M7,9h2v1h-2z M6,10h2v1h-2z M6,11h1v1h-1z M6,13h1v1h-1z"/>
<path android:fillColor="#B6F2A6" android:pathData="M12,3h1v1h-1z M10,4h2v1h-2z M8,5h3v1h-3z M8,6h2v1h-2z M7,7h2v1h-2z M7,8h1v1h-1z M6,9h1v1h-1z"/>
<path android:fillColor="#C792EA" android:pathData="M15,14h5v1h-5z M15,15h1v1h-1z M19,15h1v1h-1z M15,16h1v1h-1z M19,16h1v1h-1z M15,17h1v1h-1z M19,17h1v1h-1z M15,18h1v1h-1z M19,18h1v1h-1z M15,19h1v1h-1z M17,19h1v1h-1z M19,19h1v1h-1z M15,20h5v1h-5z"/>
<path android:fillColor="#D8FFD0" android:pathData="M14,4h2v1h-2z M13,5h2v1h-2z M12,6h2v1h-2z M11,7h2v1h-2z M10,8h2v1h-2z M9,9h2v1h-2z M8,10h2v1h-2z M7,11h2v1h-2z M6,12h2v1h-2z"/>
</group>
</vector>
@@ -3,7 +3,7 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp" android:height="108dp"
android:viewportWidth="108" android:viewportHeight="108">
<group android:translateX="26" android:translateY="26" android:scaleX="3.5" android:scaleY="3.5">
<path android:fillColor="#FFFFFFFF" android:pathData="M10,0h5v1h-5z M8,1h2v1h-2z M10,1h1v1h-1z M11,1h4v1h-4z M15,1h1v1h-1z M6,2h2v1h-2z M8,2h2v1h-2z M10,2h2v1h-2z M12,2h2v1h-2z M14,2h1v1h-1z M15,2h1v1h-1z M5,3h1v1h-1z M6,3h3v1h-3z M9,3h2v1h-2z M11,3h2v1h-2z M13,3h2v1h-2z M15,3h1v1h-1z M5,4h1v1h-1z M6,4h2v1h-2z M8,4h2v1h-2z M10,4h2v1h-2z M12,4h2v1h-2z M14,4h1v1h-1z M4,5h1v1h-1z M5,5h2v1h-2z M7,5h2v1h-2z M9,5h2v1h-2z M11,5h3v1h-3z M14,5h1v1h-1z M4,6h1v1h-1z M5,6h1v1h-1z M6,6h2v1h-2z M8,6h2v1h-2z M10,6h4v1h-4z M14,6h1v1h-1z M3,7h1v1h-1z M4,7h1v1h-1z M5,7h2v1h-2z M7,7h2v1h-2z M9,7h4v1h-4z M13,7h1v1h-1z M3,8h1v1h-1z M4,8h2v1h-2z M6,8h2v1h-2z M8,8h4v1h-4z M12,8h1v1h-1z M3,9h1v1h-1z M4,9h1v1h-1z M5,9h2v1h-2z M7,9h4v1h-4z M11,9h1v1h-1z M3,10h1v1h-1z M4,10h2v1h-2z M6,10h4v1h-4z M10,10h1v1h-1z M3,11h1v1h-1z M4,11h1v1h-1z M5,11h2v1h-2z M7,11h3v1h-3z M2,12h1v1h-1z M3,12h1v1h-1z M4,12h3v1h-3z M1,13h1v1h-1z M2,13h1v1h-1z M3,13h1v1h-1z M0,14h1v1h-1z M1,14h1v1h-1z M2,14h1v1h-1z M1,15h1v1h-1z"/>
<group android:translateX="21" android:translateY="21" android:scaleX="2.75" android:scaleY="2.75">
<path android:fillColor="#FFFFFFFF" android:pathData="M12,2h5v1h-5z M10,3h2v1h-2z M12,3h1v1h-1z M13,3h4v1h-4z M17,3h1v1h-1z M8,4h2v1h-2z M10,4h2v1h-2z M12,4h2v1h-2z M14,4h2v1h-2z M16,4h1v1h-1z M17,4h1v1h-1z M7,5h1v1h-1z M8,5h3v1h-3z M11,5h2v1h-2z M13,5h2v1h-2z M15,5h2v1h-2z M17,5h1v1h-1z M7,6h1v1h-1z M8,6h2v1h-2z M10,6h2v1h-2z M12,6h2v1h-2z M14,6h2v1h-2z M16,6h1v1h-1z M6,7h1v1h-1z M7,7h2v1h-2z M9,7h2v1h-2z M11,7h2v1h-2z M13,7h3v1h-3z M16,7h1v1h-1z M6,8h1v1h-1z M7,8h1v1h-1z M8,8h2v1h-2z M10,8h2v1h-2z M12,8h4v1h-4z M16,8h1v1h-1z M5,9h1v1h-1z M6,9h1v1h-1z M7,9h2v1h-2z M9,9h2v1h-2z M11,9h4v1h-4z M15,9h1v1h-1z M5,10h1v1h-1z M6,10h2v1h-2z M8,10h2v1h-2z M10,10h4v1h-4z M14,10h1v1h-1z M5,11h1v1h-1z M6,11h1v1h-1z M7,11h2v1h-2z M9,11h4v1h-4z M13,11h1v1h-1z M5,12h1v1h-1z M6,12h2v1h-2z M8,12h4v1h-4z M12,12h1v1h-1z M5,13h1v1h-1z M6,13h1v1h-1z M7,13h2v1h-2z M9,13h3v1h-3z M4,14h1v1h-1z M5,14h1v1h-1z M6,14h3v1h-3z M3,15h1v1h-1z M4,15h1v1h-1z M5,15h1v1h-1z M2,16h1v1h-1z M3,16h1v1h-1z M4,16h1v1h-1z M3,17h1v1h-1z M15,14h5v1h-5z M15,15h1v1h-1z M19,15h1v1h-1z M15,16h1v1h-1z M19,16h1v1h-1z M15,17h1v1h-1z M19,17h1v1h-1z M15,18h1v1h-1z M19,18h1v1h-1z M15,19h1v1h-1z M17,19h1v1h-1z M19,19h1v1h-1z M15,20h5v1h-5z"/>
</group>
</vector>
+26
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>
@@ -415,6 +428,18 @@
<string name="media_video">Video</string>
<string name="media_music">Hudba</string>
<string name="media_model">3D model</string>
<string name="media_audio">Zvuk</string>
<string name="media_pdf">PDF</string>
<string name="media_archive">Archiv</string>
<string name="media_text">Textový soubor</string>
<string name="media_binary">Soubor</string>
<string name="diff_deleted">Smazáno</string>
<string name="diff_counts">Přidané řádky: %1$s, odebrané: %2$s</string>
<string name="diff_show_all">Zobrazit všechny řádky (%1$s)</string>
<string name="diff_show_less">Zobrazit méně</string>
<string name="diff_more">Další řádky, které se zde nezobrazují: %1$s.</string>
<string name="diff_endings">Konce řádků se mění z %1$s na %2$s.</string>
<string name="diff_cut">Tato změna je příliš dlouhá na to, aby se zde porovnala. Zobrazen je jen její začátek.</string>
<string name="media_gone">Tento soubor už neexistuje.</string>
<string name="job_queued">Ve frontě</string>
<string name="job_running">Běží</string>
@@ -451,6 +476,7 @@
<string name="settings_instances">Instance</string>
<string name="sign_out">Odhlásit se</string>
<string name="add_instance">Přidat instanci</string>
<string name="instance_default">Výchozí</string>
<string name="settings_theme">Vzhled</string>
<string name="theme_system">Podle systému</string>
<string name="theme_moria">Moria (temná)</string>
+26
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>
@@ -415,6 +428,18 @@
<string name="media_video">Video</string>
<string name="media_music">Musik</string>
<string name="media_model">3D-Modell</string>
<string name="media_audio">Audio</string>
<string name="media_pdf">PDF</string>
<string name="media_archive">Archiv</string>
<string name="media_text">Textdatei</string>
<string name="media_binary">Datei</string>
<string name="diff_deleted">Gelöscht</string>
<string name="diff_counts">Zeilen hinzugefügt: %1$s, entfernt: %2$s</string>
<string name="diff_show_all">Alle %1$s Zeilen anzeigen</string>
<string name="diff_show_less">Weniger anzeigen</string>
<string name="diff_more">%1$s weitere Zeilen werden hier nicht angezeigt.</string>
<string name="diff_endings">Die Zeilenenden ändern sich von %1$s zu %2$s.</string>
<string name="diff_cut">Diese Änderung ist zu lang, um hier verglichen zu werden. Nur ihr Anfang wird angezeigt.</string>
<string name="media_gone">Diese Datei gibt es nicht mehr.</string>
<string name="job_queued">In der Warteschlange</string>
<string name="job_running">Läuft</string>
@@ -451,6 +476,7 @@
<string name="settings_instances">Instanzen</string>
<string name="sign_out">Abmelden</string>
<string name="add_instance">Instanz hinzufügen</string>
<string name="instance_default">Standard</string>
<string name="settings_theme">Design</string>
<string name="theme_system">Wie das System</string>
<string name="theme_moria">Moria (dunkel)</string>
+26
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>
@@ -415,6 +428,18 @@
<string name="media_video">Vídeo</string>
<string name="media_music">Música</string>
<string name="media_model">Modelo 3D</string>
<string name="media_audio">Audio</string>
<string name="media_pdf">PDF</string>
<string name="media_archive">Archivo comprimido</string>
<string name="media_text">Archivo de texto</string>
<string name="media_binary">Archivo</string>
<string name="diff_deleted">Eliminado</string>
<string name="diff_counts">Líneas añadidas: %1$s, eliminadas: %2$s</string>
<string name="diff_show_all">Mostrar las %1$s líneas</string>
<string name="diff_show_less">Mostrar menos</string>
<string name="diff_more">Aquí no se muestran %1$s líneas más.</string>
<string name="diff_endings">Los finales de línea cambian de %1$s a %2$s.</string>
<string name="diff_cut">Este cambio es demasiado largo para compararlo aquí. Solo se muestra su comienzo.</string>
<string name="media_gone">Ese archivo ya no existe.</string>
<string name="job_queued">En cola</string>
<string name="job_running">En ejecución</string>
@@ -451,6 +476,7 @@
<string name="settings_instances">Instancias</string>
<string name="sign_out">Cerrar sesión</string>
<string name="add_instance">Añadir una instancia</string>
<string name="instance_default">Predeterminado</string>
<string name="settings_theme">Tema</string>
<string name="theme_system">Como el sistema</string>
<string name="theme_moria">Moria (oscuro)</string>
+26
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>
@@ -415,6 +428,18 @@
<string name="media_video">Vidéo</string>
<string name="media_music">Musique</string>
<string name="media_model">Modèle 3D</string>
<string name="media_audio">Audio</string>
<string name="media_pdf">PDF</string>
<string name="media_archive">Archive</string>
<string name="media_text">Fichier texte</string>
<string name="media_binary">Fichier</string>
<string name="diff_deleted">Supprimé</string>
<string name="diff_counts">Lignes ajoutées : %1$s, supprimées : %2$s</string>
<string name="diff_show_all">Afficher les %1$s lignes</string>
<string name="diff_show_less">Afficher moins</string>
<string name="diff_more">%1$s lignes de plus ne sont pas affichées ici.</string>
<string name="diff_endings">Les fins de ligne passent de %1$s à %2$s.</string>
<string name="diff_cut">Cette modification est trop longue pour être comparée ici. Seul son début est affiché.</string>
<string name="media_gone">Ce fichier n\'existe plus.</string>
<string name="job_queued">En file d’attente</string>
<string name="job_running">En cours</string>
@@ -451,6 +476,7 @@
<string name="settings_instances">Instances</string>
<string name="sign_out">Se déconnecter</string>
<string name="add_instance">Ajouter une instance</string>
<string name="instance_default">Par défaut</string>
<string name="settings_theme">Thème</string>
<string name="theme_system">Comme le système</string>
<string name="theme_moria">Moria (sombre)</string>
+26
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>
@@ -415,6 +428,18 @@
<string name="media_video">Videó</string>
<string name="media_music">Zene</string>
<string name="media_model">3D-modell</string>
<string name="media_audio">Hang</string>
<string name="media_pdf">PDF</string>
<string name="media_archive">Archívum</string>
<string name="media_text">Szövegfájl</string>
<string name="media_binary">Fájl</string>
<string name="diff_deleted">Törölve</string>
<string name="diff_counts">Hozzáadott sorok: %1$s, eltávolított: %2$s</string>
<string name="diff_show_all">Mind a(z) %1$s sor megjelenítése</string>
<string name="diff_show_less">Kevesebb megjelenítése</string>
<string name="diff_more">További %1$s sor itt nem látható.</string>
<string name="diff_endings">A sorvégek megváltoznak: %1$s helyett %2$s.</string>
<string name="diff_cut">Ez a változás túl hosszú ahhoz, hogy itt össze lehessen hasonlítani. Csak az eleje látható.</string>
<string name="media_gone">Ez a fájl már nem létezik.</string>
<string name="job_queued">Sorban áll</string>
<string name="job_running">Fut</string>
@@ -451,6 +476,7 @@
<string name="settings_instances">Példányok</string>
<string name="sign_out">Kijelentkezés</string>
<string name="add_instance">Példány hozzáadása</string>
<string name="instance_default">Alapértelmezett</string>
<string name="settings_theme">Téma</string>
<string name="theme_system">A rendszer szerint</string>
<string name="theme_moria">Moria (sötét)</string>
+26
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>
@@ -415,6 +428,18 @@
<string name="media_video">Video</string>
<string name="media_music">Musica</string>
<string name="media_model">Modello 3D</string>
<string name="media_audio">Audio</string>
<string name="media_pdf">PDF</string>
<string name="media_archive">Archivio</string>
<string name="media_text">File di testo</string>
<string name="media_binary">File</string>
<string name="diff_deleted">Eliminato</string>
<string name="diff_counts">Righe aggiunte: %1$s, rimosse: %2$s</string>
<string name="diff_show_all">Mostra tutte le %1$s righe</string>
<string name="diff_show_less">Mostra meno</string>
<string name="diff_more">Altre %1$s righe non sono mostrate qui.</string>
<string name="diff_endings">I fine riga cambiano da %1$s a %2$s.</string>
<string name="diff_cut">Questa modifica è troppo lunga per essere confrontata qui. Ne è mostrato solo l’inizio.</string>
<string name="media_gone">Questo file non esiste più.</string>
<string name="job_queued">In coda</string>
<string name="job_running">In esecuzione</string>
@@ -451,6 +476,7 @@
<string name="settings_instances">Istanze</string>
<string name="sign_out">Esci</string>
<string name="add_instance">Aggiungi un\'istanza</string>
<string name="instance_default">Predefinito</string>
<string name="settings_theme">Tema</string>
<string name="theme_system">Come il sistema</string>
<string name="theme_moria">Moria (scuro)</string>
+1 -1
View File
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.18 (moria). Do not edit. -->
<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.19 (moria). Do not edit. -->
<resources>
<color name="token_bg">#FF0B0D10</color>
<color name="token_surface">#FF11151A</color>
+26
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>
@@ -415,6 +428,18 @@
<string name="media_video">Wideo</string>
<string name="media_music">Muzyka</string>
<string name="media_model">Model 3D</string>
<string name="media_audio">Dźwięk</string>
<string name="media_pdf">PDF</string>
<string name="media_archive">Archiwum</string>
<string name="media_text">Plik tekstowy</string>
<string name="media_binary">Plik</string>
<string name="diff_deleted">Usunięto</string>
<string name="diff_counts">Dodane wiersze: %1$s, usunięte: %2$s</string>
<string name="diff_show_all">Pokaż wszystkie wiersze (%1$s)</string>
<string name="diff_show_less">Pokaż mniej</string>
<string name="diff_more">Dalsze wiersze, których tu nie pokazano: %1$s.</string>
<string name="diff_endings">Końce wierszy zmieniają się z %1$s na %2$s.</string>
<string name="diff_cut">Ta zmiana jest zbyt długa, by ją tu porównać. Pokazano tylko jej początek.</string>
<string name="media_gone">Ten plik już nie istnieje.</string>
<string name="job_queued">W kolejce</string>
<string name="job_running">Działa</string>
@@ -451,6 +476,7 @@
<string name="settings_instances">Instancje</string>
<string name="sign_out">Wyloguj się</string>
<string name="add_instance">Dodaj instancję</string>
<string name="instance_default">Domyślny</string>
<string name="settings_theme">Motyw</string>
<string name="theme_system">Jak system</string>
<string name="theme_moria">Moria (ciemny)</string>
+26
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>
@@ -415,6 +428,18 @@
<string name="media_video">Video</string>
<string name="media_music">Hudba</string>
<string name="media_model">3D model</string>
<string name="media_audio">Zvuk</string>
<string name="media_pdf">PDF</string>
<string name="media_archive">Archív</string>
<string name="media_text">Textový súbor</string>
<string name="media_binary">Súbor</string>
<string name="diff_deleted">Zmazané</string>
<string name="diff_counts">Pridané riadky: %1$s, odobraté: %2$s</string>
<string name="diff_show_all">Zobraziť všetky riadky (%1$s)</string>
<string name="diff_show_less">Zobraziť menej</string>
<string name="diff_more">Ďalšie riadky, ktoré sa tu nezobrazujú: %1$s.</string>
<string name="diff_endings">Konce riadkov sa menia z %1$s na %2$s.</string>
<string name="diff_cut">Táto zmena je príliš dlhá na to, aby sa tu porovnala. Zobrazený je len jej začiatok.</string>
<string name="media_gone">Tento súbor už neexistuje.</string>
<string name="job_queued">Vo fronte</string>
<string name="job_running">Beží</string>
@@ -451,6 +476,7 @@
<string name="settings_instances">Inštancie</string>
<string name="sign_out">Odhlásiť sa</string>
<string name="add_instance">Pridať inštanciu</string>
<string name="instance_default">Predvolené</string>
<string name="settings_theme">Vzhľad</string>
<string name="theme_system">Podľa systému</string>
<string name="theme_moria">Moria (tmavá)</string>
+28
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>
@@ -417,6 +430,18 @@
<string name="media_video">Video</string>
<string name="media_music">Music</string>
<string name="media_model">3D model</string>
<string name="media_audio">Audio</string>
<string name="media_pdf">PDF</string>
<string name="media_archive">Archive</string>
<string name="media_text">Text file</string>
<string name="media_binary">File</string>
<string name="diff_deleted">Deleted</string>
<string name="diff_counts">Lines added: %1$s, removed: %2$s</string>
<string name="diff_show_all">Show all %1$s lines</string>
<string name="diff_show_less">Show less</string>
<string name="diff_more">%1$s more lines are not shown here.</string>
<string name="diff_endings">The line endings change from %1$s to %2$s.</string>
<string name="diff_cut">This change is too long to compare here. Only its beginning is shown.</string>
<string name="media_gone">That file no longer exists.</string>
<string name="job_queued">Queued</string>
<string name="job_running">Running</string>
@@ -453,6 +478,9 @@
<string name="settings_instances">Instances</string>
<string name="sign_out">Sign out</string>
<string name="add_instance">Add an instance</string>
<string name="instance_default">Default</string>
<string name="instance_set_default">Set as default</string>
<string name="instance_switch">Switch instance</string>
<string name="settings_theme">Theme</string>
<string name="theme_system">As the system</string>
<string name="theme_moria">Moria (dark)</string>
+1 -1
View File
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.18 (shire). Do not edit. -->
<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.19 (shire). Do not edit. -->
<resources>
<color name="token_bg">#FFF1EAD6</color>
<color name="token_surface">#FFF8F3E5</color>
@@ -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)
}
}
}
@@ -0,0 +1,80 @@
package eu.llembas.android
import eu.llembas.android.auth.Instance
import eu.llembas.android.auth.InstanceLogic
import eu.llembas.android.auth.Prefs
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class InstanceStoreTest {
private val home = Instance(id = "alice@https://home.example", base = "https://home.example", name = "Home", email = "alice", sealedToken = "t1")
private val work = Instance(id = "bob@https://work.example", base = "https://work.example", name = "Work", email = "bob", sealedToken = "t2")
private val homeAlt = Instance(id = "carol@https://home.example", base = "https://home.example", name = "Home", email = "carol", sealedToken = "t3")
@Test
fun firstAddedBecomesDefaultAndSecondKeepsIt() {
val (list1, active1, default1) = InstanceLogic.afterAdd(emptyList(), home, null)
assertEquals(listOf(home), list1)
assertEquals(home.id, active1)
assertEquals(home.id, default1)
val (list2, active2, default2) = InstanceLogic.afterAdd(list1, work, default1)
assertEquals(listOf(home, work), list2)
assertEquals(work.id, active2)
assertEquals(home.id, default2)
// Two accounts on the same server keep distinct ids.
val (list3, active3, default3) = InstanceLogic.afterAdd(list2, homeAlt, default2)
assertEquals(listOf(home, work, homeAlt), list3)
assertEquals(homeAlt.id, active3)
assertEquals(home.id, default3)
}
@Test
fun activeFallsBackToDefaultThenFirst() {
val all = listOf(home, work)
assertEquals(work, InstanceLogic.pickActive(all, work.id, home.id))
assertEquals(work, InstanceLogic.pickActive(all, null, work.id))
assertEquals(home, InstanceLogic.pickActive(all, "gone", null))
assertNull(InstanceLogic.pickActive(emptyList(), home.id, home.id))
}
@Test
fun removingDefaultOrActivePromotesSurvivingInstance() {
val all = listOf(home, work)
val (rem1, active1, default1) = InstanceLogic.afterRemove(all, home.id, home.id, home.id)
assertEquals(listOf(work), rem1)
assertEquals(work.id, active1)
assertEquals(work.id, default1)
val (rem2, active2, default2) = InstanceLogic.afterRemove(all, work.id, work.id, home.id)
assertEquals(listOf(home), rem2)
assertEquals(home.id, active2)
assertEquals(home.id, default2)
val (rem3, active3, default3) = InstanceLogic.afterRemove(listOf(home), home.id, home.id, home.id)
assertEquals(emptyList<Instance>(), rem3)
assertNull(active3)
assertNull(default3)
}
@Test
fun perInstancePrefsStayIsolated() {
val base = Prefs(assistantModel = "legacy-model", lastAssistChat = "legacy-chat")
// Unknown instance falls back to legacy flat fields.
assertEquals("legacy-model", base.forInstance(home.id).assistantModel)
val updated = base
.withInstance(home.id) { it.copy(assistantModel = "fast-home", lastAssistChat = "c-home") }
.withInstance(work.id) { it.copy(assistantModel = "fast-work", lastAssistChat = "c-work") }
assertEquals("fast-home", updated.forInstance(home.id).assistantModel)
assertEquals("c-home", updated.forInstance(home.id).lastAssistChat)
assertEquals("fast-work", updated.forInstance(work.id).assistantModel)
assertEquals("c-work", updated.forInstance(work.id).lastAssistChat)
val cleaned = updated.withoutInstance(home.id)
assertEquals("fast-work", cleaned.forInstance(work.id).assistantModel)
assertEquals("legacy-model", cleaned.forInstance(home.id).assistantModel)
}
}
@@ -0,0 +1,522 @@
package eu.llembas.android
import eu.llembas.android.api.AskFrame
import eu.llembas.android.api.DIFF_FOLD
import eu.llembas.android.api.DIFF_MOST
import eu.llembas.android.api.DIFF_TEXT_CHARS
import eu.llembas.android.api.DIFF_TEXT_LINES
import eu.llembas.android.api.DeviceList
import eu.llembas.android.api.DiffLine
import eu.llembas.android.api.DiffSign
import eu.llembas.android.api.EditorModels
import eu.llembas.android.api.FileDiff
import eu.llembas.android.api.GeneratedMedia
import eu.llembas.android.api.LembasJson
import eu.llembas.android.api.MediaView
import eu.llembas.android.api.Raw
import eu.llembas.android.api.TextLines
import eu.llembas.android.api.ToolCall
import eu.llembas.android.api.diffLines
import eu.llembas.android.api.hunks
import eu.llembas.android.api.openType
import eu.llembas.android.api.showsDetail
import eu.llembas.android.api.sniffType
import eu.llembas.android.api.textLines
import eu.llembas.android.api.view
import eu.llembas.android.api.visibly
import eu.llembas.android.ui.chat.DIFF_LINE_MOST
import eu.llembas.android.ui.chat.approvalTexts
import eu.llembas.android.ui.chat.diffRow
import eu.llembas.android.ui.chat.mediaKindWord
import eu.llembas.android.ui.chat.offersAlways
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.json.boolean
import kotlinx.serialization.json.int
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* What the pin after the editor round brought: a file an agent showed in the chat, an edit's
* diff on its approval card, and the shapes that are parsed and not drawn yet (a linked
* computer's files, an editor's two models).
*/
@OptIn(ExperimentalCoroutinesApi::class)
class ShownMediaTest {
private fun contract(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) {
"contract/$name.json is missing"
}.readText()
private fun shown(): List<ToolCall> {
val calls = LembasJson.parseToJsonElement(contract("tool_media_shown")).jsonObject.getValue("calls")
return LembasJson.decodeFromJsonElement(ListSerializer(ToolCall.serializer()), calls)
}
private fun media(kind: String, shown: Boolean = true) = GeneratedMedia(kind = kind, nodeId = "node1", name = "thing", shown = shown)
// --- A file an agent showed ---------------------------------------------------------------------
@Test
fun aShownFileIsTheCallsMediaAndNeverAnAttachment() {
val (picture, pdf, archive) = shown()
listOf(picture, pdf, archive).forEach { call ->
assertEquals("show", call.name)
assertTrue(call.media!!.shown)
// No `show` card and no attachment: the card is drawn from `media` alone.
assertNull(call.show)
assertNull(call.image)
assertNull(call.mediaJob)
}
val image = picture.media!!
assertEquals("image", image.kind)
assertEquals(MediaView.Picture, image.view)
assertEquals("chart.png", image.title)
assertEquals(1280, image.width)
assertEquals(720, image.height)
// Its bytes are asked for by its id, wherever the file is now.
assertEquals(Raw.Node("node8"), image.raw)
assertEquals("/home/frodo/oven", image.folder)
assertEquals(MediaView.Document, pdf.media!!.view)
assertEquals("report-20260102-030405.pdf", pdf.media!!.title)
assertEquals(90_000L, pdf.media!!.size)
assertEquals("/home/frodo/Generated", pdf.media!!.folder)
assertEquals(MediaView.Details, archive.media!!.view)
assertEquals(Raw.Node("node10"), archive.media!!.raw)
}
@Test
fun aGeneratedFileIsNotAShownOne() {
val calls = LembasJson.parseToJsonElement(contract("tool_media")).jsonObject.getValue("calls")
val made = LembasJson.decodeFromJsonElement(ListSerializer(ToolCall.serializer()), calls).mapNotNull { it.media }
assertTrue(made.isNotEmpty())
assertTrue(made.none { it.shown })
}
@Test
fun everyKindHasACardAndAudioPlaysAsMusicDoes() {
assertEquals(MediaView.Picture, media("image").view)
assertEquals(MediaView.Sound, media("audio").view)
assertEquals(media("music").view, media("audio").view)
assertEquals(MediaView.Video, media("video").view)
assertEquals(MediaView.Document, media("pdf").view)
// What the phone has no viewer for in a chat is its details: a name, a kind, the ways to the file.
listOf("model3d", "archive", "binary", "text", "hologram", "").forEach { assertEquals(it, MediaView.Details, media(it).view) }
}
@Test
fun everyKindTheServerNamesHasAWordAndAnUnknownOneIsStillAFile() {
listOf("image", "audio", "video", "pdf", "model3d", "archive", "binary", "text").forEach { kind ->
assertNotNull(kind, mediaKindWord(kind))
assertTrue(kind, media(kind).knownKind)
}
assertEquals(R.string.media_audio, mediaKindWord("audio"))
assertEquals(R.string.media_pdf, mediaKindWord("pdf"))
assertEquals(R.string.media_archive, mediaKindWord("archive"))
// No word of its own: the card says "File" for a shown one (`mediaKind`), never nothing.
assertNull(mediaKindWord("hologram"))
assertFalse(media("hologram").knownKind)
}
@Test
fun aShownFileWithoutANameIsCalledByItsPath() {
val nameless = GeneratedMedia(kind = "binary", path = "/home/frodo/Generated/dump-20260102.bin", shown = true)
assertEquals("dump-20260102.bin", nameless.title)
// Without an id it is asked for by its path.
assertEquals(Raw.Path("/home/frodo/Generated/dump-20260102.bin"), nameless.raw)
}
// --- An edit's diff on its card -----------------------------------------------------------------
private fun edit() = contractCard().items.single()
private fun contractCard() = LembasJson.decodeFromString(AskFrame.serializer(), contract("event_ask_edit")).cards.single()
@Test
fun anEditsCardCarriesADiffPerFile() {
val card = contractCard()
assertEquals("approval", card.kind)
val (changed, made, gone) = edit().diffs
assertEquals("src/oven.py", changed.path)
assertFalse(changed.made)
assertFalse(changed.deleted)
assertEquals("src/timer.py", made.path)
assertNull(made.oldText)
assertTrue(made.made)
assertEquals("src/old.py", gone.path)
assertTrue(gone.deleted)
assertFalse(gone.made)
// Allow and Deny are the card's usual ones: nothing of the diff goes back with the answer.
assertTrue(offersAlways(card))
assertTrue(approvalTexts(card.items, emptyMap()).isEmpty())
}
@Test
fun aCardWithoutADiffHasNone() {
val cards = LembasJson.decodeFromString(AskFrame.serializer(), contract("event_ask")).cards
assertTrue(cards.flatMap { it.items }.all { it.diffs.isEmpty() })
}
@Test
fun aChangedFileShowsWhatGoesAndWhatComes() {
val view = edit().diffs[0].view()
assertEquals(2, view.added)
assertEquals(1, view.removed)
assertEquals(
listOf(
DiffLine(DiffSign.Same, "def bake(loaf):"),
DiffLine(DiffSign.Removed, " return loaf.heat(220)"),
DiffLine(DiffSign.Added, " # <img src=x onerror=alert(1)>"),
DiffLine(DiffSign.Added, " return loaf.heat(240)"),
),
view.lines,
)
// A model's words stay words: the line is written as it is, with its sign before it.
assertEquals("+ # <img src=x onerror=alert(1)>", diffRow(view.lines[2]))
assertEquals("- return loaf.heat(220)", diffRow(view.lines[1]))
assertEquals(" def bake(loaf):", diffRow(view.lines[0]))
}
@Test
fun aNewFileIsAllAddedAndADeletedOneAllRemoved() {
val (_, made, gone) = edit().diffs
assertEquals(listOf(DiffLine(DiffSign.Added, "MINUTES = 40")), made.view().lines)
assertEquals(1 to 0, made.view().let { it.added to it.removed })
assertEquals(listOf(DiffLine(DiffSign.Removed, "x = 1")), gone.view().lines)
assertEquals(0 to 1, gone.view().let { it.added to it.removed })
// A deleted file's new text is not read, whatever it says.
assertEquals(gone.view(), gone.copy(newText = "ignored\n").view())
}
@Test
fun aChangeKeepsALittleAroundItAndLeavesTheRestOut() {
val old = (1..40).map { "line $it" }
val new = old.toMutableList().also {
it[9] = "line ten"
it[29] = "line thirty"
}
val all = diffLines(old, new)
assertEquals(42, all.size)
val cut = hunks(all)
// Three lines before and after each change, and one mark for the lines between them.
assertEquals(1, cut.count { it.sign == DiffSign.Gap })
assertEquals("line 7", cut.first().text)
assertEquals("line 33", cut.last().text)
assertEquals(listOf("line 10", "line 30"), cut.filter { it.sign == DiffSign.Removed }.map { it.text })
assertEquals(listOf("line ten", "line thirty"), cut.filter { it.sign == DiffSign.Added }.map { it.text })
assertEquals(17, cut.size)
assertEquals("⋯", diffRow(cut.first { it.sign == DiffSign.Gap }))
}
@Test
fun linesThatMovedAreComparedAsTheLongestSharedRun() {
val lines = diffLines(listOf("a", "b", "c", "d"), listOf("a", "c", "d", "b"))
assertEquals(
listOf(
DiffLine(DiffSign.Same, "a"),
DiffLine(DiffSign.Removed, "b"),
DiffLine(DiffSign.Same, "c"),
DiffLine(DiffSign.Same, "d"),
DiffLine(DiffSign.Added, "b"),
),
lines,
)
// The same text is no change, and so no line on the card.
assertTrue(FileDiff(path = "same.txt", oldText = "a\nb\n", newText = "a\nb\n").view().lines.isEmpty())
// An empty file that is made adds nothing; one without a last newline keeps its last line.
assertTrue(FileDiff(path = "empty", oldText = null, newText = "").view().lines.isEmpty())
assertEquals(listOf("a", "b"), FileDiff(path = "p", oldText = null, newText = "a\nb").view().lines.map { it.text })
}
@Test
fun aLongDiffIsFoldedAndAHugeOneIsBounded() {
val long = FileDiff(path = "long.txt", oldText = null, newText = (1..1000).joinToString("\n") { "row $it" })
val view = long.view()
assertEquals(1000, view.added)
assertTrue(view.folds)
assertEquals(DIFF_FOLD, view.shown(open = false).size)
assertEquals(DIFF_MOST, view.shown(open = true).size)
assertEquals(1000 - DIFF_MOST, view.beyond)
val short = edit().diffs[0].view()
assertFalse(short.folds)
assertEquals(short.lines, short.shown(open = false))
assertEquals(0, short.beyond)
// Two middles too long to compare line against line are not compared: the old goes, the
// new comes. They share every line, in the other order -- compared, some would be "same".
val a = (1..1500).map { "line $it" }
val both = diffLines(a, a.reversed())
assertEquals(3000, both.size)
assertTrue(both.none { it.sign == DiffSign.Same })
assertTrue(both.take(1500).all { it.sign == DiffSign.Removed })
assertTrue(both.drop(1500).all { it.sign == DiffSign.Added })
// The same two, short enough, are compared: something is found to be the same.
val few = (1..50).map { "line $it" }
assertTrue(diffLines(few, few.reversed()).any { it.sign == DiffSign.Same })
// One line of any length is one bounded line of the card; a tab is spaces.
val row = diffRow(DiffLine(DiffSign.Added, "x".repeat(5000)))
assertEquals(2 + DIFF_LINE_MOST + 1, row.length)
assertEquals(" " + " a", diffRow(DiffLine(DiffSign.Same, "\ta")))
}
@Test
fun aTextIsCutBeforeItIsComparedNotAfter() {
// Two megabytes of newlines: only the first lines are ever split off.
val newlines = "\n".repeat(2_000_000)
val cut = textLines(newlines)
assertEquals(DIFF_TEXT_LINES, cut.lines.size)
assertTrue(cut.cut)
// One line of two megabytes: only its beginning is kept.
val one = textLines("x".repeat(2_000_000))
assertEquals(1, one.lines.size)
assertEquals(DIFF_TEXT_CHARS, one.lines.single().length)
assertTrue(one.cut)
// A text within both bounds is whole, and says so.
assertEquals(TextLines(listOf("a", "b"), cut = false), textLines("a\nb\n"))
assertEquals(TextLines(listOf("a", "b"), cut = false), textLines("a\nb"))
assertEquals(TextLines(listOf("a"), cut = true), textLines("a\nb\n", mostLines = 1))
assertEquals(TextLines(listOf("a"), cut = true), textLines("a\nbcd", mostChars = 2))
assertEquals(TextLines(listOf("a", "b"), cut = true), textLines("a\nbcd", mostChars = 3))
// A new file of that size is a card of bounded size that says it is not all there.
val huge = FileDiff(path = "huge.txt", oldText = null, newText = (1..100_000).joinToString("\n") { "row $it" }).view()
assertTrue(huge.cut)
assertEquals(DIFF_TEXT_LINES, huge.added)
assertEquals(DIFF_TEXT_LINES, huge.lines.size)
assertTrue(huge.says)
assertFalse(edit().diffs[0].view().cut)
}
@Test
fun aChangeOfLineEndingsIsSaidOnceNotAsEveryLine() {
val crlf = FileDiff(path = "a.txt", oldText = "one\ntwo\nthree\n", newText = "one\r\ntwo\r\nthree\r\n").view()
assertTrue(crlf.lines.isEmpty())
assertEquals(0 to 0, crlf.added to crlf.removed)
assertEquals("LF" to "CRLF", crlf.endings)
assertTrue(crlf.says)
// With a real change beside it, only that line goes and comes.
val both = FileDiff(path = "a.txt", oldText = "one\r\ntwo\r\n", newText = "one\nTWO\n").view()
assertEquals("CRLF" to "LF", both.endings)
assertEquals(listOf(DiffSign.Same, DiffSign.Removed, DiffSign.Added), both.lines.map { it.sign })
assertEquals(listOf("one", "two", "TWO"), both.lines.map { it.text })
// The same endings, a new file, a file of one line: nothing to say of endings.
assertNull(edit().diffs[0].view().endings)
assertNull(edit().diffs[1].view().endings)
assertNull(FileDiff(path = "p", oldText = "a", newText = "a\r\nb\r\n").view().endings)
}
@Test
fun whatCannotBeSeenIsWrittenAsItsCodePoint() {
// A direction override makes a line read as something it is not; a line separator breaks it in two.
assertEquals("+ if (admin<U+202E>) {", diffRow(DiffLine(DiffSign.Added, "if (admin\u202E) {")))
assertEquals("- a<U+2028>b", diffRow(DiffLine(DiffSign.Removed, "a\u2028b")))
assertEquals("a<U+200B>b<U+FEFF><U+2066><U+0000><U+000D><U+0085>", visibly("a\u200Bb\uFEFF\u2066\u0000\r\u0085"))
// A path is read too: it names what is changed.
assertEquals("src/<U+202E>yp.nevo", visibly("src/\u202Eyp.nevo"))
// Ordinary text, other scripts and wide characters are left as they are.
listOf("def bake(loaf):", "žltý kôň — ünïcödé", "日本語 \uD83C\uDF5E", "").forEach { assertEquals(it, visibly(it)) }
}
@Test
fun theArgumentsStayInViewWhenTheDiffsSayNothing() {
val item = edit()
// Diffs that say something stand in the arguments' place, once they are worked out and while they are.
assertFalse(showsDetail(item, item.diffs.map { it.view() }))
assertFalse(showsDetail(item, null))
// The same text twice, or an entry with nothing in it: the card would say "+0 -0" and nothing else.
val same = item.copy(diffs = listOf(FileDiff(path = "a.txt", oldText = "a\n", newText = "a\n"), FileDiff()))
assertTrue(same.diffs.map { it.view() }.none { it.says })
assertTrue(showsDetail(same, same.diffs.map { it.view() }))
// A card without diffs is as it always was.
assertTrue(showsDetail(item.copy(diffs = emptyList()), emptyList()))
assertTrue(showsDetail(item.copy(diffs = emptyList()), null))
}
// --- The gate and the assistant's sheet ---------------------------------------------------------
@Test
fun theAssistantsSheetIsTheAppInFrontAndTheLockStillShutsTheGate() = runTest {
var locked = false
val gate = InstanceGate { locked }
// No activity: the sheet is a session's window. A picture in it waits as a chat's does...
val fetched = mutableListOf<String>()
val picture = launch {
gate.passLater()
fetched += "picture"
}
runCurrent()
assertTrue(fetched.isEmpty())
// ...until the sheet shows, which no activity's start would ever say.
gate.sessionShown()
runCurrent()
assertEquals(listOf("picture"), fetched)
picture.join()
// Shown again while up, hidden once: shut.
gate.sessionShown()
gate.sessionHidden()
assertFalse(gate.open.value)
// Over the lock screen the sheet opens nothing; the unlock does.
locked = true
gate.sessionShown()
assertFalse(gate.open.value)
locked = false
assertTrue(gate.look())
// An activity of the app in front keeps the gate open when the sheet goes.
gate.activityStarted()
gate.sessionHidden()
assertTrue(gate.open.value)
gate.activityStopped()
assertFalse(gate.open.value)
}
@Test
fun aSessionTornDownWithoutBeingHiddenLeavesTheGateShut() = runTest {
val gate = InstanceGate { false }
val sheet = SheetAtGate(gate)
// Shown, then destroyed with no hide between them: the end is said all the same.
sheet.shown()
assertTrue(gate.open.value)
sheet.gone()
assertFalse(gate.open.value)
assertFalse(gate.look())
// Nothing asked for now starts until something of the app is in front again.
val fetched = mutableListOf<String>()
val picture = launch {
gate.passLater()
fetched += "picture"
}
runCurrent()
assertTrue(fetched.isEmpty())
// Hidden and then destroyed, or destroyed twice, is still one end; the next showing opens it.
sheet.gone()
sheet.gone()
assertFalse(gate.open.value)
sheet.shown()
runCurrent()
assertEquals(listOf("picture"), fetched)
picture.join()
// An activity in front is not undone by the sheet's end.
gate.activityStarted()
sheet.gone()
assertTrue(gate.open.value)
}
// --- Open with ----------------------------------------------------------------------------------
private fun bytes(vararg values: Int) = ByteArray(values.size) { values[it].toByte() }
@Test
fun aFileIsOfferedAsWhatItsBytesSayNotAsWhatItWasCalled() {
val png = bytes(0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A)
val pdf = "%PDF-1.7\n".toByteArray()
val zip = bytes(0x50, 0x4B, 0x03, 0x04, 0x14, 0x00)
assertEquals("image/png", sniffType(png))
assertEquals("application/pdf", sniffType(pdf))
assertEquals("image/jpeg", sniffType(bytes(0xFF, 0xD8, 0xFF, 0xE0)))
assertEquals("video/mp4", sniffType(bytes(0, 0, 0, 0x20) + "ftypisom".toByteArray()))
assertEquals("audio/wav", sniffType("RIFF".toByteArray() + bytes(0, 0, 0, 0) + "WAVE".toByteArray()))
assertEquals("image/webp", sniffType("RIFF".toByteArray() + bytes(0, 0, 0, 0) + "WEBP".toByteArray()))
assertNull(sniffType("just words".toByteArray()))
assertNull(sniffType(ByteArray(0)))
assertNull(sniffType(bytes(0x89)))
// The bytes decide, whatever the name says.
assertEquals("application/pdf", openType(pdf, "image/png"))
assertEquals("image/png", openType(png, null))
// No mark in the bytes: the name's extension, else anything.
assertEquals("text/plain", openType("just words".toByteArray(), "text/plain"))
assertEquals("*/*", openType("just words".toByteArray(), null))
assertEquals("*/*", openType(ByteArray(0), ""))
// A zip is what many documents are inside: a known extension is the better word there.
assertEquals("application/epub+zip", openType(zip, "application/epub+zip"))
assertEquals("application/zip", openType(zip, null))
}
// --- Parsed, and not drawn yet ------------------------------------------------------------------
@Test
fun aDeviceSaysWhetherItHandsItsFilesOver() {
val (workstation, laptop) = LembasJson.decodeFromString(DeviceList.serializer(), contract("devices")).devices
assertTrue(workstation.files)
assertTrue(workstation.filesWritable)
assertFalse(workstation.filesThatRunCode)
assertFalse(laptop.files)
assertFalse(laptop.filesWritable)
// An instance from before the files says nothing, and that is "no".
assertFalse(LembasJson.decodeFromString(DeviceList.serializer(), """{"devices":[{"id":"t1"}]}""").devices.single().files)
}
@Test
fun anEditorsTwoModelsAreReadSetAndUnset() {
val set = LembasJson.decodeFromString(EditorModels.serializer(), contract("editor"))
assertEquals("local/qwen", set.autocomplete.model)
assertEquals("person", set.autocomplete.source)
assertEquals(listOf("local/qwen", "local/vision-small"), set.autocomplete.allowed)
assertEquals("local/gpt-oss", set.main.model)
val unset = LembasJson.decodeFromString(EditorModels.serializer(), contract("editor_unset"))
assertNull(unset.autocomplete.model)
assertNull(unset.autocomplete.source)
assertNull(unset.autocomplete.allowed)
assertNull(unset.main.model)
}
private fun fixture(name: String) = LembasJson.parseToJsonElement(contract(name)).jsonObject
private fun kotlinx.serialization.json.JsonObject.word(key: String) = getValue(key).jsonPrimitive.content
@Test
fun aComputersFilesAndAMessagesEditorContextSayWhatTheApiSays() {
// No screen and no model of these here yet. The fields a browser would stand on are
// where App-API puts them, so a pin that moves them fails here.
val roots = fixture("device_fs_roots")
assertEquals("", roots.word("path"))
assertTrue(roots.getValue("entries").jsonArray.isNotEmpty())
val listing = fixture("device_fs_listing")
assertEquals("/home/dev/project", listing.word("path"))
val entries = listing.getValue("entries").jsonArray.map { it.jsonObject }
val keys = setOf("name", "path", "kind", "size", "mtime", "updated_at", "file_kind", "link", "outside", "protected", "runs_code", "writable")
entries.forEach { assertEquals(keys, it.keys) }
assertTrue(entries.map { it.word("kind") }.containsAll(listOf("dir", "file")))
assertTrue(entries.single { it.word("name") == "shared" }.getValue("outside").jsonPrimitive.boolean)
assertTrue(entries.single { it.word("name") == ".env" }.getValue("protected").jsonPrimitive.boolean)
val content = fixture("device_fs_content")
assertTrue(content.word("sha").startsWith("sha256:"))
assertTrue(content.word("text").isNotEmpty())
val withheld = fixture("device_fs_content_withheld")
assertEquals("", withheld.word("text"))
assertTrue(withheld.getValue("withheld").jsonObject.word("reason") in setOf("not_text", "too_large"))
val conflict = fixture("device_fs_conflict")
assertEquals("changed", conflict.word("reason"))
assertTrue(conflict.getValue("conflict").jsonPrimitive.boolean)
assertTrue(conflict.word("sha").startsWith("sha256:"))
assertEquals("no_trash", fixture("device_fs_no_trash").word("reason"))
assertTrue(fixture("device_fs_written").word("sha").startsWith("sha256:"))
val batch = fixture("device_fs_batch")
assertFalse(batch.getValue("atomic").jsonPrimitive.boolean)
assertTrue(batch.getValue("results").jsonArray.all { "ok" in it.jsonObject && "path" in it.jsonObject })
val editor = fixture("message_editor")
assertEquals("/home/dev/project/src/oven.py", editor.word("path"))
assertEquals(2, editor.getValue("selection").jsonObject.getValue("start").jsonPrimitive.int)
assertEquals("warning", editor.getValue("diagnostics").jsonArray.single().jsonObject.word("severity"))
}
}
@@ -90,6 +90,67 @@ class MediaShots {
shoot("60-media-cards", Phone.SmallScroll, fontScale = 1.5f, content = drawn)
}
private fun shown(kind: String, name: String, size: Long, mime: String = "", width: Int = 0, height: Int = 0) = GeneratedMedia(
kind = kind,
path = "$made/$name",
nodeId = "node-$kind",
name = name,
mime = mime,
size = size,
width = width,
height = height,
shown = true,
)
/** Every kind a shown file can be, and one this app has never heard of: each is a name, a kind in words and the ways to the file. */
private val shownFiles = listOf(
shown("image", "chart.png", 48_211, "image/png", 1280, 720),
shown("audio", "a-recording-of-the-meeting-about-the-ovens-20260102-030405.ogg", 3_300_000, "audio/ogg"),
shown("video", "screen-recording-20260102-030405.webm", 12_400_000, "video/webm", 1920, 1080),
shown("pdf", "report-20260102-030405.pdf", 90_000, "application/pdf"),
shown("model3d", "loaf-20260102.glb", 880_000),
shown("archive", "bundle-20260102-030405.zip", 1_200_000, "application/zip"),
shown("binary", "core-20260102.dump", 64_000_000),
shown("text", "notes-on-the-long-fermentation-of-waybread.txt", 2_048, "text/plain"),
shown("hologram", "something-new.holo", 512),
)
@Test
fun filesAnAgentShowed() {
val drawn: @Composable () -> Unit = {
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
shownFiles.forEach { MediaCard(it, null, actions) }
}
}
shoot("63-shown-files", Phone.Scroll, content = drawn)
shoot("63-shown-files", Phone.SmallScroll, content = drawn)
shoot("63-shown-files", Phone.SmallScroll, fontScale = 1.5f, content = drawn)
}
@Test
fun aChatWithShownFiles() {
fun call(id: String, media: GeneratedMedia) = ToolCall(
id = id,
name = "show",
status = "ok",
path = media.path,
media = media,
block = ToolBlock(kind = "tool", title = media.path, state = "done", label = "Shown"),
)
val reply = Message(
id = "m9",
role = "assistant",
steps = listOf(
Step(index = 0, kind = "tools", calls = listOf(call("c1", shownFiles[0]), call("c2", shownFiles[3]), call("c3", shownFiles[5]))),
Step(index = 1, kind = "text", markdown = "The chart, the report and everything else in one archive."),
),
)
val state = Fakes.transcript.copy(messages = listOf(Message(id = "m8", role = "user", text = "Show me what the run left."), reply), summary = null)
shoot("64-chat-shown") { ChatContent(state, object : ChatActions {}, agent = false, media = actions) }
shoot("64-chat-shown", Phone.Small) { ChatContent(state, object : ChatActions {}, agent = false, media = actions) }
shoot("64-chat-shown", Phone.Small, fontScale = 1.5f) { ChatContent(state, object : ChatActions {}, agent = false, media = actions) }
}
@Test
fun aChatWithGeneratedMedia() {
fun call(id: String, media: GeneratedMedia? = null, job: MediaJob? = null) = ToolCall(
@@ -28,6 +28,9 @@ import com.github.takahirom.roborazzi.inspectionMode
import com.github.takahirom.roborazzi.size
import eu.llembas.android.R
import eu.llembas.android.actions.NavApp
import eu.llembas.android.api.Card
import eu.llembas.android.api.CardItem
import eu.llembas.android.api.FileDiff
import eu.llembas.android.assist.AssistActions
import eu.llembas.android.assist.AssistSheetContent
import eu.llembas.android.assist.AssistSheetFrame
@@ -141,6 +144,45 @@ class ScreenShots {
shoot("03-waiting", Phone.Small, fontScale = 1.5f) { ChatContent(Fakes.waiting, NoChatActions, agent = false) }
}
@Test
fun editDiffCard() {
// An edit's approval card with its diff: a changed file with one line wider than the phone
// (it scrolls in its own box), a new file long enough to fold, a file that goes, and one
// whose line endings change with a character in it that cannot be seen. The
// card itself must not be wider than the phone, at a small one's width and large type too.
val long = " return loaf.heat(240, minutes=timer.MINUTES, rack=\"middle\", steam=True, turn_after=20) # <b>hotter</b>, as asked"
val card = Card(
id = "card9",
kind = "approval",
items = listOf(
CardItem(
key = "0",
kind = "approval",
tool = "edit",
title = "Edit a file",
detail = "{\"path\": \"src/oven.py\"}",
reason = "Manual mode asks before every edit.",
purpose = "Bake hotter",
freeText = false,
diffs = listOf(
FileDiff(
path = "src/bakery/ovens/oven.py",
oldText = "import timer\n\n\ndef bake(loaf):\n loaf.proof()\n return loaf.heat(220)\n",
newText = "import timer\n\n\ndef bake(loaf):\n loaf.proof()\n # 220 was cool for waybread.\n$long\n",
),
FileDiff(path = "src/bakery/timer.py", oldText = null, newText = (1..30).joinToString("\n") { "STEP_$it = ${it * 5}" } + "\n"),
FileDiff(path = "src/bakery/old.py", oldText = "x = 1\ny = 2\n", newText = "", deleted = true),
// Line endings that change are said once; a direction override in a line is written out.
FileDiff(path = "src/bakery/notes.txt", oldText = "keep warm\nserve\n", newText = "keep warm\r\nserve\u202E now\r\n"),
),
),
),
)
shoot("09-edit-diff", Phone.Scroll) { SheetOver { CardSheet(card, onAnswer = {}) } }
shoot("09-edit-diff", Phone.SmallScroll) { SheetOver { CardSheet(card, onAnswer = {}) } }
shoot("09-edit-diff", Phone.SmallScroll, fontScale = 1.5f) { SheetOver { CardSheet(card, onAnswer = {}) } }
}
@Test
fun writing() {
// The 3.4.0 progress line under the reply: `{{text}} · {{elapsed}}`, the clock still.
+20
View File
@@ -0,0 +1,20 @@
{
"op": "delete",
"to": null,
"atomic": false,
"done": 1,
"failed": 1,
"results": [
{
"path": "/home/dev/project/old.md",
"ok": true,
"trash": true
},
{
"path": "/mnt/usb/old.bin",
"ok": false,
"error": "This computer has no trash for /mnt/usb/old.bin: deleting it cannot be undone.",
"reason": "no_trash"
}
]
}
+7
View File
@@ -0,0 +1,7 @@
{
"detail": "/home/dev/project/oven.py changed on the computer since you opened it.",
"reason": "changed",
"conflict": true,
"sha": "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
"mtime": 1767323050000
}
+13
View File
@@ -0,0 +1,13 @@
{
"path": "/home/dev/project/oven.py",
"name": "oven.py",
"size": 412,
"mtime": 1767323045000,
"mime": "text/x-python",
"kind": "code",
"file_kind": "code",
"writable": true,
"language": "python",
"sha": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"text": "def bake():\n return 'lembas'\n"
}
+17
View File
@@ -0,0 +1,17 @@
{
"path": "/home/dev/project/loaf.png",
"name": "loaf.png",
"size": 48211,
"mtime": 1767323045000,
"mime": "image/png",
"kind": "image",
"file_kind": "image",
"writable": true,
"language": "",
"sha": "",
"text": "",
"withheld": {
"reason": "not_text",
"message": "This is not a text file, so it is not shown here."
}
}
+4
View File
@@ -0,0 +1,4 @@
{
"deleted": true,
"trash": true
}
+93
View File
@@ -0,0 +1,93 @@
{
"device": "",
"path": "/home/dev/project",
"parent": "",
"writable": false,
"entries": [
{
"name": "src",
"path": "/home/dev/project/src",
"kind": "dir",
"size": 0,
"mtime": 1767323045000,
"updated_at": "2026-01-02T03:04:05+00:00",
"file_kind": null,
"link": null,
"outside": false,
"protected": false,
"runs_code": false,
"writable": false
},
{
"name": "shared",
"path": "/home/dev/project/shared",
"kind": "dir",
"size": 0,
"mtime": 1767323045000,
"updated_at": "2026-01-02T03:04:05+00:00",
"file_kind": null,
"link": "/srv/shared",
"outside": true,
"protected": false,
"runs_code": false,
"writable": false
},
{
"name": ".env",
"path": "/home/dev/project/.env",
"kind": "file",
"size": 0,
"mtime": 1767323045000,
"updated_at": "2026-01-02T03:04:05+00:00",
"file_kind": "text",
"link": null,
"outside": false,
"protected": true,
"runs_code": false,
"writable": false
},
{
"name": "oven.py",
"path": "/home/dev/project/oven.py",
"kind": "file",
"size": 412,
"mtime": 1767323045000,
"updated_at": "2026-01-02T03:04:05+00:00",
"file_kind": "code",
"link": null,
"outside": false,
"protected": false,
"runs_code": false,
"writable": false
},
{
"name": "loaf.png",
"path": "/home/dev/project/loaf.png",
"kind": "file",
"size": 48211,
"mtime": 1767323045000,
"updated_at": "2026-01-02T03:04:05+00:00",
"file_kind": "binary",
"link": null,
"outside": false,
"protected": false,
"runs_code": false,
"writable": false
},
{
"name": ".git",
"path": "/home/dev/project/.git",
"kind": "dir",
"size": 0,
"mtime": 1767323045000,
"updated_at": "2026-01-02T03:04:05+00:00",
"file_kind": null,
"link": null,
"outside": false,
"protected": false,
"runs_code": true,
"writable": false
}
],
"truncated": false
}
+4
View File
@@ -0,0 +1,4 @@
{
"detail": "This computer has no trash for /mnt/usb/old.bin: deleting it cannot be undone.",
"reason": "no_trash"
}
+23
View File
@@ -0,0 +1,23 @@
{
"device": "",
"path": "",
"parent": "",
"writable": false,
"entries": [
{
"name": "project",
"path": "/home/dev/project",
"kind": "dir",
"size": 0,
"mtime": 1767323045000,
"updated_at": "2026-01-02T03:04:05+00:00",
"file_kind": null,
"link": null,
"outside": false,
"protected": false,
"runs_code": false,
"writable": false
}
],
"truncated": false
}
+14
View File
@@ -0,0 +1,14 @@
{
"root": "/home/dev/project",
"truncated": false,
"files": [
{
"path": "src/oven.py",
"kind": "file"
},
{
"path": "src",
"kind": "dir"
}
]
}
+11
View File
@@ -0,0 +1,11 @@
{
"root": "/home/dev/project",
"truncated": true,
"matches": [
{
"path": "src/oven.py",
"line": 2,
"text": " return 'lembas'"
}
]
}
+15
View File
@@ -0,0 +1,15 @@
{
"name": "oven.py",
"path": "/home/dev/project/oven.py",
"kind": "file",
"size": 412,
"mtime": 1767323045000,
"updated_at": "2026-01-02T03:04:05+00:00",
"file_kind": "code",
"link": null,
"outside": false,
"protected": false,
"runs_code": false,
"writable": false,
"sha": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
+6
View File
@@ -0,0 +1,6 @@
{
"path": "/home/dev/project/oven.py",
"size": 430,
"mtime": 1767323054000,
"sha": "sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
}
+8 -2
View File
@@ -10,7 +10,10 @@
"terminal_hint": "",
"scheduled": true,
"max_mode": "edit",
"directory_model": true
"directory_model": true,
"files": true,
"files_writable": true,
"files_that_run_code": false
},
{
"id": "token2",
@@ -22,7 +25,10 @@
"terminal_hint": "laptop does not open terminals. Switch it on there: in LLeMbas Desktop's settings, or with the LLeMbas CLI's remote.terminal setting.",
"scheduled": false,
"max_mode": "",
"directory_model": false
"directory_model": false,
"files": false,
"files_writable": false,
"files_that_run_code": false
}
]
}
+13
View File
@@ -0,0 +1,13 @@
{
"autocomplete": {
"model": "local/qwen",
"source": "person",
"allowed": [
"local/qwen",
"local/vision-small"
]
},
"main": {
"model": "local/gpt-oss"
}
}
+10
View File
@@ -0,0 +1,10 @@
{
"autocomplete": {
"model": null,
"source": null,
"allowed": null
},
"main": {
"model": null
}
}
+51
View File
@@ -0,0 +1,51 @@
{
"cards": [
{
"id": "card9",
"kind": "approval",
"why": "",
"dismissable": false,
"expires_in": 1800,
"items": [
{
"index": 0,
"key": "0",
"kind": "approval",
"tool": "edit",
"title": "Edit a file",
"header": "",
"detail": "{\"path\": \"src/oven.py\"}",
"reason": "Manual mode asks before every edit.",
"purpose": "Bake hotter",
"options": [],
"multiple": false,
"free_text": false,
"always": true,
"editable": false,
"plan": null,
"mode_choice": true,
"job": "",
"subagent": null,
"diffs": [
{
"path": "src/oven.py",
"old_text": "def bake(loaf):\n return loaf.heat(220)\n",
"new_text": "def bake(loaf):\n # <img src=x onerror=alert(1)>\n return loaf.heat(240)\n"
},
{
"path": "src/timer.py",
"old_text": null,
"new_text": "MINUTES = 40\n"
},
{
"path": "src/old.py",
"old_text": "x = 1\n",
"new_text": "",
"deleted": true
}
]
}
]
}
]
}
+3 -3
View File
@@ -1,5 +1,5 @@
{
"ref": "v2.0.0-beta.18",
"commit": "4c0573f1e68b068b1382ae00c918babb37c91293",
"sha256": "ac22d0333a131982ff2906be7d25bedb1ff730cd8d86e68b71b6e907de634220"
"ref": "v2.0.0-beta.19",
"commit": "47b6e09e67cd36fb702d298643baa518d4396170",
"sha256": "d1ae16aa1ee34c34a960bc2343a40e89cd5d836e8c3106af475d5bdad2d00bd3"
}
+24
View File
@@ -0,0 +1,24 @@
{
"path": "/home/dev/project/src/oven.py",
"cursor": {
"line": 2
},
"selection": {
"start": 2,
"end": 2,
"path": "/home/dev/project/src/oven.py",
"text": " return loaf.heat(220)"
},
"diagnostics": [
{
"message": "220 is cool for waybread.",
"path": "/home/dev/project/src/oven.py",
"line": 2,
"severity": "warning",
"source": "baker"
}
],
"open": [
"/home/dev/project/README.md"
]
}
+85
View File
@@ -0,0 +1,85 @@
{
"calls": [
{
"id": "call8",
"name": "show",
"status": "ok",
"query": "/home/frodo/oven/chart.png",
"path": "/home/frodo/oven/chart.png",
"media": {
"kind": "image",
"path": "/home/frodo/oven/chart.png",
"node_id": "node8",
"version_id": "ver8",
"name": "chart.png",
"mime": "image/png",
"size": 48211,
"shown": true,
"width": 1280,
"height": 720
},
"block": {
"kind": "tool",
"title": "/home/frodo/oven/chart.png",
"chips": [],
"added": 0,
"removed": 0,
"state": "done",
"duration": "",
"label": "Shown"
}
},
{
"id": "call9",
"name": "show",
"status": "ok",
"path": "out/report.pdf",
"media": {
"kind": "pdf",
"path": "/home/frodo/Generated/report-20260102-030405.pdf",
"node_id": "node9",
"version_id": "ver9",
"name": "report-20260102-030405.pdf",
"mime": "application/pdf",
"size": 90000,
"shown": true
},
"block": {
"kind": "tool",
"title": "",
"chips": [],
"added": 0,
"removed": 0,
"state": "done",
"duration": "",
"label": "Shown"
}
},
{
"id": "call10",
"name": "show",
"status": "ok",
"path": "out/bundle.zip",
"media": {
"kind": "archive",
"path": "/home/frodo/Generated/bundle-20260102-030405.zip",
"node_id": "node10",
"version_id": "ver10",
"name": "bundle-20260102-030405.zip",
"mime": "application/zip",
"size": 1200000,
"shown": true
},
"block": {
"kind": "tool",
"title": "",
"chips": [],
"added": 0,
"removed": 0,
"state": "done",
"duration": "",
"label": "Shown"
}
}
]
}
+47 -7
View File
@@ -6,9 +6,13 @@
The mark is a 16x16 grid of rects, so it converts exactly into Android vector drawables -- one
path per colour -- and needs no PNG at any density:
drawable/ic_launcher_foreground.xml the leaf, in the adaptive icon's 66dp safe zone
drawable/ic_launcher_monochrome.xml its silhouette, for themed icons
drawable/ic_notification.xml the same silhouette: a status-bar icon is alpha only
drawable/ic_launcher_foreground.xml the leaf and the app's own sign, in the adaptive icon's 66dp safe zone
drawable/ic_launcher_monochrome.xml their silhouette, for themed icons
drawable/ic_notification.xml the leaf's silhouette alone: a status-bar icon is alpha only
Each LLeMbas product carries the server's leaf with one small pixel sign of its own in the free
corner; this app's is a phone. The launcher's art is 24 pixels across: the leaf at (2, 2), the sign
at (13, 14).
"""
from __future__ import annotations
@@ -37,6 +41,37 @@ def rects(svg: str) -> list[tuple[int, int, int, int, str]]:
return found
# The app's sign: a phone, in the launcher only.
SIGN_COLOUR = "#C792EA"
SIGN = (
"..#####..",
"..#...#..",
"..#...#..",
"..#...#..",
"..#...#..",
"..#.#.#..",
"..#####..",
)
LEAF_AT = (2, 2)
SIGN_AT = (13, 14)
def sign() -> list[tuple[int, int, int, int, str]]:
cells = []
for y, row in enumerate(SIGN):
x = 0
while x < len(row):
if row[x] != "#":
x += 1
continue
w = 1
while x + w < len(row) and row[x + w] == "#":
w += 1
cells.append((x + SIGN_AT[0], y + SIGN_AT[1], w, 1, SIGN_COLOUR))
x += w
return cells
def path(cells) -> str:
return " ".join(f"M{x},{y}h{w}v{h}h-{w}z" for x, y, w, h, _ in cells)
@@ -61,14 +96,19 @@ def main() -> None:
for cell in cells:
by_colour[cell[4]].append(cell)
# 108dp adaptive canvas; the leaf scaled x3.5 (56dp) and centred, inside the 66dp safe zone.
# 108dp adaptive canvas; the art is 24 pixels across, scaled x2.75 (66dp) and centred: the safe zone.
launcher = [(x + LEAF_AT[0], y + LEAF_AT[1], w, h, c) for x, y, w, h, c in cells] + sign()
launcher_by_colour: dict[str, list] = defaultdict(list)
for cell in launcher:
launcher_by_colour[cell[4]].append(cell)
coloured = "".join(
f' <path android:fillColor="{colour}" android:pathData="{path(group)}"/>\n'
for colour, group in sorted(by_colour.items())
for colour, group in sorted(launcher_by_colour.items())
)
group = f' <group android:translateX="26" android:translateY="26" android:scaleX="3.5" android:scaleY="3.5">\n{coloured} </group>\n'
placed = ' <group android:translateX="21" android:translateY="21" android:scaleX="2.75" android:scaleY="2.75">\n'
group = f"{placed}{coloured} </group>\n"
mono = f'{placed} <path android:fillColor="#FFFFFFFF" android:pathData="{path(launcher)}"/>\n </group>\n'
silhouette = f' <path android:fillColor="#FFFFFFFF" android:pathData="{path(cells)}"/>\n'
mono = f' <group android:translateX="26" android:translateY="26" android:scaleX="3.5" android:scaleY="3.5">\n{silhouette} </group>\n'
RES.mkdir(parents=True, exist_ok=True)
(RES / "ic_launcher_foreground.xml").write_text(vector(108, 108, group))
+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
+32
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.",
@@ -447,6 +462,20 @@ STRINGS: dict[str, str] = {
"media_video": "Video",
"media_music": "Music",
"media_model": "3D model",
# A file an agent showed: what it is, in words, for every kind
"media_audio": "Audio",
"media_pdf": "PDF",
"media_archive": "Archive",
"media_text": "Text file",
"media_binary": "File",
# An edit's diff on its approval card
"diff_deleted": "Deleted",
"diff_counts": "Lines added: %1$s, removed: %2$s",
"diff_show_all": "Show all %1$s lines",
"diff_show_less": "Show less",
"diff_more": "%1$s more lines are not shown here.",
"diff_endings": "The line endings change from %1$s to %2$s.",
"diff_cut": "This change is too long to compare here. Only its beginning is shown.",
"media_gone": "That file no longer exists.",
"job_queued": "Queued",
"job_running": "Running",
@@ -485,6 +514,9 @@ STRINGS: dict[str, str] = {
"settings_instances": "Instances",
"sign_out": "Sign out",
"add_instance": "Add an instance",
"instance_default": "Default",
"instance_set_default": "Set as default",
"instance_switch": "Switch instance",
"settings_theme": "Theme",
"theme_system": "As the system",
"theme_moria": "Moria (dark)",
+192 -8
View File
@@ -424,7 +424,30 @@
"mcp_browser_note": "Přihlášení probíhá v prohlížeči, přímo na instanci. Pokud prohlížeč není k instanci přihlášen, nejprve si to vyžádá. Potom se vraťte sem.",
"files_waiting": "Čeká se, až bude aplikace otevřená a telefon odemčený.",
"share_refused": "Něco ze sdíleného odsud odeslat nelze a bylo vynecháno.",
"media_in_trash": "Tento soubor je v koši."
"media_in_trash": "Tento soubor je v koši.",
"media_pdf": "PDF",
"media_archive": "Archiv",
"media_text": "Textový soubor",
"diff_deleted": "Smazáno",
"diff_counts": "Přidané řádky: %1$s, odebrané: %2$s",
"diff_show_all": "Zobrazit všechny řádky (%1$s)",
"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.",
"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",
@@ -852,7 +875,30 @@
"mcp_browser_note": "Die Anmeldung geschieht im Browser, auf der Instanz selbst. Ist der Browser dort nicht angemeldet, wird zuerst danach gefragt. Danach hierher zurückkehren.",
"files_waiting": "Wartet, bis die App geöffnet und das Telefon entsperrt ist.",
"share_refused": "Etwas vom Geteilten kann von hier nicht gesendet werden und wurde ausgelassen.",
"media_in_trash": "Diese Datei liegt im Papierkorb."
"media_in_trash": "Diese Datei liegt im Papierkorb.",
"media_pdf": "PDF",
"media_archive": "Archiv",
"media_text": "Textdatei",
"diff_deleted": "Gelöscht",
"diff_counts": "Zeilen hinzugefügt: %1$s, entfernt: %2$s",
"diff_show_all": "Alle %1$s Zeilen anzeigen",
"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.",
"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",
@@ -1279,7 +1325,30 @@
"mcp_browser_note": "El inicio de sesión se hace en el navegador, en la propia instancia. Si el navegador no tiene la sesión iniciada en la instancia, primero la pide. Después, vuelva aquí.",
"files_waiting": "Esperando a que la aplicación esté abierta y el teléfono desbloqueado.",
"share_refused": "Algo de lo compartido no se puede enviar desde aquí y se ha omitido.",
"media_in_trash": "Ese archivo está en la papelera."
"media_in_trash": "Ese archivo está en la papelera.",
"media_pdf": "PDF",
"media_archive": "Archivo comprimido",
"media_text": "Archivo de texto",
"diff_deleted": "Eliminado",
"diff_counts": "Líneas añadidas: %1$s, eliminadas: %2$s",
"diff_show_all": "Mostrar las %1$s líneas",
"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.",
"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",
@@ -1707,7 +1776,30 @@
"mcp_browser_note": "La connexion se fait dans le navigateur, sur l’instance elle-même. Si le navigateur n’y est pas connecté, il le demande d’abord. Revenez ensuite ici.",
"files_waiting": "En attente que l'application soit ouverte et le téléphone déverrouillé.",
"share_refused": "Un élément partagé ne peut pas être envoyé d'ici et a été laissé de côté.",
"media_in_trash": "Ce fichier est dans la corbeille."
"media_in_trash": "Ce fichier est dans la corbeille.",
"media_pdf": "PDF",
"media_archive": "Archive",
"media_text": "Fichier texte",
"diff_deleted": "Supprimé",
"diff_counts": "Lignes ajoutées : %1$s, supprimées : %2$s",
"diff_show_all": "Afficher les %1$s lignes",
"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é.",
"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",
@@ -2135,7 +2227,30 @@
"mcp_browser_note": "A bejelentkezés a böngészőben történik, magán a példányon. Ha a böngésző nincs bejelentkezve a példányba, előbb azt kéri. Utána térjen vissza ide.",
"files_waiting": "Várakozás, amíg az alkalmazás meg van nyitva és a telefon fel van oldva.",
"share_refused": "A megosztottak közül valami innen nem küldhető el, ezért kimaradt.",
"media_in_trash": "Ez a fájl a lomtárban van."
"media_in_trash": "Ez a fájl a lomtárban van.",
"media_pdf": "PDF",
"media_archive": "Archívum",
"media_text": "Szövegfájl",
"diff_deleted": "Törölve",
"diff_counts": "Hozzáadott sorok: %1$s, eltávolított: %2$s",
"diff_show_all": "Mind a(z) %1$s sor megjelenítése",
"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ó.",
"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",
@@ -2562,7 +2677,30 @@
"mcp_browser_note": "L’accesso avviene nel browser, sull’istanza stessa. Se il browser non ha effettuato l’accesso all’istanza, prima lo chiede. Poi torna qui.",
"files_waiting": "In attesa che l'app sia aperta e il telefono sbloccato.",
"share_refused": "Qualcosa di ciò che è stato condiviso non può essere inviato da qui ed è stato escluso.",
"media_in_trash": "Questo file è nel cestino."
"media_in_trash": "Questo file è nel cestino.",
"media_pdf": "PDF",
"media_archive": "Archivio",
"media_text": "File di testo",
"diff_deleted": "Eliminato",
"diff_counts": "Righe aggiunte: %1$s, rimosse: %2$s",
"diff_show_all": "Mostra tutte le %1$s righe",
"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.",
"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",
@@ -2989,7 +3127,30 @@
"mcp_browser_note": "Logowanie odbywa się w przeglądarce, na samej instancji. Jeśli przeglądarka nie jest zalogowana do instancji, najpierw o to poprosi. Potem wróć tutaj.",
"files_waiting": "Oczekiwanie, aż aplikacja będzie otwarta, a telefon odblokowany.",
"share_refused": "Czegoś z udostępnionych rzeczy nie można stąd wysłać i zostało pominięte.",
"media_in_trash": "Ten plik jest w koszu."
"media_in_trash": "Ten plik jest w koszu.",
"media_pdf": "PDF",
"media_archive": "Archiwum",
"media_text": "Plik tekstowy",
"diff_deleted": "Usunięto",
"diff_counts": "Dodane wiersze: %1$s, usunięte: %2$s",
"diff_show_all": "Pokaż wszystkie wiersze (%1$s)",
"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.",
"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",
@@ -3416,6 +3577,29 @@
"mcp_browser_note": "Prihlásenie prebieha v prehliadači, priamo na inštancii. Ak prehliadač nie je do inštancie prihlásený, najprv si to vyžiada. Potom sa vráťte sem.",
"files_waiting": "Čaká sa, kým bude aplikácia otvorená a telefón odomknutý.",
"share_refused": "Niečo zo zdieľaného sa odtiaľto nedá odoslať a bolo vynechané.",
"media_in_trash": "Tento súbor je v koši."
"media_in_trash": "Tento súbor je v koši.",
"media_pdf": "PDF",
"media_archive": "Archív",
"media_text": "Textový súbor",
"diff_deleted": "Zmazané",
"diff_counts": "Pridané riadky: %1$s, odobraté: %2$s",
"diff_show_all": "Zobraziť všetky riadky (%1$s)",
"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.",
"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á."
}
}
+5 -5
View File
@@ -1,9 +1,9 @@
{
"tag": "v2.0.0-beta.18",
"commit": "4c0573f1e68b068b1382ae00c918babb37c91293",
"sha256": "b5cb5ca7a03fad9fa0f9f9a84f89a71f1ef5f0166eb510e522fac5966910447f",
"tag": "v2.0.0-beta.19",
"commit": "47b6e09e67cd36fb702d298643baa518d4396170",
"sha256": "56095bb3d93a8bc736ff7e7fe27e670ba490c08f2644a5025ec7df5b71d94670",
"res": {
"values": "d4d0387b6d963d6c3cd1b82dfb745117dfeb38502acd957d4f4e305309ab8d4e",
"values-night": "2d22b872202970c14efbbbc2f25bc0fba60ba25f67e504eb75159c6f85c15e9b"
"values": "cc5a18f8d91fb9b7a50183c889d84e160f1785aa2c2ff4d5d0505901c20758a3",
"values-night": "251f54399a6134f6d9fa631be38c04184259ffc2a05a1a237a863fd768412afd"
}
}