Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f596af56d
|
||
|
|
635982a4f8
|
||
|
|
5d9e367992
|
||
|
|
72657ba157
|
||
|
|
37574292cd
|
||
|
|
a9bdfcc18a
|
||
|
|
5256959a11
|
||
|
|
c4813831f5
|
||
|
|
6e08795a5c
|
||
|
|
385f2f7f5d
|
||
|
|
eeba64b1c7
|
||
|
|
a249b516fd
|
||
|
|
7a75633ea1
|
||
|
|
7fcdecf1c8
|
||
|
|
7971676344
|
||
|
|
97ba7f6a29
|
||
|
|
e485530e46
|
||
|
|
1659a79848
|
||
|
|
dec2225a9c
|
||
|
|
5d1e36868c
|
||
|
|
6e24f6f370
|
||
|
|
536f71a627
|
||
|
|
ceaf8ea91f
|
||
|
|
c38582f600
|
||
|
|
7d49b8d94b
|
No files matched your search
+125
-1
@@ -3,7 +3,131 @@
|
||||
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.14] — 2026-11-24
|
||||
|
||||
What is said here of replies that start by themselves needs an instance newer than LLeMbas
|
||||
2.0.0-beta.17. On an older one the app behaves as before.
|
||||
|
||||
### Added
|
||||
|
||||
- **An open chat shows a reply it did not ask for, as it is written.** When a subagent finishes
|
||||
and the main agent answers, when a scheduled task's result or a finished generation wakes the
|
||||
chat, or when the linked computer starts a turn itself, the reply appears and is written in
|
||||
front of you, with its tools and cards, instead of only after the chat was opened again.
|
||||
Coming back to the app reads the chat once, for what happened meanwhile. Such a reply is
|
||||
followed only while the app is in front of an unlocked phone: locked or in the background the
|
||||
app lets it go and asks the instance nothing, and on your return it picks up where the chat
|
||||
is then. A reply you asked for yourself goes on being received, as before.
|
||||
- **The list of chats moves by itself.** While the drawer is open, a chat a reply starts in
|
||||
goes to the top and shows its dot, and the dot of a reply being written goes when the reply
|
||||
ends, without the drawer being closed and opened.
|
||||
|
||||
- **A message that waits can be sent now or discarded.** Under a message that has not been
|
||||
given to a model yet -- queued behind a reply, or waiting on a linked computer -- there are
|
||||
"Send now" and "Discard", as on the web page. Send now starts its reply, which is written in
|
||||
front of you like any you asked for; Discard asks once and takes the message away. Where the
|
||||
instance refuses (a reply is still being written; the message is no longer waiting), it says
|
||||
so in its own words and the chat is read again. A waiting message is not offered Edit: the
|
||||
instance refuses that. Needs an instance that has these two actions.
|
||||
|
||||
### Changed
|
||||
|
||||
- **A waiting message says how it waits**, in the instance's words. One of which it is not
|
||||
known whether it reached the linked computer says so, instead of looking queued: the
|
||||
instance does not send it by itself. One the computer holds says that the computer has it
|
||||
and takes it in with its next turn.
|
||||
- **A turn the linked computer started is a quiet note**, as a schedule's line is: it never
|
||||
looks like something you typed.
|
||||
- In an agent chat, a finished reply that holds nothing, after such a turn, says "The reply to
|
||||
this was not recorded." in one line. Older instances left a few of these as blank rows.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The chat keeps its place.** At the end of the chat you stay at the end; anywhere else, what
|
||||
you are reading does not move.
|
||||
- Reading the chat again (after an edit, a queued message, a reply that woke the chat) no
|
||||
longer takes away the earlier messages you had loaded, and with them the row you were
|
||||
reading.
|
||||
- The app's own scroll to the end can no longer be taken for you scrolling away, which
|
||||
stopped the chat from following a reply although you had not touched it. The assistant's
|
||||
sheet has the same fix.
|
||||
- Scrolling up with a mouse wheel, a keyboard or a screen reader while a reply arrives no
|
||||
longer throws you back to the end: only a finger used to count as you scrolling.
|
||||
- A reply's foot is as tall while it is written as when it has finished, so the end of a
|
||||
reply no longer changes the height of the page.
|
||||
|
||||
## [1.0.0-beta.13] — 2026-11-19
|
||||
|
||||
For Files, generated media and MCP servers as described here the instance must be newer than
|
||||
LLeMbas 2.0.0-beta.16. On an older one Files lists and shows text as before, and says so where
|
||||
it cannot do more.
|
||||
|
||||
### Added
|
||||
|
||||
- **Files is a file manager.** Upload from the phone (several at once, with progress; a file
|
||||
over the instance's limit is refused in the instance's own words and the others still go),
|
||||
make a folder or a text file, rename, move and copy by walking to the folder rather than
|
||||
typing a path, and delete to the trash. A long press chooses; with several chosen, a bar moves,
|
||||
copies, downloads, shares or deletes them all, and says which the instance refused.
|
||||
- **The trash and a file's versions.** What was deleted can be restored or removed for good,
|
||||
one thing or everything. A file's earlier versions are listed, and any of them can be made
|
||||
the file again without losing the others, or saved to the phone as it was.
|
||||
- **Download, Open with and Share.** A file is saved where you choose in the phone's own
|
||||
"Save to" page; several files or a folder come as one zip. Open with and Share hand another
|
||||
app a copy from the app's private storage, which is deleted an hour later, and at once when
|
||||
you sign out or switch instance. The app asks for no storage permission.
|
||||
- **Text files can be edited.** Markdown, code, plain text, a page's source and a table's text,
|
||||
up to the instance's 1 MB. If the file changed on the instance while you were writing, nothing
|
||||
is written over: you choose Reload or Save anyway. Leaving with unsaved text asks first.
|
||||
- **A viewer for each kind of file.** Pictures, with zoom and pan; PDFs, page by page; sound and
|
||||
video, streamed, with seeking; CSV and TSV as a grid; notebooks as their cells' text; an
|
||||
archive as the list of what is inside it, with nothing unpacked. For 3D models and anything
|
||||
else: what it is, with Download, Open with and Share. A PDF is shown up to 100 MB and 2000
|
||||
pages. An HTML page and an SVG are shown as their source -- the app draws nothing a file
|
||||
could script.
|
||||
- **"Save to Files" in the share sheet.** Something shared from another app can be kept in a
|
||||
folder of your files instead of being sent into a chat; shared text is kept as a note. If a
|
||||
file is refused, Save again goes on from that file and does not send the earlier ones twice.
|
||||
- **The share sheet says what came in.** Each shared file is listed with its name and size
|
||||
before anything is sent, and the instance is asked nothing until you choose what to do.
|
||||
- **What a model makes is shown in the chat.** A picture, a video, a piece of music or a 3D
|
||||
model the instance made has a card in the reply: the picture drawn, video and music with
|
||||
Play, a 3D model as what it is. Each card leads to the file in Files -- where it is now, also
|
||||
after it was renamed or moved -- saves it where you choose, shares it, or opens it with
|
||||
another app.
|
||||
- **A long generation shows how it stands.** A video or a track takes minutes. Its card says
|
||||
what is being made, whether it is waiting or running and for how long, and has Cancel. When
|
||||
it is ready the card becomes the player and the chat says so; when it was not made, the card
|
||||
says why in the instance's own words. Nothing of this is shown over the lock screen, and the
|
||||
app posts no notification about a file.
|
||||
- **Sound and video you attached can be played** from the message they are attached to.
|
||||
- **Settings › MCP servers.** The MCP servers your chats may be offered, how many tools each
|
||||
has and how each is signed in to. One that waits for your sign-in has a button that opens the
|
||||
instance's own sign-in page in the browser; the list is read again when you come back.
|
||||
- **A new folder from inside the folder picker**, when moving, copying or saving a share.
|
||||
- **A table can be shown as its text**, and as a table again.
|
||||
|
||||
### Changed
|
||||
|
||||
- **A new file is never written over another.** The instance now makes a new file only where
|
||||
nothing has that name, and says what is there otherwise.
|
||||
- **Only models you can chat with are offered** in the model lists and for the assistant.
|
||||
- **Nothing new is sent while the phone is locked.** Uploads, downloads and the copies for
|
||||
Share and Open with go one request at a time: when the phone locks or the app is left, the
|
||||
one under way finishes and the rest wait, and go on by themselves when the app is open on an
|
||||
unlocked phone again. The progress dialog says when it is waiting.
|
||||
- **The share sheet takes files only from other apps.** A share that names something of
|
||||
LLeMbas's own storage is left out, and the sheet says so.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A chat on a model two connections serve shows the right connection.** When an instance has
|
||||
the same model on two connections, a chat, a reply and a scheduled task on the second one were
|
||||
shown as being on the first: the title, the tick in the model list, the picture, the thinking
|
||||
control. The instance now says which connection each is on, and the app shows that one. The
|
||||
line under a reply and a scheduled task's model name the connection where two share a name.
|
||||
An instance that does not say it yet is shown as before. A chat or a scheduled task whose
|
||||
connection is no longer offered shows no model rather than another connection's.
|
||||
|
||||
## [1.0.0-beta.12] — 2026-11-18
|
||||
|
||||
|
||||
@@ -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.12"
|
||||
versionName = "1.0.0-beta.14"
|
||||
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
|
||||
|
||||
@@ -211,7 +211,9 @@
|
||||
android:name=".push.ScheduleActionReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<!-- A photo for the composer: the camera app writes into one file in the cache. -->
|
||||
<!-- One file of the private cache at a time, to one other app: the photo the camera app
|
||||
takes for the composer, and the copy of a file that Open with or Share hands over
|
||||
(res/xml/file_paths.xml names the two folders). Not exported. -->
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.files"
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* Whether a new request that carries the account's files may start: only while the app is in
|
||||
* front and the phone is unlocked. Work that goes on by itself -- a queue of uploads, the copies
|
||||
* for a share, a player's copy -- asks [pass] before each request. A request already on its way
|
||||
* 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.
|
||||
*/
|
||||
class InstanceGate(private val locked: () -> Boolean) {
|
||||
private val started = AtomicInteger(0)
|
||||
private val state = MutableStateFlow(false)
|
||||
|
||||
/** Whether a request may start now, as it was last looked at. */
|
||||
val open: StateFlow<Boolean> = state.asStateFlow()
|
||||
|
||||
fun activityStarted() {
|
||||
started.incrementAndGet()
|
||||
look()
|
||||
}
|
||||
|
||||
fun activityStopped() {
|
||||
started.updateAndGet { (it - 1).coerceAtLeast(0) }
|
||||
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()
|
||||
state.value = now
|
||||
return now
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns when a request may start. [waiting] hears `true` when that is not now, and `false`
|
||||
* when the wait is over (also when it is given up), so a screen can say what it is waiting
|
||||
* for. While waiting the lock is looked at again every [AGAIN_MS]: an unlock nobody
|
||||
* announced must not leave a queue standing.
|
||||
*/
|
||||
suspend fun pass(waiting: (Boolean) -> Unit = {}) {
|
||||
if (look()) return
|
||||
waiting(true)
|
||||
try {
|
||||
while (!look()) withTimeoutOrNull(AGAIN_MS) { state.first { it } }
|
||||
} finally {
|
||||
waiting(false)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [pass], for a wait that may last as long as the phone lies locked or the app is away: it
|
||||
* sleeps until the gate is told of a change (an activity starting, the unlock) instead of
|
||||
* looking at the lock every second, and only then takes its turn as [pass] does.
|
||||
*/
|
||||
suspend fun passLater() {
|
||||
if (!look()) state.first { it }
|
||||
pass()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val AGAIN_MS = 1_000L
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [work], for as long as a request may start: something nobody asked for (a reply that began by
|
||||
* itself) is followed only while the app is in front of an unlocked phone. When the gate closes
|
||||
* the work is let go -- cancelled, with its connection -- and the answer is null; so it is when
|
||||
* the gate is closed already, and then nothing is started. [stays] says the work is the
|
||||
* person's own after all (they asked for it while it ran): that goes on behind the gate, as a
|
||||
* request under way does. The caller's own cancellation is not taken for a letting go.
|
||||
*/
|
||||
suspend fun <T : Any> InstanceGate.whileOpen(stays: () -> Boolean = { false }, work: suspend () -> T): T? {
|
||||
if (!look() && !stays()) return null
|
||||
return coroutineScope {
|
||||
val doing = async { work() }
|
||||
val watch = launch {
|
||||
open.first { !it && !stays() }
|
||||
doing.cancel()
|
||||
}
|
||||
try {
|
||||
doing.await()
|
||||
} catch (e: CancellationException) {
|
||||
// The caller's own end is the caller's; only the gate's is "let go".
|
||||
currentCoroutineContext().ensureActive()
|
||||
null
|
||||
} finally {
|
||||
watch.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [send] for each of [items] from the one at [from], each after its [turn] at the gate, and
|
||||
* [done] hears how many are through after each. A failure leaves the count where it was, so
|
||||
* the same call with that count takes the queue up at the one that failed, not at the first.
|
||||
*/
|
||||
suspend fun <T> sendFrom(items: List<T>, from: Int, turn: suspend () -> Unit, done: (Int) -> Unit, send: suspend (T) -> Unit) {
|
||||
for (i in from.coerceAtLeast(0) until items.size) {
|
||||
turn()
|
||||
send(items[i])
|
||||
done(i + 1)
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,15 @@ package eu.llembas.android
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Application
|
||||
import android.app.KeyguardManager
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
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.StreamClient
|
||||
@@ -23,27 +29,62 @@ class LembasApp : Application() {
|
||||
/** The one connection to the person's events route, shared by all that watch it. */
|
||||
val events = EventsHub(CoroutineScope(SupervisorJob() + Dispatchers.Default))
|
||||
|
||||
/** The events route of the instance in use, as its frames; null when not signed in. */
|
||||
/**
|
||||
* The events route of the instance in use, as its frames; null when not signed in. Whoever
|
||||
* collects them does so only while its screen is in front (`repeatOnLifecycle`), never from
|
||||
* 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
|
||||
val api = instances.clientFor(instance)
|
||||
return events.frames(instance.id) { StreamClient(api).watch { api.events() } }
|
||||
// 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() } }
|
||||
}
|
||||
|
||||
/** Whether a new request with the account's files may start: the app in front, the phone unlocked. */
|
||||
val gate = InstanceGate { getSystemService(KeyguardManager::class.java)?.isKeyguardLocked == true }
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
instances = InstanceStore(this)
|
||||
// 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.
|
||||
eu.llembas.android.ui.files.FileCache.atStart(this)
|
||||
// The gate hears the lock from the screen going off and the unlock; the activities below say the rest.
|
||||
ContextCompat.registerReceiver(
|
||||
this,
|
||||
object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
gate.look()
|
||||
}
|
||||
},
|
||||
IntentFilter().apply {
|
||||
addAction(Intent.ACTION_USER_PRESENT)
|
||||
addAction(Intent.ACTION_SCREEN_OFF)
|
||||
addAction(Intent.ACTION_SCREEN_ON)
|
||||
},
|
||||
ContextCompat.RECEIVER_NOT_EXPORTED,
|
||||
)
|
||||
// Whether the app is on screen: the wake word may open the assistant's sheet as an
|
||||
// activity only then (Android blocks one started from the background, silently).
|
||||
registerActivityLifecycleCallbacks(
|
||||
object : ActivityLifecycleCallbacks {
|
||||
override fun onActivityStarted(activity: Activity) = AppVisibility.activityStarted()
|
||||
override fun onActivityStarted(activity: Activity) {
|
||||
AppVisibility.activityStarted()
|
||||
gate.activityStarted()
|
||||
}
|
||||
|
||||
override fun onActivityStopped(activity: Activity) = AppVisibility.activityStopped()
|
||||
override fun onActivityStopped(activity: Activity) {
|
||||
AppVisibility.activityStopped()
|
||||
gate.activityStopped()
|
||||
}
|
||||
|
||||
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit
|
||||
|
||||
override fun onActivityResumed(activity: Activity) = Unit
|
||||
override fun onActivityResumed(activity: Activity) {
|
||||
gate.look()
|
||||
}
|
||||
|
||||
override fun onActivityPaused(activity: Activity) = Unit
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
@@ -57,6 +58,7 @@ import eu.llembas.android.ui.scheduled.ScheduleEditScreen
|
||||
import eu.llembas.android.ui.scheduled.ScheduleScreen
|
||||
import eu.llembas.android.ui.scheduled.ScheduledScreen
|
||||
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.theme.LembasTheme
|
||||
@@ -210,9 +212,18 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
// The list is read again each time the drawer opens, so a new title or a finished
|
||||
// reply's dot is there without a pull.
|
||||
LaunchedEffect(drawer.isOpen) { if (drawer.isOpen) chats.load() }
|
||||
// The badge on Reports follows the instance while the app is in front.
|
||||
// While it is open the list follows the replies; closed, nothing reads it.
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
LaunchedEffect(drawer.isOpen) {
|
||||
chats.shown(drawer.isOpen)
|
||||
if (drawer.isOpen) {
|
||||
chats.load()
|
||||
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { chats.watchRunning() }
|
||||
}
|
||||
}
|
||||
// The chat on screen: the end of its reply is not something new in the list.
|
||||
LaunchedEffect(current) { chats.open = current }
|
||||
// The badge on Reports follows the instance while the app is in front.
|
||||
LaunchedEffect(instance.id) { lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { chats.watchReports() } }
|
||||
LaunchedEffect(open) {
|
||||
open?.let {
|
||||
@@ -275,6 +286,7 @@ class MainActivity : ComponentActivity() {
|
||||
// The title of each report whose conversation was opened, by its chat: what that chat's bar says.
|
||||
val reportTitles = remember { mutableStateMapOf<String, String>() }
|
||||
val menu: () -> Unit = { scope.launch { drawer.open() } }
|
||||
val filesAt: (String) -> Unit = { folder -> over("files-at/" + Uri.encode(folder)) }
|
||||
ModalNavigationDrawer(
|
||||
drawerState = drawer,
|
||||
// The drawer opens by a swipe only from a chat: elsewhere the swipe is Back's.
|
||||
@@ -292,6 +304,7 @@ class MainActivity : ComponentActivity() {
|
||||
onNewChat = { top("new") },
|
||||
onLeave = { top("new") },
|
||||
onOpened = { id -> top("chat/$id") },
|
||||
onFiles = filesAt,
|
||||
)
|
||||
}
|
||||
composable("new-agent") {
|
||||
@@ -311,9 +324,13 @@ class MainActivity : ComponentActivity() {
|
||||
onMenu = menu,
|
||||
onNewChat = { top("new") },
|
||||
onLeave = { top("new") },
|
||||
onFiles = filesAt,
|
||||
)
|
||||
}
|
||||
composable("files") { FilesScreen(onBack = { nav.popBackStack() }) }
|
||||
// Files at a folder: where a generated file's "Open in Files" leads.
|
||||
composable("files-at/{at}") { e -> FilesScreen(onBack = { nav.popBackStack() }, start = e.arguments?.getString("at")) }
|
||||
composable("mcp") { McpScreen(onBack = { nav.popBackStack() }) }
|
||||
composable("archived") {
|
||||
ArchivedScreen(onBack = { nav.popBackStack() }, onOpen = { top("chat/$it") }, onRestored = { chats.load() })
|
||||
}
|
||||
@@ -340,6 +357,7 @@ class MainActivity : ComponentActivity() {
|
||||
onNewChat = { top("new") },
|
||||
onLeave = { nav.popBackStack() },
|
||||
report = reportTitles[id].orEmpty(),
|
||||
onFiles = filesAt,
|
||||
)
|
||||
}
|
||||
composable("scheduled") {
|
||||
@@ -381,7 +399,7 @@ class MainActivity : ComponentActivity() {
|
||||
ScheduleEditScreen(e.arguments?.getString("id"), onBack = { nav.popBackStack() }, onSaved = { nav.popBackStack() })
|
||||
}
|
||||
composable("settings") {
|
||||
SettingsScreen(onBack = { nav.popBackStack() }, onAddInstance = { over("add") })
|
||||
SettingsScreen(onBack = { nav.popBackStack() }, onAddInstance = { over("add") }, onMcp = { over("mcp") })
|
||||
}
|
||||
// Signing in to one more instance makes it the one in use, which starts a
|
||||
// fresh navigation for it (the `key` above).
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.coroutines.CoroutineStart
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.KSerializer
|
||||
@@ -22,6 +26,7 @@ import okhttp3.RequestBody
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import okhttp3.Response
|
||||
import java.io.IOException
|
||||
import java.io.OutputStream
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlin.coroutines.resumeWithException
|
||||
|
||||
@@ -153,15 +158,19 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
|
||||
suspend fun models(chatId: String? = null): List<ModelInfo> = modelList(chatId).models
|
||||
|
||||
/** The models with the instance's subagent cap; with [chatId], whether each is offered subagents on that chat. */
|
||||
suspend fun modelList(chatId: String? = null): ModelList = get(if (chatId != null) "/models?chat=$chatId" else "/models")
|
||||
/**
|
||||
* The models with the instance's subagent cap; with [chatId], whether each is offered subagents
|
||||
* on that chat. Only models a chat can be on (`capability` `chat`): this list is what every
|
||||
* picker and the assistant's model setting are filled from.
|
||||
*/
|
||||
suspend fun modelList(chatId: String? = null): ModelList = get<ModelList>(if (chatId != null) "/models?chat=$chatId" else "/models").forChat()
|
||||
|
||||
/** The models for a new agent chat on [deviceId], with whether it may have subagents (`agent_subagents`). */
|
||||
suspend fun agentModelList(deviceId: String?, directory: String? = null): ModelList = get(
|
||||
suspend fun agentModelList(deviceId: String?, directory: String? = null): ModelList = get<ModelList>(
|
||||
"/models?kind=agent" + deviceId?.let { "&device=" + segment(it) }.orEmpty() +
|
||||
// With a directory (spec 3.9.0) the answer carries `start`: the model a chat there starts on.
|
||||
directory?.takeIf { deviceId != null && it.isNotBlank() }?.let { "&directory=" + segment(it.trim()) }.orEmpty(),
|
||||
)
|
||||
).forChat()
|
||||
|
||||
suspend fun folders(): List<Folder> = get<FolderList>("/folders").folders
|
||||
|
||||
@@ -333,6 +342,17 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* Send a message that waits (`queued`) now: the message as it is after, and the reply started
|
||||
* for it, as a message sent answers. 409 in the instance's words while a reply is being
|
||||
* written in the chat, and when the message no longer waits.
|
||||
*/
|
||||
suspend fun sendWaiting(chatId: String, messageId: String): Turn = send("POST", "/chats/$chatId/messages/${segment(messageId)}/send", DECLARED)
|
||||
|
||||
/** Withdraw a message that waits: its row is gone. 409 in words when it no longer waits, 404 when it is not there. */
|
||||
suspend fun discardWaiting(chatId: String, messageId: String): Discarded =
|
||||
call(authed("$v2/chats/$chatId/messages/${segment(messageId)}/discard").post(emptyBody()).build(), Discarded.serializer())
|
||||
|
||||
suspend fun regenerate(chatId: String, messageId: String): Turn = send("POST", "/chats/$chatId/messages/$messageId/regenerate", DECLARED)
|
||||
|
||||
suspend fun continueChat(chatId: String): Turn = send("POST", "/chats/$chatId/continue", DECLARED)
|
||||
@@ -600,6 +620,241 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
return call(authed(url.toString()).get().build(), FileContent.serializer())
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the file with node id [id] is now, after any rename or move: `GET /api/v2/files/node`.
|
||||
* A file the person may not read and an id that names nothing are the same 404; an instance
|
||||
* from before this route answers a 404 or a 405 of its own ([eu.llembas.android.ui.files.noSuchRoute]).
|
||||
*/
|
||||
suspend fun fileNode(id: String): FileNode = call(authed(filesUrl("/node", "id" to id)).get().build(), FileNode.serializer())
|
||||
|
||||
// --- The file manager's writes, the trash, versions and bytes ---------------------------------
|
||||
// Each write answers the listing of the directory it changed; a refusal is the tree's own
|
||||
// sentence (400), a path that cannot be read a 404, and both come back as an ApiException.
|
||||
|
||||
private fun filesUrl(path: String, vararg query: Pair<String, String?>): String = "$v2/files$path".toHttpUrl().newBuilder()
|
||||
.apply { query.forEach { (name, value) -> if (value != null) addQueryParameter(name, value) } }
|
||||
.build()
|
||||
.toString()
|
||||
|
||||
suspend fun makeFolder(dir: String, name: String): FileListing = send(
|
||||
"POST",
|
||||
"/files/mkdir",
|
||||
buildJsonObject {
|
||||
put("path", dir)
|
||||
put("name", name)
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun renameFile(path: String, name: String): FileListing = send(
|
||||
"POST",
|
||||
"/files/rename",
|
||||
buildJsonObject {
|
||||
put("path", path)
|
||||
put("name", name)
|
||||
},
|
||||
)
|
||||
|
||||
/** Copy [path] into the directory [to]; the answer's `copied` says what the copy is called. */
|
||||
suspend fun copyFile(path: String, to: String, name: String? = null): FileListing = send(
|
||||
"POST",
|
||||
"/files/copy",
|
||||
buildJsonObject {
|
||||
put("path", path)
|
||||
put("to", to)
|
||||
name?.let { put("name", it) }
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* Move or copy [paths] into the directory [to], or delete them (to the trash): `op` is
|
||||
* `move`, `copy` or `delete`. Each path is done by itself, so the answer is read for what
|
||||
* failed even though the request succeeded.
|
||||
*/
|
||||
suspend fun batchFiles(op: String, paths: List<String>, to: String? = null): BatchAnswer = send(
|
||||
"POST",
|
||||
"/files/batch",
|
||||
buildJsonObject {
|
||||
put("op", op)
|
||||
put("paths", JsonArray(paths.map { JsonPrimitive(it) }))
|
||||
to?.let { put("to", it) }
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* Save a text file. [base] is the `sha` the file had when it was opened: when it holds
|
||||
* something else by now the server writes nothing and this throws [SaveConflict] with its
|
||||
* sentence, unless [force]. Without a [base] nothing is compared, and a path with no file
|
||||
* makes one. With [create] the file must be new: where something is already at the path the
|
||||
* server writes nothing (409, `exists`) and this throws [FileExists] with its sentence -- an
|
||||
* older server knows no `create` and writes as before.
|
||||
*/
|
||||
suspend fun saveFile(path: String, text: String, base: String? = null, force: Boolean = false, create: Boolean = false): FileContent {
|
||||
val body = buildJsonObject {
|
||||
put("path", path)
|
||||
put("text", text)
|
||||
base?.takeIf { it.isNotBlank() }?.let { put("base", it) }
|
||||
if (force) put("force", true)
|
||||
if (create) put("create", true)
|
||||
}
|
||||
val request = authed("$v2/files/content").put(body.toString().toRequestBody(JSON)).build()
|
||||
return withContext(Dispatchers.IO) { http.newCall(request).await().use { response -> saved(response) } }
|
||||
}
|
||||
|
||||
/**
|
||||
* A new, empty text file called [name] in the directory [dir]; its path. Never over what
|
||||
* is there: `create` has the instance refuse a taken name ([FileExists], its sentence), and
|
||||
* because an instance from before `create` ignores the word and would empty the file, the
|
||||
* directory is read first and a name it holds is refused here, with nothing sent.
|
||||
*/
|
||||
suspend fun newFile(dir: String, name: String): String {
|
||||
val path = FileKinds.child(dir, name)
|
||||
if (files(dir).entries.any { it.name == name.trim() || it.path == path }) throw FileExists("")
|
||||
saveFile(path, "", create = true)
|
||||
return path
|
||||
}
|
||||
|
||||
/** A save's answer: the file as it is now, or what refused it. */
|
||||
private fun saved(response: Response): FileContent {
|
||||
val said = runCatching { response.body?.string().orEmpty() }.getOrDefault("")
|
||||
if (response.code == 409) {
|
||||
val conflict = runCatching { LembasJson.parseToJsonElement(said) as? JsonObject }.getOrNull() ?: JsonObject(emptyMap())
|
||||
if ((conflict["conflict"] as? JsonPrimitive)?.content == "true") {
|
||||
throw SaveConflict(refusal(said).orEmpty(), (conflict["sha"] as? JsonPrimitive)?.takeUnless { it is JsonNull }?.content.orEmpty())
|
||||
}
|
||||
// A new file whose name is taken: nothing was written, and the sentence says what is there.
|
||||
if ((conflict["exists"] as? JsonPrimitive)?.content == "true") throw FileExists(refusal(said).orEmpty())
|
||||
}
|
||||
if (!response.isSuccessful) throw ApiException(response.code, refusal(said) ?: "The server answered ${response.code}.")
|
||||
return LembasJson.decodeFromString(FileContent.serializer(), said)
|
||||
}
|
||||
|
||||
suspend fun trash(): TrashList = get("/files/trash")
|
||||
|
||||
suspend fun restoreTrashed(id: String): TrashList = send("POST", "/files/restore", buildJsonObject { put("id", id) })
|
||||
|
||||
/** Remove for good: the one thing named, or with no [id] everything in the trash. */
|
||||
suspend fun removeTrashed(id: String? = null): TrashList = call(authed(filesUrl("/trash", "id" to id)).delete().build(), TrashList.serializer())
|
||||
|
||||
suspend fun fileVersions(path: String): FileVersions = call(authed(filesUrl("/versions", "path" to path)).get().build(), FileVersions.serializer())
|
||||
|
||||
/** Make an older version the file again, as a new version: nothing is lost. */
|
||||
suspend fun restoreVersion(path: String, version: String): FileVersions = send(
|
||||
"POST",
|
||||
"/files/versions/restore",
|
||||
buildJsonObject {
|
||||
put("path", path)
|
||||
put("version", version)
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* Upload one file into the directory [dir], streamed: [body] writes the file's bytes as they
|
||||
* are read, so a large file is never held in memory. A file over the instance's limit is a
|
||||
* 413 whose sentence names it.
|
||||
*/
|
||||
suspend fun uploadFile(dir: String, name: String, body: RequestBody): FileListing {
|
||||
val form = MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("files", name, body).build()
|
||||
return call(authed(filesUrl("/upload", "path" to dir)).post(form).build(), FileListing.serializer())
|
||||
}
|
||||
|
||||
/**
|
||||
* The request for a file's bytes (`/files/raw`), or for [range] of them. The token goes in
|
||||
* the Authorization header, as on every call: the address names the path and nothing else.
|
||||
*/
|
||||
fun rawFile(path: String, range: LongRange? = null, inline: Boolean = false): Request = raw(Raw.Path(path), range, inline)
|
||||
|
||||
/**
|
||||
* The request for [what]'s bytes, or for [range] of them: a file of the tree by its path (one
|
||||
* [Raw.Path.version] of it, where named), a file by its node id wherever it is now, or a chat's
|
||||
* attachment. Always with the token in the header and never in the address.
|
||||
*/
|
||||
fun raw(what: Raw, range: LongRange? = null, inline: Boolean = false): Request = authed(
|
||||
when (what) {
|
||||
is Raw.Path -> filesUrl("/raw", "path" to what.path, "version" to what.version?.ifBlank { null }, "inline" to if (inline) "1" else null)
|
||||
is Raw.Node -> filesUrl("/raw", "node" to what.id, "inline" to if (inline) "1" else null)
|
||||
is Raw.Attached -> "$v2/attachments/${segment(what.id)}"
|
||||
},
|
||||
)
|
||||
.header("Accept", "*/*")
|
||||
.apply { range?.let { header("Range", "bytes=${it.first}-${it.last}") } }
|
||||
.get()
|
||||
.build()
|
||||
|
||||
/** The request for [paths] (files and folders) as one zip. */
|
||||
fun zipFiles(paths: List<String>): Request = authed("$v2/files/zip")
|
||||
.header("Accept", "*/*")
|
||||
.post(buildJsonObject { put("paths", JsonArray(paths.map { JsonPrimitive(it) })) }.toString().toRequestBody(JSON))
|
||||
.build()
|
||||
|
||||
/**
|
||||
* Run [request] and copy what it answers into [out] as it comes, saying how far it is
|
||||
* ([progress]: bytes so far, and the total when the server said one, else -1). At most
|
||||
* [most] bytes are taken: more than that is refused as a 413, with nothing more read.
|
||||
*/
|
||||
suspend fun download(request: Request, out: OutputStream, most: Long = Long.MAX_VALUE, progress: (done: Long, total: Long) -> Unit = { _, _ -> }): Long =
|
||||
withContext(Dispatchers.IO) {
|
||||
val call = http.newCall(request)
|
||||
val finished = java.util.concurrent.atomic.AtomicBoolean(false)
|
||||
// A read that waits for the server does not hear that the transfer was given up:
|
||||
// the call is cancelled from beside it, which ends the read at once.
|
||||
val watch = launch(start = CoroutineStart.UNDISPATCHED) {
|
||||
try {
|
||||
awaitCancellation()
|
||||
} finally {
|
||||
if (!finished.get()) call.cancel()
|
||||
}
|
||||
}
|
||||
try {
|
||||
call.await().use { response ->
|
||||
if (!response.isSuccessful) throw ApiException(response.code, detail(response))
|
||||
val body = response.body ?: throw ApiException(response.code, "")
|
||||
val total = body.contentLength()
|
||||
if (total > most) throw ApiException(413, "")
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
var done = 0L
|
||||
body.byteStream().use { stream ->
|
||||
while (true) {
|
||||
ensureActive()
|
||||
val n = stream.read(buffer)
|
||||
if (n < 0) break
|
||||
done += n
|
||||
if (done > most) throw ApiException(413, "")
|
||||
out.write(buffer, 0, n)
|
||||
progress(done, total)
|
||||
}
|
||||
}
|
||||
out.flush()
|
||||
done
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
// The read a cancelled call ends with is the cancelling, not a failure of the network.
|
||||
ensureActive()
|
||||
throw e
|
||||
} finally {
|
||||
// Ended by itself: the watcher is let go, and leaves the finished call alone.
|
||||
finished.set(true)
|
||||
watch.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The bytes `[from, to]` of a file, for a player or a table's first rows: a `Range` request,
|
||||
* blocking, on whatever thread asks (never the main one). A server that answers the whole
|
||||
* file to a range that does not start at 0 is refused rather than read from the wrong place.
|
||||
*/
|
||||
fun rawBytes(path: String, from: Long, to: Long): ByteArray = rawBytes(Raw.Path(path), from, to)
|
||||
|
||||
/** The same for any [Raw]: a file by its node id is read a piece at a time as one by its path is. */
|
||||
fun rawBytes(what: Raw, from: Long, to: Long): ByteArray = http.newCall(raw(what, from..to)).execute().use { response ->
|
||||
if (!response.isSuccessful) throw ApiException(response.code, detail(response))
|
||||
if (response.code != 206 && from > 0) throw ApiException(416, "")
|
||||
val want = to - from + 1
|
||||
response.body!!.source().use { source ->
|
||||
source.request(want)
|
||||
source.buffer.readByteArray(minOf(source.buffer.size, want))
|
||||
}
|
||||
}
|
||||
|
||||
/** A file of the tree in the web UI's own viewer (`/files/view`), for what the app does not draw. */
|
||||
fun webFile(path: String): String = "$base/files/view".toHttpUrl().newBuilder().addQueryParameter("path", path).build().toString()
|
||||
|
||||
@@ -610,6 +865,21 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
.build()
|
||||
.toString()
|
||||
|
||||
// --- Generated media's jobs, and the MCP servers ----------------------------------------------
|
||||
|
||||
/** A chat's long generations, newest first (at most 50); with [active] only those under way. */
|
||||
suspend fun mediaJobs(chatId: String, active: Boolean = false): List<MediaJob> =
|
||||
get<MediaJobList>("/media/jobs?chat_id=${segment(chatId)}" + if (active) "&active=true" else "").jobs
|
||||
|
||||
/** One job as it stands; somebody else's, or one that is gone, is a 404 in the server's words. */
|
||||
suspend fun mediaJob(id: String): MediaJob = get("/media/jobs/${segment(id)}")
|
||||
|
||||
/** Stop a job: the job as it is after. One that has ended stays what it was, so this is safe to repeat. */
|
||||
suspend fun cancelMediaJob(id: String): MediaJob = call(authed("$v2/media/jobs/${segment(id)}").delete().build(), MediaJob.serializer())
|
||||
|
||||
/** The MCP servers whose tools this person's chats may be offered, and how each is signed in to. */
|
||||
suspend fun mcpServers(): List<McpServer> = get<McpServerList>("/mcp").servers
|
||||
|
||||
// --- Push --------------------------------------------------------------------------------
|
||||
suspend fun pushKey(): PushKey = get("/push")
|
||||
|
||||
|
||||
@@ -136,11 +136,96 @@ enum class Drawn {
|
||||
* instruction, the line that opens a report's conversation) is not something the person said,
|
||||
* so it is never their bubble: a quiet note -- and in a report's conversation ([reportChat]) the
|
||||
* [first] such line, which only tells the model what the conversation continues, is left out,
|
||||
* since the report itself is one tap back.
|
||||
* since the report itself is one tap back. A turn the linked computer's harness started
|
||||
* (`origin` `harness`: a job's end, a team member's report) is such a line whatever else the
|
||||
* row says: nobody typed it, here or in a terminal.
|
||||
*/
|
||||
fun drawn(message: Message, first: Boolean, reportChat: Boolean): Drawn = when {
|
||||
!message.isUser -> Drawn.Reply
|
||||
!message.machine -> Drawn.Person
|
||||
!message.byMachine -> Drawn.Person
|
||||
reportChat && first -> Drawn.Hidden
|
||||
else -> Drawn.Note
|
||||
}
|
||||
|
||||
/** The `origin` of a turn the linked computer's harness started by itself. */
|
||||
const val ORIGIN_HARNESS = "harness"
|
||||
|
||||
/** The `origin` of a message handed to the linked computer whose arrival there was never heard. */
|
||||
const val ORIGIN_UNSURE = "unsure"
|
||||
|
||||
/**
|
||||
* Whether this is the person's message of which nobody knows whether it reached the linked
|
||||
* computer (`origin` `unsure`, waiting): the instance never sends it by itself, so it is not
|
||||
* "queued, two ahead" -- it says what it is, in the instance's sentence. Any other origin this
|
||||
* app does not know is drawn as none.
|
||||
*/
|
||||
val Message.fateUnknown: Boolean get() = isUser && queued && origin == ORIGIN_UNSURE
|
||||
|
||||
/** The `origin` of a message the linked computer has said it holds for its next turn. */
|
||||
const val ORIGIN_CARRIED = "carried"
|
||||
|
||||
/** Why a message of the person's has not been given to a model yet. */
|
||||
enum class Waiting {
|
||||
/** A reply was being written when it was sent: it goes when its turn comes. */
|
||||
Queued,
|
||||
|
||||
/** Handed to the linked computer, its arrival never heard: the instance never sends it by itself. */
|
||||
Unsure,
|
||||
|
||||
/** The linked computer holds it and takes it in with its next turn. */
|
||||
Carried,
|
||||
}
|
||||
|
||||
/**
|
||||
* How this message waits, or null for one that does not: a message of the person's with
|
||||
* `queued` true. Such a message is not a turn yet, so it is sent now or discarded, never
|
||||
* edited. An origin this app does not know waits as a plain queued one does.
|
||||
*/
|
||||
val Message.waiting: Waiting?
|
||||
get() = when {
|
||||
!isUser || !queued -> null
|
||||
origin == ORIGIN_UNSURE -> Waiting.Unsure
|
||||
origin == ORIGIN_CARRIED -> Waiting.Carried
|
||||
else -> Waiting.Queued
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether Edit is offered on this message of the person's: not while a reply is being
|
||||
* [writing], and never on one that still waits -- the instance refuses that, since it has not
|
||||
* been a turn yet and a linked computer may still hold its old words.
|
||||
*/
|
||||
fun Message.editable(writing: Boolean): Boolean = isUser && !writing && !queued
|
||||
|
||||
/** Whether nobody typed this row: the server wrote it (`machine`), or a device's harness did. */
|
||||
val Message.byMachine: Boolean get() = machine || origin == ORIGIN_HARNESS
|
||||
|
||||
/**
|
||||
* Whether [reply] is a finished reply that holds nothing at all and answers a turn nobody typed
|
||||
* ([asked], the row before it): what was said to that turn was never written into the chat
|
||||
* (instances from before the reply to a harness turn followed the device hold a few). One quiet
|
||||
* line says so in its place -- the server's rule for its own page, never a blank row with
|
||||
* buttons. A reply still being written, one that was stopped or failed, one that holds a plan
|
||||
* and nothing else, and an empty reply to something a person asked are not this.
|
||||
*
|
||||
* [live] is the reply this screen knows is being written, by its id: that one is never this,
|
||||
* whatever its row says. A row says `complete` only when the server does, and a row that says
|
||||
* nothing reads as complete ([Message.complete]); the rule does not rest on that alone.
|
||||
*/
|
||||
fun replyUnrecorded(reply: Message, asked: Message?, live: String? = null): Boolean = !reply.isUser &&
|
||||
reply.id != live &&
|
||||
reply.complete &&
|
||||
!reply.stopped &&
|
||||
reply.error.isNullOrBlank() &&
|
||||
reply.end == null &&
|
||||
reply.text.isNullOrBlank() &&
|
||||
reply.steps.isEmpty() &&
|
||||
reply.plan == null &&
|
||||
reply.attachments.isEmpty() &&
|
||||
asked != null &&
|
||||
asked.isUser &&
|
||||
asked.byMachine
|
||||
|
||||
/** The replies of [messages] that are [replyUnrecorded], by id; [live] is the one being written, if any. */
|
||||
fun unrecordedReplies(messages: List<Message>, live: String? = null): Set<String> = messages.indices
|
||||
.filter { replyUnrecorded(messages[it], messages.getOrNull(it - 1), live) }
|
||||
.mapTo(HashSet()) { messages[it].id }
|
||||
@@ -16,9 +16,13 @@ import java.util.concurrent.ConcurrentHashMap
|
||||
* the drawer's Reports badge, the Scheduled list -- instead of one each. It is open while
|
||||
* somebody watches and closed when nobody does.
|
||||
*
|
||||
* Every frame of the route is a whole state (`schedules`, `reports`), which the server sends at
|
||||
* A frame of the route is a whole state (`schedules`, `reports`), which the server sends at
|
||||
* once to a new connection. A watcher that joins a connection already open missed that, so it
|
||||
* is first told the last frame of each kind this connection carried.
|
||||
* is first told the last frame of each such kind this connection carried.
|
||||
*
|
||||
* `reply` is the exception ([MOMENTS]): something that happened, not how things are. It is
|
||||
* passed on to whoever is watching and never said again -- a watcher that joins later would
|
||||
* take a reply long finished for one that has just started.
|
||||
*
|
||||
* A route that refuses (an older server) ends quietly: its watchers hear nothing, as they did
|
||||
* when each asked for itself.
|
||||
@@ -36,11 +40,16 @@ class EventsHub(private val scope: CoroutineScope) {
|
||||
val shared = open()
|
||||
// A connection opened anew is told everything again: what the last one said is stale.
|
||||
.onStart { latest.clear() }
|
||||
.onEach { latest[it.event] = it }
|
||||
.onEach { if (it.event !in MOMENTS) latest[it.event] = it }
|
||||
.catch { }
|
||||
.shareIn(scope, SharingStarted.WhileSubscribed(), replay = 0)
|
||||
Line(key, shared, latest).also { line = it }
|
||||
}
|
||||
return now.frames.onSubscription { now.latest.values.toList().forEach { emit(it) } }
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** The frames that say something happened, rather than how things are: never told again to a late watcher. */
|
||||
val MOMENTS = setOf("reply")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import java.io.IOException
|
||||
|
||||
// The person's files as a file manager needs them: the shapes of the trash, the versions and a
|
||||
// batch (`contract/files_*.json`, `file_versions.json`, `file_save_conflict.json`), and what the
|
||||
// app decides from a file's kind without a phone: which viewer, a table's rows, a notebook's cells.
|
||||
|
||||
/** One thing in the trash: restored or removed for good by its [id]. */
|
||||
@Serializable
|
||||
data class TrashItem(
|
||||
val id: String = "",
|
||||
val name: String = "",
|
||||
val path: String = "",
|
||||
val kind: String = "file",
|
||||
val size: Long = 0,
|
||||
@SerialName("trashed_at") val trashedAt: String? = null,
|
||||
)
|
||||
|
||||
/** `GET /files/trash`, and what is left after a restore ([restored]: where it went back to) or a removal. */
|
||||
@Serializable
|
||||
data class TrashList(val items: List<TrashItem> = emptyList(), val restored: String? = null, val removed: Int = 0)
|
||||
|
||||
/** One version of a file, newest first in [FileVersions]; [current] is what the file holds now. */
|
||||
@Serializable
|
||||
data class FileVersion(
|
||||
val id: String = "",
|
||||
val sha: String = "",
|
||||
val size: Long = 0,
|
||||
val at: String? = null,
|
||||
val by: String? = null,
|
||||
@SerialName("chat_id") val chatId: String? = null,
|
||||
val current: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class FileVersions(val path: String = "", val sha: String = "", val versions: List<FileVersion> = emptyList())
|
||||
|
||||
/** One path of a batch: done ([ok], and where it is now) or refused, in the server's sentence. */
|
||||
@Serializable
|
||||
data class BatchResult(val path: String = "", val ok: Boolean = false, val to: String? = null, val error: String? = null)
|
||||
|
||||
/** `POST /files/batch`: never all-or-nothing, so [failed] is read even from a 200. */
|
||||
@Serializable
|
||||
data class BatchAnswer(val op: String = "", val to: String? = null, val results: List<BatchResult> = emptyList(), val done: Int = 0, val failed: Int = 0) {
|
||||
/** The server's sentences for what was refused, each once, at most [most]. */
|
||||
fun refusals(most: Int = 3): List<String> = results.filter { !it.ok }.mapNotNull { it.error?.ifBlank { null } }.distinct().take(most)
|
||||
}
|
||||
|
||||
/**
|
||||
* A save the server refused because the file changed since it was opened (409, `conflict: true`):
|
||||
* its sentence, and the [sha] the file holds now. Nothing was written.
|
||||
*/
|
||||
class SaveConflict(message: String, val sha: String) : IOException(message)
|
||||
|
||||
/** The viewer a file gets, by the server's word for what it is. */
|
||||
enum class FileView {
|
||||
/** Markdown, code, text, and the source of an HTML page or an SVG: drawn as text, editable. */
|
||||
Text,
|
||||
Image,
|
||||
Pdf,
|
||||
Audio,
|
||||
Video,
|
||||
Table,
|
||||
Notebook,
|
||||
|
||||
/** Nothing to draw here: what the file is, and Download, Open with, Share. */
|
||||
Details,
|
||||
}
|
||||
|
||||
object FileKinds {
|
||||
/** The kinds whose text the server hands over and the app may save back. */
|
||||
val TEXT = setOf("markdown", "code", "text", "html", "svg")
|
||||
|
||||
/**
|
||||
* The viewer for a file of [kind]. A server that does not say the kind (null) is read as
|
||||
* before: as text, and the content answer says when it is not. An SVG is its source -- the
|
||||
* app has no WebView and draws nothing a file could script.
|
||||
*/
|
||||
fun viewer(kind: String?): FileView = when (kind) {
|
||||
null, "", in TEXT -> FileView.Text
|
||||
"image" -> FileView.Image
|
||||
"pdf" -> FileView.Pdf
|
||||
"audio" -> FileView.Audio
|
||||
"video" -> FileView.Video
|
||||
"table" -> FileView.Table
|
||||
"notebook" -> FileView.Notebook
|
||||
else -> FileView.Details
|
||||
}
|
||||
|
||||
/** Whether the app offers to edit it: a text kind (a table too, as its text) the person may change. */
|
||||
fun editable(kind: String?, writable: Boolean?, withheld: Boolean): Boolean = writable == true && !withheld && (kind in TEXT || kind == "table")
|
||||
|
||||
/** Why [name] cannot be a file's or a folder's name, as the server would refuse it; false for a good one. */
|
||||
fun badName(name: String): Boolean = name.isBlank() || "/" in name || name.trim() in setOf(".", "..")
|
||||
|
||||
/** [name] inside the directory [dir]. */
|
||||
fun child(dir: String, name: String): String = dir.trimEnd('/') + "/" + name.trim()
|
||||
|
||||
/** The directory a path is in; `/` for a path at the top. */
|
||||
fun parent(path: String): String = path.trimEnd('/').substringBeforeLast('/', "").ifEmpty { "/" }
|
||||
|
||||
/** The last name of a path. */
|
||||
fun name(path: String): String = path.trimEnd('/').substringAfterLast('/').ifBlank { path }
|
||||
|
||||
/**
|
||||
* A name another app or a file system may be given: no separators, no control characters,
|
||||
* never empty, and at most [most] bytes as UTF-8 -- a file system counts a name in bytes
|
||||
* (255 of them), and a name in another script is three bytes a letter. A longer name loses
|
||||
* the end of its stem and keeps its extension, which is what says how to open it.
|
||||
*/
|
||||
fun safeName(name: String, most: Int = NAME_MAX_BYTES): String {
|
||||
val kept = name.map { if (it == '/' || it == '\\' || it.isISOControl()) '_' else it }.joinToString("").trim().trim('.').ifBlank { "file" }
|
||||
if (utf8(kept) <= most) return kept
|
||||
val dot = kept.lastIndexOf('.')
|
||||
// An extension is short; a last dot far from the end is a sentence's, and the name is cut as a whole.
|
||||
val ext = if (dot > 0 && utf8(kept.substring(dot)) <= minOf(EXTENSION_MAX_BYTES, most / 2)) kept.substring(dot) else ""
|
||||
val stem = kept.substring(0, kept.length - ext.length)
|
||||
val room = most - utf8(ext)
|
||||
val cut = StringBuilder()
|
||||
var used = 0
|
||||
var i = 0
|
||||
while (i < stem.length) {
|
||||
// By code point: half of a pair is not a character.
|
||||
val point = stem.codePointAt(i)
|
||||
val bytes = utf8(String(Character.toChars(point)))
|
||||
if (used + bytes > room) break
|
||||
cut.appendCodePoint(point)
|
||||
used += bytes
|
||||
i += Character.charCount(point)
|
||||
}
|
||||
return cut.toString().trimEnd().trimEnd('.').ifBlank { "file" } + ext
|
||||
}
|
||||
|
||||
private fun utf8(text: String): Int = text.toByteArray(Charsets.UTF_8).size
|
||||
|
||||
/** The longest name [safeName] gives, in bytes. */
|
||||
const val NAME_MAX_BYTES = 200
|
||||
private const val EXTENSION_MAX_BYTES = 24
|
||||
}
|
||||
|
||||
/** One thing an archive holds: its [name] is the archive's own text (a path inside it), [size] null for a folder and where the archive does not say. */
|
||||
@Serializable
|
||||
data class ArchiveEntry(val name: String = "", val size: Long? = null, val dir: Boolean = false)
|
||||
|
||||
/**
|
||||
* What is inside an archive, listed by the instance and never unpacked: at most 2000 [entries];
|
||||
* [total] how many it holds where it says; [truncated] when there are more than are listed.
|
||||
* [problem] is null, or why there is no listing (`unreadable`, `unsupported`, `busy`), with the
|
||||
* instance's sentence for it in [message].
|
||||
*/
|
||||
@Serializable
|
||||
data class ArchiveListing(
|
||||
val entries: List<ArchiveEntry> = emptyList(),
|
||||
val total: Int? = null,
|
||||
val truncated: Boolean = false,
|
||||
val problem: String? = null,
|
||||
val message: String = "",
|
||||
)
|
||||
|
||||
/**
|
||||
* Where a file known by its id is now (`GET /files/node?id=`): [parent] is the directory to
|
||||
* list, [path] the file. [trashed]: it is in the trash, and [path] is where it lay.
|
||||
*/
|
||||
@Serializable
|
||||
data class FileNode(
|
||||
val id: String = "",
|
||||
val path: String = "",
|
||||
val name: String = "",
|
||||
val parent: String = "",
|
||||
val kind: String = "",
|
||||
@SerialName("file_kind") val fileKind: String? = null,
|
||||
val trashed: Boolean = false,
|
||||
)
|
||||
|
||||
/** Where "Open in Files" leads for a file a chat names by its id. */
|
||||
sealed interface Whereabouts {
|
||||
/** The directory to open: where the file is now. */
|
||||
data class Folder(val path: String) : Whereabouts
|
||||
|
||||
/** It is in the trash: no directory holds it. */
|
||||
data object Trashed : Whereabouts
|
||||
}
|
||||
|
||||
/**
|
||||
* Where to go for a file last known at [written], from what the instance says of its node
|
||||
* ([node]; null from an instance that cannot say): the directory it is in now -- it may have
|
||||
* been renamed or moved -- else the one it was written to.
|
||||
*/
|
||||
fun whereabouts(node: FileNode?, written: String): Whereabouts = when {
|
||||
node == null -> Whereabouts.Folder(FileKinds.parent(written))
|
||||
node.trashed -> Whereabouts.Trashed
|
||||
else -> Whereabouts.Folder(node.parent.ifBlank { FileKinds.parent(node.path.ifBlank { written }) })
|
||||
}
|
||||
|
||||
/** A table's first rows and columns; [cut] when the file has more than is laid out. */
|
||||
data class Table(val rows: List<List<String>>, val columns: Int, val cut: Boolean)
|
||||
|
||||
/**
|
||||
* A CSV or TSV file as rows of cells: quoted cells, doubled quotes and line breaks inside quotes
|
||||
* as RFC 4180 has them. At most [maxRows] rows of at most [maxColumns] cells are kept, each cell
|
||||
* at most [maxCell] characters -- a table is for looking at, the text has all of it. [partial]:
|
||||
* the text is only the file's beginning, so its last line may be half a row and is left out.
|
||||
*/
|
||||
fun parseTable(text: String, delimiter: Char, maxRows: Int = 500, maxColumns: Int = 40, maxCell: Int = 200, partial: Boolean = false): Table {
|
||||
val rows = mutableListOf<List<String>>()
|
||||
var row = mutableListOf<String>()
|
||||
val cell = StringBuilder()
|
||||
var quoted = false
|
||||
var cut = partial
|
||||
var widest = 0
|
||||
var i = 0
|
||||
|
||||
fun endCell() {
|
||||
if (row.size < maxColumns) row += cell.toString().take(maxCell) else cut = true
|
||||
cell.setLength(0)
|
||||
}
|
||||
|
||||
fun endRow(): Boolean {
|
||||
endCell()
|
||||
if (row.size > 1 || row[0].isNotEmpty()) {
|
||||
rows += row
|
||||
widest = maxOf(widest, row.size)
|
||||
}
|
||||
row = mutableListOf()
|
||||
return rows.size < maxRows
|
||||
}
|
||||
|
||||
var open = true
|
||||
while (i < text.length) {
|
||||
val c = text[i]
|
||||
when {
|
||||
quoted && c == '"' && i + 1 < text.length && text[i + 1] == '"' -> {
|
||||
cell.append('"')
|
||||
i++
|
||||
}
|
||||
|
||||
c == '"' && (quoted || cell.isEmpty()) -> quoted = !quoted
|
||||
|
||||
!quoted && c == delimiter -> endCell()
|
||||
|
||||
!quoted && (c == '\n' || c == '\r') -> {
|
||||
if (c == '\r' && i + 1 < text.length && text[i + 1] == '\n') i++
|
||||
if (!endRow()) {
|
||||
cut = cut || i + 1 < text.length
|
||||
open = false
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
else -> if (cell.length <= maxCell) cell.append(c)
|
||||
}
|
||||
i++
|
||||
}
|
||||
// What is left after the last line break: a whole last row, unless the text was cut short.
|
||||
if (open && !partial && (cell.isNotEmpty() || row.isNotEmpty())) endRow()
|
||||
return Table(rows, widest, cut)
|
||||
}
|
||||
|
||||
/** The delimiter a table file is cut by: a tab for `.tsv` (or a first line with tabs and no commas), else a comma. */
|
||||
fun tableDelimiter(name: String, text: String): Char {
|
||||
if (name.endsWith(".tsv", ignoreCase = true) || name.endsWith(".tab", ignoreCase = true)) return '\t'
|
||||
val first = text.lineSequence().firstOrNull().orEmpty()
|
||||
return if ('\t' in first && ',' !in first) {
|
||||
'\t'
|
||||
} else if (';' in first && ',' !in first) {
|
||||
';'
|
||||
} else {
|
||||
','
|
||||
}
|
||||
}
|
||||
|
||||
/** One cell of a notebook, as text: its [source], and what it printed ([output], plain text only). */
|
||||
data class NotebookCell(val kind: String, val source: String, val output: String = "", val count: Int? = null, val cut: Boolean = false)
|
||||
|
||||
/** A notebook's first cells; [more]: how many are not shown. Null from [parseNotebook]: not a notebook. */
|
||||
data class Notebook(val cells: List<NotebookCell>, val more: Int = 0, val language: String = "")
|
||||
|
||||
/**
|
||||
* A Jupyter notebook, read-only, as text and nothing else: a cell's source, and of its outputs
|
||||
* only the plain text (a stream, `text/plain`, an error's name and value). HTML, pictures and
|
||||
* scripts in an output are not drawn and not kept. Null for a file that is not a notebook.
|
||||
*/
|
||||
fun parseNotebook(text: String, maxCells: Int = 200, maxChars: Int = 20_000): Notebook? {
|
||||
val root = runCatching { LembasJson.parseToJsonElement(text) as? JsonObject }.getOrNull() ?: return null
|
||||
val cells = root["cells"] as? JsonArray ?: return null
|
||||
|
||||
fun words(of: JsonElement?): String = when (of) {
|
||||
is JsonPrimitive -> if (of.isString) of.content else ""
|
||||
is JsonArray -> of.joinToString("") { (it as? JsonPrimitive)?.takeIf { p -> p.isString }?.content.orEmpty() }
|
||||
else -> ""
|
||||
}
|
||||
|
||||
fun printed(cell: JsonObject): String = (cell["outputs"] as? JsonArray).orEmpty().mapNotNull { it as? JsonObject }.joinToString("") { out ->
|
||||
when ((out["output_type"] as? JsonPrimitive)?.content) {
|
||||
"stream" -> words(out["text"])
|
||||
"error" -> listOf(words(out["ename"]), words(out["evalue"])).filter { it.isNotBlank() }.joinToString(": ") + "\n"
|
||||
else -> words((out["data"] as? JsonObject)?.get("text/plain")).let { if (it.isEmpty() || it.endsWith("\n")) it else it + "\n" }
|
||||
}
|
||||
}.trimEnd('\n')
|
||||
|
||||
val language = (((root["metadata"] as? JsonObject)?.get("kernelspec") as? JsonObject)?.get("language") as? JsonPrimitive)?.content
|
||||
?: ((((root["metadata"] as? JsonObject)?.get("language_info") as? JsonObject)?.get("name")) as? JsonPrimitive)?.content
|
||||
val read = cells.mapNotNull { it as? JsonObject }.take(maxCells).map { cell ->
|
||||
val source = words(cell["source"])
|
||||
val output = printed(cell)
|
||||
NotebookCell(
|
||||
kind = (cell["cell_type"] as? JsonPrimitive)?.content ?: "code",
|
||||
source = source.take(maxChars),
|
||||
output = output.take(maxChars),
|
||||
count = (cell["execution_count"] as? JsonPrimitive)?.content?.toIntOrNull(),
|
||||
cut = source.length > maxChars || output.length > maxChars,
|
||||
)
|
||||
}
|
||||
return Notebook(read, more = (cells.size - read.size).coerceAtLeast(0), language = language.orEmpty())
|
||||
}
|
||||
|
||||
/**
|
||||
* How much smaller a picture of [width] × [height] is decoded (a power of two, `inSampleSize`):
|
||||
* so its longer edge is at most about [edge] and it holds at most [pixels] pixels, whatever the
|
||||
* file claims. A picture of 30 000 × 30 000 is then a few megabytes in memory, not gigabytes.
|
||||
*/
|
||||
fun sampleFor(width: Int, height: Int, edge: Int = 2560, pixels: Long = 8_000_000): Int {
|
||||
if (width <= 0 || height <= 0) return 1
|
||||
var sample = 1
|
||||
while (maxOf(width, height) / sample > edge || (width.toLong() / sample) * (height.toLong() / sample) > pixels) sample *= 2
|
||||
return sample
|
||||
}
|
||||
|
||||
/**
|
||||
* A file read a piece at a time, for a player that seeks: [fetch] gets the bytes `[from, to]`
|
||||
* (a `Range` request with the token in its header), a few blocks are kept, and a read is
|
||||
* answered from the block its position is in. [length] is the file's size as the server said it.
|
||||
*/
|
||||
class RangeReader(private val length: Long, private val block: Int = BLOCK, private val keep: Int = 6, private val fetch: (from: Long, to: Long) -> ByteArray) {
|
||||
private val blocks = object : LinkedHashMap<Long, ByteArray>(keep, 0.75f, true) {
|
||||
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, ByteArray>?): Boolean = size > keep
|
||||
}
|
||||
|
||||
/** Up to [size] bytes from [position] into [buffer] at [offset]; -1 at or past the end. */
|
||||
@Synchronized
|
||||
fun read(position: Long, buffer: ByteArray, offset: Int, size: Int): Int {
|
||||
if (position < 0 || position >= length) return -1
|
||||
if (size <= 0) return 0
|
||||
val index = position / block
|
||||
val start = index * block
|
||||
val bytes = blocks[index] ?: fetch(start, minOf(start + block, length) - 1).also { blocks[index] = it }
|
||||
val within = (position - start).toInt()
|
||||
if (within >= bytes.size) return -1
|
||||
val n = minOf(size, bytes.size - within)
|
||||
System.arraycopy(bytes, within, buffer, offset, n)
|
||||
return n
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun close() = blocks.clear()
|
||||
|
||||
companion object {
|
||||
const val BLOCK = 512 * 1024
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
// What a model made, as the app is told of it (`contract/tool_media.json`, `media_job*.json`,
|
||||
// `mcp_servers.json`): a tool call's typed result, a long generation's job, and -- because they
|
||||
// arrived with the same server -- the instance's MCP servers and how each is signed in to.
|
||||
|
||||
/**
|
||||
* A file a tool call made: [kind] is what was asked for (`image`, `image_edit`, `video`, `music`,
|
||||
* `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.
|
||||
*/
|
||||
@Serializable
|
||||
data class GeneratedMedia(
|
||||
val kind: String = "",
|
||||
val path: String = "",
|
||||
@SerialName("node_id") val nodeId: String = "",
|
||||
@SerialName("version_id") val versionId: String = "",
|
||||
val name: String = "",
|
||||
val mime: String = "",
|
||||
val size: Long = 0,
|
||||
val width: Int = 0,
|
||||
val height: Int = 0,
|
||||
val seconds: Double = 0.0,
|
||||
) {
|
||||
/** How the card shows it, by what was asked for: 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
|
||||
else -> MediaView.Details
|
||||
}
|
||||
|
||||
/** What to call it: its name, else the last name of its path. */
|
||||
val title: String get() = name.ifBlank { FileKinds.name(path) }
|
||||
|
||||
/** Where its bytes are asked for: by its id, which outlives a rename or a move; by its path from a result without one. */
|
||||
val raw: Raw get() = if (nodeId.isNotBlank()) Raw.Node(nodeId) else Raw.Path(path)
|
||||
|
||||
/** The folder of the person's Files it was written to. */
|
||||
val folder: String get() = FileKinds.parent(path)
|
||||
}
|
||||
|
||||
/** 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 }
|
||||
|
||||
/** The job a tool call started (`media_job`): [state] as it was when the call returned. */
|
||||
@Serializable
|
||||
data class MediaJobRef(val id: String = "", val kind: String = "", val state: String = "")
|
||||
|
||||
/** What a finished job was counted as; an empty [currency] is the instance's own. */
|
||||
@Serializable
|
||||
data class MediaCost(val amount: Double = 0.0, val currency: String = "")
|
||||
|
||||
/**
|
||||
* A long generation (`GET /media/jobs/{id}`): `queued` and `running` are under way, `done` has
|
||||
* its [result], `failed`, `cancelled` and `expired` say why in [error] -- the server's sentence,
|
||||
* for the person. [seconds] is how long it has taken so far, or took. [told]: the chat was woken
|
||||
* with a reply about it.
|
||||
*/
|
||||
@Serializable
|
||||
data class MediaJob(
|
||||
val id: String = "",
|
||||
val kind: String = "",
|
||||
val state: String = "",
|
||||
val active: Boolean = false,
|
||||
@SerialName("chat_id") val chatId: String? = null,
|
||||
@SerialName("message_id") val messageId: String? = null,
|
||||
val source: String = "",
|
||||
val prompt: String = "",
|
||||
val started: String? = null,
|
||||
val ended: String? = null,
|
||||
val deadline: String? = null,
|
||||
val seconds: Double = 0.0,
|
||||
val error: String = "",
|
||||
val result: GeneratedMedia? = null,
|
||||
val cost: MediaCost? = null,
|
||||
val told: Boolean = false,
|
||||
) {
|
||||
/** Still to end: by the server's word, or by a state that is one of the two that are under way. */
|
||||
val underWay: Boolean get() = active || state in ACTIVE
|
||||
|
||||
/** Ended some way other than with a file. */
|
||||
val unsuccessful: Boolean get() = !underWay && state != DONE
|
||||
|
||||
companion object {
|
||||
val ACTIVE = setOf("queued", "running")
|
||||
const val DONE = "done"
|
||||
const val CANCELLED = "cancelled"
|
||||
|
||||
/** A job known only by the call that started it. */
|
||||
fun of(ref: MediaJobRef): MediaJob = MediaJob(id = ref.id, kind = ref.kind, state = ref.state, active = ref.state in ACTIVE)
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class MediaJobList(val jobs: List<MediaJob> = emptyList())
|
||||
|
||||
/**
|
||||
* A new file that was not made because something is already called that (409, `exists: true`):
|
||||
* the server's sentence. Nothing was written.
|
||||
*/
|
||||
class FileExists(message: String) : java.io.IOException(message)
|
||||
|
||||
/**
|
||||
* How an MCP server is signed in to: [kind] `none`, `secret` or `oauth`; [state] `ready`,
|
||||
* `signed_in`, `signed_out` or `needs_signin`. [account] is who the provider says signed in -- a
|
||||
* stranger's text, drawn as plain text. [signinUrl] is a page of the instance to open in a
|
||||
* browser, where the person signs in to the instance itself with its cookie: the app's token is
|
||||
* never part of it.
|
||||
*/
|
||||
@Serializable
|
||||
data class McpAuth(
|
||||
val kind: String = "none",
|
||||
val state: String = "ready",
|
||||
val shared: Boolean = false,
|
||||
val account: String = "",
|
||||
@SerialName("expires_at") val expiresAt: String? = null,
|
||||
val renews: Boolean = false,
|
||||
@SerialName("signin_url") val signinUrl: String? = null,
|
||||
) {
|
||||
/** The server's tools are not offered until somebody signs in. */
|
||||
val needsSignIn: Boolean get() = state == "signed_out" || state == "needs_signin"
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class McpServer(val id: String = "", val slug: String = "", val name: String = "", val tools: Int = 0, val auth: McpAuth = McpAuth()) {
|
||||
val label: String get() = name.ifBlank { slug.ifBlank { id } }
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class McpServerList(val servers: List<McpServer> = emptyList())
|
||||
|
||||
/**
|
||||
* The address the browser is sent to for a sign-in: always a page of the instance the app is
|
||||
* signed in to ([base]). An address on that origin is taken as it is; a path alone, or an
|
||||
* address the instance wrote with another name for itself, is that path on [base] -- so nothing
|
||||
* the list says can send the person to another host. Null for no address, or one that is no
|
||||
* http(s) page.
|
||||
*/
|
||||
fun signInAddress(base: String, url: String?): String? {
|
||||
val said = url?.trim().orEmpty()
|
||||
if (said.isEmpty()) return null
|
||||
val want = runCatching { java.net.URI(said) }.getOrNull() ?: return null
|
||||
val home = runCatching { java.net.URI(base) }.getOrNull() ?: return null
|
||||
if (want.scheme != null && want.scheme.lowercase() !in setOf("http", "https")) return null
|
||||
val path = want.rawPath.orEmpty()
|
||||
if (!path.startsWith("/") || path.startsWith("//")) return null
|
||||
|
||||
fun port(u: java.net.URI) = when {
|
||||
u.port >= 0 -> u.port
|
||||
u.scheme.equals("https", true) -> 443
|
||||
else -> 80
|
||||
}
|
||||
val same = want.scheme != null && want.scheme.equals(home.scheme, true) && want.host != null && want.host.equals(home.host, true) &&
|
||||
port(want) == port(home) && want.userInfo == null
|
||||
return if (same) said else base.trimEnd('/') + path + want.rawQuery?.let { "?$it" }.orEmpty()
|
||||
}
|
||||
|
||||
/** Which bytes of the instance are asked for: a file of the tree (or one version of it), a file by its id, or a chat's attachment. */
|
||||
sealed interface Raw {
|
||||
data class Path(val path: String, val version: String? = null) : Raw
|
||||
|
||||
/** A file by its node id, wherever it is now: what a generated file's result carries. */
|
||||
data class Node(val id: String) : Raw
|
||||
|
||||
/** A chat's attachment. Answered whole: a player gets a copy, not a stream. */
|
||||
data class Attached(val id: String) : Raw
|
||||
}
|
||||
@@ -127,7 +127,16 @@ data class ModelInfo(
|
||||
val provider: String = "",
|
||||
/** The connection's name, for telling two models with one [id] apart. */
|
||||
val connection: String = "",
|
||||
/**
|
||||
* What the model is for (server 2.0.0-beta.17): `chat`, or a word for something a chat cannot
|
||||
* start on (`embedding`, and later `image`, `video`, …). A server that does not say it offers
|
||||
* only models to chat with.
|
||||
*/
|
||||
val capability: String = CHAT,
|
||||
) {
|
||||
/** Whether a chat can be on it: the one capability this app's pickers offer. An unknown word is not one. */
|
||||
val forChat: Boolean get() = capability == CHAT
|
||||
|
||||
/** What this model is chosen, kept and sent by: its [ref], or its [id] from a server without refs. */
|
||||
val key: String get() = ref.ifBlank { id }
|
||||
|
||||
@@ -162,9 +171,13 @@ data class ModelInfo(
|
||||
|
||||
companion object {
|
||||
val CONTROLS = setOf("none", "switch", "slider")
|
||||
const val CHAT = "chat"
|
||||
}
|
||||
}
|
||||
|
||||
/** The models a chat can be on, of a list: what every model picker and the assistant's model setting offer. */
|
||||
fun List<ModelInfo>.forChat(): List<ModelInfo> = filter { it.forChat }
|
||||
|
||||
/**
|
||||
* The model a name means, in a list: by its `ref`, else the first with that `id` -- which is
|
||||
* what a bare id names on the server too. So a name kept from before refs (a setting, a chat's
|
||||
@@ -175,6 +188,37 @@ fun List<ModelInfo>.named(name: String?): ModelInfo? {
|
||||
return firstOrNull { it.ref == name } ?: firstOrNull { it.id == name }
|
||||
}
|
||||
|
||||
/**
|
||||
* The model a kept name means when it is known how the name was said. A name the server said as
|
||||
* a `model_ref` ([isRef]) is looked up as a ref and nothing else: an id may itself hold a slash
|
||||
* (a model of an aggregator, `openai/gpt`), so a ref whose model has left the list could
|
||||
* otherwise "find" another connection's model that happens to be called that. A name of
|
||||
* unknown kind -- a setting, a pick -- goes through [named].
|
||||
*/
|
||||
fun List<ModelInfo>.named(name: String?, isRef: Boolean): ModelInfo? = if (isRef) firstOrNull { !name.isNullOrBlank() && it.ref == name } else named(name)
|
||||
|
||||
/**
|
||||
* The model a chat, a reply or a schedule is on, in a list. The server says the id (`model`) and,
|
||||
* where it knows it, which connection serves it (`model_ref`). With a [ref] the model is the one
|
||||
* with that ref and no other: one that is not in the list is no model here, never "the first
|
||||
* with that id" -- that would name the wrong connection. Without one (an older server, or a
|
||||
* connection that is gone) the bare [id] is all there is.
|
||||
*/
|
||||
fun List<ModelInfo>.serving(ref: String?, id: String?): ModelInfo? = if (ref.isNullOrBlank()) named(id) else firstOrNull { it.ref == ref }
|
||||
|
||||
/** What such a thing's model is kept and sent by: its [ref] where the server says one, else its [id]; null for neither. */
|
||||
fun modelKey(ref: String?, id: String?): String? = ref?.ifBlank { null } ?: id?.ifBlank { null }
|
||||
|
||||
/**
|
||||
* The quiet line under a reply: the model's [id] as before, and its connection only where the
|
||||
* reply says which one ([ref]) and another model here shares the id. Null when there is no id.
|
||||
*/
|
||||
fun List<ModelInfo>.replyModel(ref: String?, id: String?): String? {
|
||||
val said = id?.ifBlank { null } ?: return null
|
||||
val model = firstOrNull { !ref.isNullOrBlank() && it.ref == ref } ?: return said
|
||||
return twinTitle(said, model.connection, count { it.id == model.id } > 1)
|
||||
}
|
||||
|
||||
/** A model's name in a list of [all]: with its connection where another model there shares its id. */
|
||||
fun ModelInfo.titleAmong(all: List<ModelInfo>): String = twinTitle(name.ifBlank { id }, connection, all.count { it.id == id } > 1)
|
||||
|
||||
@@ -190,7 +234,10 @@ data class ModelList(
|
||||
@SerialName("agent_subagents") val agentSubagents: AgentSubagents? = null,
|
||||
/** With `kind=agent`, a device and a directory (spec 3.9.0): the model a new agent chat there starts on. */
|
||||
val start: StartModel? = null,
|
||||
)
|
||||
) {
|
||||
/** The same answer with only the models a chat can be on. */
|
||||
fun forChat(): ModelList = if (models.all { it.forChat }) this else copy(models = models.forChat())
|
||||
}
|
||||
|
||||
/**
|
||||
* A new agent chat's Subagents fact (`/models?kind=agent&device=`): [offered] where the instance
|
||||
@@ -352,6 +399,8 @@ data class Chat(
|
||||
val kind: String = "chat",
|
||||
val title: String = "",
|
||||
val model: String = "",
|
||||
/** Which connection serves [model] (`provider/model`); null from an older server, or when that connection is gone. */
|
||||
@SerialName("model_ref") val modelRef: String? = null,
|
||||
@SerialName("folder_id") val folderId: String? = null,
|
||||
val pinned: Boolean = false,
|
||||
val archived: Boolean = false,
|
||||
@@ -379,6 +428,9 @@ data class Chat(
|
||||
) {
|
||||
val isAgent: Boolean get() = kind == "agent"
|
||||
|
||||
/** The chat's model as it is looked up and sent: its ref, else its id. */
|
||||
val modelKey: String? get() = modelKey(modelRef, model)
|
||||
|
||||
fun allows(control: String): Boolean = controls?.contains(control) ?: true
|
||||
}
|
||||
|
||||
@@ -401,6 +453,16 @@ data class ChatPage(val chats: List<Chat> = emptyList(), val more: Boolean = fal
|
||||
@Serializable
|
||||
data class ChatDetail(val chat: Chat, val messages: List<Message> = emptyList(), val more: Boolean = false, val live: String? = null)
|
||||
|
||||
/**
|
||||
* `GET /events`, frame `reply`: a reply started in the chat [chatId] -- whoever started it, this
|
||||
* app's own too -- and, with [live] false, that it is over (`event_reply_end.json`): once per
|
||||
* reply, however it ended; a reply shorter than the news of its start is said by that one frame
|
||||
* alone. [messageId] is the reply's row. An event, not a state: a start is said once (and, on a
|
||||
* connection just opened, for every reply being written then), an end once and never again.
|
||||
*/
|
||||
@Serializable
|
||||
data class ReplyFrame(@SerialName("chat_id") val chatId: String = "", @SerialName("message_id") val messageId: String = "", val live: Boolean = false)
|
||||
|
||||
@Serializable
|
||||
data class MessagePage(val messages: List<Message> = emptyList(), val more: Boolean = false)
|
||||
|
||||
@@ -483,6 +545,10 @@ data class ToolCall(
|
||||
val show: ShowCard? = null,
|
||||
/** `image_generate`'s picture: the server's own attachment, by id, and its size. */
|
||||
val image: GeneratedImage? = null,
|
||||
/** The file the call made (a picture, video, music, a 3D model), which is in the person's Files. */
|
||||
val media: GeneratedMedia? = null,
|
||||
/** A generation that takes minutes: the job the call started, as it was when the call returned. */
|
||||
@SerialName("media_job") val mediaJob: MediaJobRef? = null,
|
||||
val block: ToolBlock = ToolBlock(),
|
||||
)
|
||||
|
||||
@@ -536,6 +602,12 @@ data class FileEntry(
|
||||
val name: String = "",
|
||||
val path: String = "",
|
||||
val kind: String = "file",
|
||||
/**
|
||||
* What the file is, read by the server from its name and its own bytes: `markdown`, `code`,
|
||||
* `text`, `html`, `image`, `svg`, `pdf`, `audio`, `video`, `table`, `notebook`, `model3d`,
|
||||
* `archive` or `binary`. Null for a folder, and from a server that does not say it.
|
||||
*/
|
||||
@SerialName("file_kind") val fileKind: String? = null,
|
||||
val size: Long = 0,
|
||||
val mime: String = "",
|
||||
@SerialName("updated_at") val updatedAt: String? = null,
|
||||
@@ -546,7 +618,13 @@ data class FileEntry(
|
||||
|
||||
/** A directory, through the person's own access. `parent` is null at `/`. */
|
||||
@Serializable
|
||||
data class FileListing(val path: String = "/", val parent: String? = null, val entries: List<FileEntry> = emptyList())
|
||||
data class FileListing(
|
||||
val path: String = "/",
|
||||
val parent: String? = null,
|
||||
val entries: List<FileEntry> = emptyList(),
|
||||
/** After a copy: the new entry, under the name the server gave it (a taken name is numbered). */
|
||||
val copied: FileEntry? = null,
|
||||
)
|
||||
|
||||
/** Why a file's text did not come: `reason` is `not_text` or `too_large`; `message` says it. */
|
||||
@Serializable
|
||||
@@ -563,10 +641,17 @@ data class FileContent(
|
||||
val size: Long = 0,
|
||||
val mime: String = "",
|
||||
val kind: String = "text",
|
||||
/** What the file is ([FileEntry.fileKind]); null from a server that does not say it. */
|
||||
@SerialName("file_kind") val fileKind: String? = null,
|
||||
/** Whether the person may change it; null from a server that does not say (then: no editing). */
|
||||
val writable: Boolean? = null,
|
||||
val language: String = "",
|
||||
/** What the file holds now: sent back as a save's `base`, so a save over somebody else's change is refused. */
|
||||
val sha: String = "",
|
||||
val text: String = "",
|
||||
val withheld: Withheld? = null,
|
||||
/** What is inside an archive, as far as the instance lists it; null for every other kind and from a server that does not say. */
|
||||
val archive: ArchiveListing? = null,
|
||||
) {
|
||||
/** The kind the viewer draws, by the `show` card's rule: anything unknown is plain text. */
|
||||
val viewKind: String get() = if (kind in ShowCard.VIEW_KINDS) kind else "text"
|
||||
@@ -624,6 +709,8 @@ data class Message(
|
||||
val machine: Boolean = false,
|
||||
val origin: String = "",
|
||||
val model: String? = null,
|
||||
/** Which connection wrote this reply (see [Chat.modelRef]). */
|
||||
@SerialName("model_ref") val modelRef: String? = null,
|
||||
val attachments: List<Attachment> = emptyList(),
|
||||
val text: String? = null,
|
||||
val steps: List<Step> = emptyList(),
|
||||
@@ -638,6 +725,10 @@ data class Message(
|
||||
@Serializable
|
||||
data class Turn(val message: Message? = null, val reply: Message? = null)
|
||||
|
||||
/** The answer to discarding a waiting message: the row that is gone, by its id. */
|
||||
@Serializable
|
||||
data class Discarded(val id: String = "", val discarded: Boolean = false)
|
||||
|
||||
@Serializable
|
||||
data class NewChat(val chat: Chat, val message: Message? = null, val reply: Message? = null)
|
||||
|
||||
|
||||
@@ -23,6 +23,8 @@ data class RunModel(
|
||||
val name: String? = null,
|
||||
val reason: String? = null,
|
||||
@SerialName("switched_from") val switchedFrom: String? = null,
|
||||
/** Which connection served the run (`provider/model`); null from an older server. */
|
||||
val ref: String? = null,
|
||||
) {
|
||||
/** What to call it: its name, else its id. */
|
||||
val label: String? get() = name ?: id
|
||||
@@ -115,6 +117,8 @@ data class Schedule(
|
||||
@SerialName("catch_up") val catchUp: String = "",
|
||||
@SerialName("grace_minutes") val graceMinutes: Int? = null,
|
||||
val model: String? = null,
|
||||
/** Which connection serves [model] (`provider/model`); null from an older server, or with no model of its own. */
|
||||
@SerialName("model_ref") val modelRef: String? = null,
|
||||
val effort: String? = null,
|
||||
val agents: Int? = null,
|
||||
val tools: List<String> = emptyList(),
|
||||
@@ -132,6 +136,9 @@ data class Schedule(
|
||||
@SerialName("created_at") val createdAt: String? = null,
|
||||
) {
|
||||
val paused: Boolean get() = !enabled
|
||||
|
||||
/** The schedule's model as a form holds and sends it: its ref, else its id. */
|
||||
val modelKey: String? get() = modelKey(modelRef, model)
|
||||
}
|
||||
|
||||
@Serializable
|
||||
@@ -210,6 +217,21 @@ fun List<SchedulingModel>.named(name: String?): SchedulingModel? {
|
||||
return firstOrNull { it.ref == name } ?: firstOrNull { it.id == name }
|
||||
}
|
||||
|
||||
/** The same when it is known that the server said the name as a `model_ref` ([isRef]): then by ref alone, never by an id that looks like it. */
|
||||
fun List<SchedulingModel>.named(name: String?, isRef: Boolean): SchedulingModel? =
|
||||
if (isRef) firstOrNull { !name.isNullOrBlank() && it.ref == name } else named(name)
|
||||
|
||||
/**
|
||||
* What a schedule's or a run's model is called among [this] list: [said] (the id or the name
|
||||
* the server gave), and its connection where the server says which one ([ref]) and another
|
||||
* model in the list shares the id. A ref the list does not have leaves [said] as it is.
|
||||
*/
|
||||
fun List<SchedulingModel>.saidWithConnection(ref: String?, said: String?): String? {
|
||||
val word = said?.ifBlank { null } ?: return null
|
||||
val model = firstOrNull { !ref.isNullOrBlank() && it.ref == ref } ?: return word
|
||||
return twinTitle(word, model.connection, count { it.id == model.id } > 1)
|
||||
}
|
||||
|
||||
/** A scheduling model's name in a list of [all]: with its connection where another there shares its id. */
|
||||
fun SchedulingModel.titleAmong(all: List<SchedulingModel>): String = twinTitle(name.ifBlank { id }, connection, all.count { it.id == id } > 1)
|
||||
|
||||
|
||||
@@ -22,48 +22,29 @@ data class Frame(val event: String, val data: String)
|
||||
* 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.
|
||||
* 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).
|
||||
*/
|
||||
class StreamClient(private val api: ApiClient) {
|
||||
private val http = api.http.newBuilder().readTimeout(0, TimeUnit.SECONDS).build()
|
||||
|
||||
fun follow(chatId: String, messageId: String): Flow<Frame> = flow {
|
||||
var wait = 1_000L
|
||||
while (true) {
|
||||
var closed = false
|
||||
var refused: ApiException? = null
|
||||
once(api.streamRequest(chatId, messageId)).collect { result ->
|
||||
when (result) {
|
||||
is Outcome.Event -> {
|
||||
wait = 1_000L
|
||||
emit(result.frame)
|
||||
if (result.frame.event == "close") closed = true
|
||||
}
|
||||
|
||||
is Outcome.Refused -> refused = result.error
|
||||
|
||||
is Outcome.Dropped -> Unit
|
||||
}
|
||||
}
|
||||
refused?.let { throw it }
|
||||
if (closed) return@flow
|
||||
delay(wait)
|
||||
wait = (wait * 2).coerceAtMost(30_000L)
|
||||
}
|
||||
}
|
||||
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
|
||||
* its collector stops; a refusal (4xx) ends it with the error.
|
||||
* its collector stops; a refusal (4xx) ends it with the error. Each opening, the first
|
||||
* too, waits for its [turn].
|
||||
*/
|
||||
fun watch(request: () -> Request): Flow<Frame> = flow {
|
||||
fun watch(turn: suspend () -> Unit = {}, request: () -> Request): Flow<Frame> = flow {
|
||||
var wait = 1_000L
|
||||
while (true) {
|
||||
var closed = false
|
||||
var said = false
|
||||
var refused: ApiException? = null
|
||||
// Every opening is a request of its own: it waits for its turn (the gate).
|
||||
turn()
|
||||
once(request()).collect { result ->
|
||||
when (result) {
|
||||
is Outcome.Event -> {
|
||||
@@ -91,12 +72,6 @@ class StreamClient(private val api: ApiClient) {
|
||||
}
|
||||
}
|
||||
|
||||
private sealed interface Outcome {
|
||||
data class Event(val frame: Frame) : Outcome
|
||||
data class Refused(val error: ApiException) : Outcome
|
||||
data object Dropped : Outcome
|
||||
}
|
||||
|
||||
private fun once(request: Request): Flow<Outcome> = callbackFlow {
|
||||
val source = EventSources.createFactory(http).newEventSource(
|
||||
request,
|
||||
@@ -125,5 +100,44 @@ class StreamClient(private val api: ApiClient) {
|
||||
}
|
||||
}
|
||||
|
||||
/** What one opening of a stream gave: a frame, a refusal (4xx), or a connection that broke. */
|
||||
sealed interface Outcome {
|
||||
data class Event(val frame: Frame) : Outcome
|
||||
data class Refused(val error: ApiException) : 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
|
||||
* with the error.
|
||||
*/
|
||||
fun reopened(turn: suspend () -> Unit, open: () -> Flow<Outcome>): Flow<Frame> = flow {
|
||||
var wait = 1_000L
|
||||
while (true) {
|
||||
var closed = false
|
||||
var refused: ApiException? = null
|
||||
open().collect { result ->
|
||||
when (result) {
|
||||
is Outcome.Event -> {
|
||||
wait = 1_000L
|
||||
emit(result.frame)
|
||||
if (result.frame.event == "close") closed = true
|
||||
}
|
||||
|
||||
is Outcome.Refused -> refused = result.error
|
||||
|
||||
is Outcome.Dropped -> Unit
|
||||
}
|
||||
}
|
||||
refused?.let { throw it }
|
||||
if (closed) return@flow
|
||||
delay(wait)
|
||||
wait = (wait * 2).coerceAtMost(30_000L)
|
||||
turn()
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether an events route that ended is opened again without a pause: only one that [closed] itself after it [said] something. */
|
||||
fun reopenAtOnce(closed: Boolean, said: Boolean): Boolean = closed && said
|
||||
@@ -71,6 +71,8 @@ data class AssistUiState(
|
||||
val connection: Connection = Connection.Checking,
|
||||
val models: List<ModelInfo> = emptyList(),
|
||||
val modelId: String? = null,
|
||||
/** [modelId] is a continued chat's own `model_ref`: looked up as a ref alone, never as an id. */
|
||||
val modelIsRef: Boolean = false,
|
||||
val listening: Boolean = false,
|
||||
/** The words heard so far, while listening and while the last of them is written down. */
|
||||
val heard: String = "",
|
||||
@@ -115,7 +117,7 @@ data class AssistUiState(
|
||||
val held: Boolean get() = waiting.isNotBlank() || waitingRecording
|
||||
|
||||
val screenAvailable: Boolean get() = screenText || screenshot != null
|
||||
val modelInfo: ModelInfo? get() = models.named(modelId)
|
||||
val modelInfo: ModelInfo? get() = models.named(modelId, modelIsRef)
|
||||
val empty: Boolean get() = turns.isEmpty()
|
||||
}
|
||||
|
||||
@@ -215,7 +217,7 @@ class AssistController(
|
||||
context.lembas.instances.prefs.map { it.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) else it }
|
||||
_state.update { if (it.chatId == null) it.copy(modelId = newChatModel, modelIsRef = false) else it }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -715,7 +717,16 @@ class AssistController(
|
||||
val question = detail.messages.lastOrNull { it.isUser }
|
||||
val answer = detail.messages.lastOrNull { !it.isUser }
|
||||
val turns = if (question != null) listOf(AssistTurn(question.text.orEmpty(), earlier = answer?.steps.orEmpty())) else emptyList()
|
||||
_state.update { it.copy(chatId = last.chatId, turns = turns, modelId = detail.chat.model.ifBlank { null } ?: it.modelId, last = null) }
|
||||
val own = detail.chat.modelKey
|
||||
_state.update {
|
||||
it.copy(
|
||||
chatId = last.chatId,
|
||||
turns = turns,
|
||||
modelId = own ?: it.modelId,
|
||||
modelIsRef = if (own != null) !detail.chat.modelRef.isNullOrBlank() else it.modelIsRef,
|
||||
last = null,
|
||||
)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// A chat deleted since is simply not offered again.
|
||||
if (e is ApiException && e.status == 404) {
|
||||
@@ -749,13 +760,24 @@ class AssistController(
|
||||
following?.cancel()
|
||||
speaker.stop()
|
||||
// And on the assistant's own model again, not the one of the chat that was continued.
|
||||
_state.update { it.copy(chatId = null, turns = emptyList(), error = null, busy = false, conversation = false, modelId = newChatModel ?: it.modelId) }
|
||||
_state.update {
|
||||
it.copy(
|
||||
chatId = null,
|
||||
turns = emptyList(),
|
||||
error = null,
|
||||
busy = false,
|
||||
conversation = false,
|
||||
modelId = newChatModel ?: it.modelId,
|
||||
modelIsRef =
|
||||
newChatModel == null && it.modelIsRef,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** The model: for the chat this sheet is in, changed at once; for a new one, kept for next time. */
|
||||
override fun pickModel(id: String) {
|
||||
newChatModel = id
|
||||
_state.update { it.copy(modelId = id) }
|
||||
_state.update { it.copy(modelId = id, modelIsRef = false) }
|
||||
scope.launch {
|
||||
context.lembas.instances.savePrefs { it.copy(assistantModel = id) }
|
||||
val chat = _state.value.chatId ?: return@launch
|
||||
|
||||
@@ -97,7 +97,7 @@ import eu.llembas.android.ui.ModelAvatar
|
||||
import eu.llembas.android.ui.ProgressStatus
|
||||
import eu.llembas.android.ui.chat.PhoneCard
|
||||
import eu.llembas.android.ui.chat.Steps
|
||||
import eu.llembas.android.ui.chat.followsAt
|
||||
import eu.llembas.android.ui.chat.restFollows
|
||||
import eu.llembas.android.ui.chat.yielding
|
||||
import eu.llembas.android.ui.progressLineOf
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
@@ -227,13 +227,26 @@ fun ColumnScope.AssistSheetContent(
|
||||
// come to rest says whether it is taken up again, and a question asked always shows.
|
||||
var following by remember { mutableStateOf(true) }
|
||||
val slack = with(LocalDensity.current) { 48.dp.roundToPx() }
|
||||
val touched = remember { booleanArrayOf(false) }
|
||||
LaunchedEffect(scroll) {
|
||||
scroll.interactionSource.interactions.collect { if (it is DragInteraction.Start) following = false }
|
||||
scroll.interactionSource.interactions.collect {
|
||||
if (it is DragInteraction.Start) {
|
||||
touched[0] = true
|
||||
following = false
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(scroll) {
|
||||
var moving = false
|
||||
var from = scroll.value
|
||||
snapshotFlow { scroll.isScrollInProgress }.collect { now ->
|
||||
if (moving && !now) following = followsAt(scroll.maxValue - scroll.value, slack)
|
||||
if (now && !moving) from = scroll.value
|
||||
if (moving && !now) {
|
||||
// Only the person's own scroll ends the following (`restFollows`), not one of ours
|
||||
// that an arriving line left short of the end.
|
||||
following = restFollows(following, touched[0] || scroll.value < from, scroll.maxValue - scroll.value, slack)
|
||||
touched[0] = false
|
||||
}
|
||||
moving = now
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,26 +4,35 @@ import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.provider.OpenableColumns
|
||||
import android.widget.Toast
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.core.content.IntentCompat
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.MainActivity
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.assist.AssistSheetFrame
|
||||
import eu.llembas.android.assist.LastAssist
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.push.Notifications
|
||||
import eu.llembas.android.sendFrom
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.files.FolderPicker
|
||||
import eu.llembas.android.ui.files.LocalFile
|
||||
import eu.llembas.android.ui.files.describe
|
||||
import eu.llembas.android.ui.files.filesSay
|
||||
import eu.llembas.android.ui.files.uploadFrom
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
@@ -37,29 +46,49 @@ import kotlinx.coroutines.withContext
|
||||
* or to the last chat the assistant made; files are uploaded first and bound to that message, as
|
||||
* the composer's are. The chat then opens in the app. A new chat made here becomes the
|
||||
* assistant's last chat, so the next share can follow it.
|
||||
*
|
||||
* The instance is asked nothing until the person has chosen what to do, and no request starts
|
||||
* while the phone is locked or the sheet is not in front ([eu.llembas.android.InstanceGate]).
|
||||
*/
|
||||
class ShareActivity :
|
||||
ComponentActivity(),
|
||||
ShareActions {
|
||||
private val state = MutableStateFlow(ShareState())
|
||||
private var uris: List<Uri> = emptyList()
|
||||
|
||||
/** The files that came in and may be sent on ([SharedSource]), as the provider describes each. */
|
||||
private var files: List<LocalFile> = emptyList()
|
||||
private val choosing = MutableStateFlow(false)
|
||||
|
||||
/** How far "Save to Files" got into which folder: a second try takes it up at the one that failed. */
|
||||
private var kept = Kept()
|
||||
|
||||
/** The attachments already uploaded for which chat (null: a new one), so a second try does not upload them again. */
|
||||
private var attached: Pair<String?, List<String>> = null to emptyList()
|
||||
private var homeAsked = false
|
||||
|
||||
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
uris = when (intent.action) {
|
||||
val given = when (intent.action) {
|
||||
Intent.ACTION_SEND -> listOfNotNull(IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java))
|
||||
Intent.ACTION_SEND_MULTIPLE -> IntentCompat.getParcelableArrayListExtra(intent, Intent.EXTRA_STREAM, Uri::class.java).orEmpty()
|
||||
else -> emptyList()
|
||||
}
|
||||
// The addresses are the other app's word: one that names something of this app's own is never opened.
|
||||
val taken = given.filter { SharedSource.acceptable(this, it) }
|
||||
val text = listOfNotNull(intent.getStringExtra(Intent.EXTRA_SUBJECT), intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString())
|
||||
.filter { it.isNotBlank() }
|
||||
.distinct()
|
||||
.joinToString("\n\n")
|
||||
.trim()
|
||||
state.update { it.copy(text = text, files = uris.map { uri -> SharedFile(nameOf(uri), (contentResolver.getType(uri) ?: "").startsWith("image/")) }) }
|
||||
state.update { it.copy(text = text, refused = taken.size < given.size, reading = taken.isNotEmpty()) }
|
||||
lifecycleScope.launch {
|
||||
// What each is called and how large, from its provider, before anything can be sent. The instance is asked nothing yet.
|
||||
files = withContext(Dispatchers.IO) { taken.map { contentResolver.describe(it) } }
|
||||
state.update { it.copy(files = files.map { f -> SharedFile(f.name, f.mime.startsWith("image/"), f.size) }, reading = false) }
|
||||
}
|
||||
lifecycleScope.launch {
|
||||
val store = lembas.instances
|
||||
val prefs = store.prefs.first()
|
||||
@@ -74,14 +103,96 @@ class ShareActivity :
|
||||
setContent {
|
||||
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
|
||||
val shown by state.collectAsState()
|
||||
val picking by choosing.collectAsState()
|
||||
LembasTheme(prefs.theme) {
|
||||
AssistSheetFrame(onDismiss = ::cancel) { handle, _ -> ShareSheetContent(shown, this@ShareActivity, handle) }
|
||||
if (picking) {
|
||||
FolderPicker(
|
||||
stringResource(R.string.files_choose_folder),
|
||||
stringResource(R.string.files_save_here),
|
||||
shown.folder ?: "/",
|
||||
onPick = { folder ->
|
||||
choosing.value = false
|
||||
state.update { it.copy(folder = folder) }
|
||||
},
|
||||
onDismiss = { choosing.value = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun cancel() = finish()
|
||||
|
||||
override fun chooseFolder() {
|
||||
choosing.value = true
|
||||
}
|
||||
|
||||
/** The gate, before a request: nothing is sent while the phone is locked or the sheet is not in front. */
|
||||
private suspend fun turn() = lembas.gate.pass { waiting -> state.update { it.copy(waiting = waiting) } }
|
||||
|
||||
/**
|
||||
* "Save to Files" was chosen: only now is the instance asked where the person's files
|
||||
* open, once. Until it answers there is no folder and nothing can be saved; the folder
|
||||
* picker works either way.
|
||||
*/
|
||||
override fun toFiles() {
|
||||
if (homeAsked || state.value.folder != null) return
|
||||
homeAsked = true
|
||||
lifecycleScope.launch {
|
||||
try {
|
||||
turn()
|
||||
val home = lembas.instances.client()?.files("/")?.path ?: return@launch
|
||||
state.update { it.copy(folder = it.folder ?: home) }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
homeAsked = false
|
||||
state.update { it.copy(error = filesSay(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep what was shared in the person's files: each file streamed into the folder as it is,
|
||||
* the text (when there is any) as a note beside them. No chat is made and no model is asked.
|
||||
* What the instance refuses -- a file over its limit, a folder that may not be written --
|
||||
* is said in its own sentence, and the sheet stays; Save again goes on from the file that
|
||||
* failed, into the same folder, and does not send the ones before it twice.
|
||||
*/
|
||||
override fun saveToFiles() {
|
||||
val now = state.value
|
||||
val folder = now.folder ?: return
|
||||
if (now.sending) return
|
||||
state.update { it.copy(sending = true, error = null) }
|
||||
lifecycleScope.launch {
|
||||
try {
|
||||
val api = lembas.instances.client() ?: run {
|
||||
startActivity(Intent(this@ShareActivity, MainActivity::class.java))
|
||||
finish()
|
||||
return@launch
|
||||
}
|
||||
// The files, then the text as a note (null): one queue, so a second try knows where it was.
|
||||
val items: List<LocalFile?> = if (now.text.isNotBlank()) files + listOf<LocalFile?>(null) else files
|
||||
kept = kept.into(folder)
|
||||
sendFrom(items, kept.done, { turn() }, { kept = kept.copy(done = it) }) { file ->
|
||||
if (file != null) {
|
||||
api.uploadFrom(this@ShareActivity, file, folder)
|
||||
} else {
|
||||
// The note is new each time: never over one that is there.
|
||||
api.saveFile(FileKinds.child(folder, sharedNoteName(java.time.LocalDateTime.now())), now.text + "\n", create = true)
|
||||
}
|
||||
}
|
||||
Toast.makeText(this@ShareActivity, R.string.files_uploaded, Toast.LENGTH_SHORT).show()
|
||||
finish()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
state.update { it.copy(sending = false, error = filesSay(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun send(ask: String, toLast: Boolean) {
|
||||
if (state.value.sending) return
|
||||
state.update { it.copy(sending = true, error = null) }
|
||||
@@ -95,13 +206,18 @@ class ShareActivity :
|
||||
}
|
||||
val now = state.value
|
||||
val into = if (toLast) now.last?.chatId else null
|
||||
val files = uris.map { uri ->
|
||||
val bytes = withContext(Dispatchers.IO) { contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0) }
|
||||
api.upload(nameOf(uri), contentResolver.getType(uri) ?: "application/octet-stream", bytes, into).id
|
||||
// What a first try already uploaded for this chat is not uploaded again.
|
||||
if (attached.first != into) attached = into to emptyList()
|
||||
val ids = attached.second.toMutableList()
|
||||
sendFrom(files, ids.size, { turn() }, { attached = into to ids.toList() }) { file ->
|
||||
val bytes = withContext(Dispatchers.IO) { SharedSource.open(this@ShareActivity, file.uri).use { it.readBytes() } }
|
||||
ids += api.upload(file.name, file.mime, bytes, into).id
|
||||
}
|
||||
val sent = ids.toList()
|
||||
val message = shareMessage(ask, now.text, getString(R.string.share_default_prompt))
|
||||
turn()
|
||||
val chatId = if (into != null) {
|
||||
api.sendMessage(into, message, files)
|
||||
api.sendMessage(into, message, sent)
|
||||
into
|
||||
} else {
|
||||
val prefs = store.prefs.first()
|
||||
@@ -109,7 +225,8 @@ class ShareActivity :
|
||||
// gone is not asked for (the instance's default answers instead).
|
||||
val chosen = prefs.assistantModel
|
||||
val gone = chosen.isNotBlank() && runCatching { api.models() }.getOrNull()?.let { it.named(chosen) == null } == true
|
||||
val made = api.createChat(message, files, model = chosen.takeIf { it.isNotBlank() && !gone })
|
||||
turn()
|
||||
val made = api.createChat(message, sent, model = chosen.takeIf { it.isNotBlank() && !gone })
|
||||
store.savePrefs {
|
||||
it.copy(
|
||||
lastAssistChat = made.chat.id,
|
||||
@@ -125,18 +242,16 @@ class ShareActivity :
|
||||
.putExtra(Notifications.EXTRA_CHAT, chatId),
|
||||
)
|
||||
finish()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} 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) }
|
||||
state.update { it.copy(last = null) }
|
||||
}
|
||||
state.update { it.copy(sending = false, error = explain(e)) }
|
||||
state.update { it.copy(sending = false, error = if (e is SharedRefused) filesSay(e) else explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun nameOf(uri: Uri): String = runCatching {
|
||||
contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
|
||||
}.getOrNull() ?: uri.lastPathSegment ?: "shared"
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package eu.llembas.android.share
|
||||
|
||||
import android.text.format.Formatter
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -21,6 +22,7 @@ import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
|
||||
import androidx.compose.material.icons.filled.EditNote
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.History
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material3.Button
|
||||
@@ -43,6 +45,7 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalInspectionMode
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
@@ -52,8 +55,16 @@ import eu.llembas.android.R
|
||||
import eu.llembas.android.assist.LastAssist
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
|
||||
/** One shared file, as the sheet names it. */
|
||||
data class SharedFile(val name: String, val image: Boolean)
|
||||
/** One shared file, as the sheet names it: what its provider calls it and how large it says it is ([size] -1: it does not say). */
|
||||
data class SharedFile(val name: String, val image: Boolean, val size: Long = -1)
|
||||
|
||||
/** How far a "Save to Files" got: [done] of its queue are in [folder]. Another folder starts at the first again. */
|
||||
data class Kept(val folder: String = "", val done: Int = 0) {
|
||||
fun into(folder: String): Kept = if (folder == this.folder) this else Kept(folder, 0)
|
||||
}
|
||||
|
||||
/** A shared address that is not taken: not `content:`, this app's own provider, or one that opens onto this app's own files. */
|
||||
class SharedRefused : java.io.IOException("")
|
||||
|
||||
/** What was shared, where it may go, and how sending it went. */
|
||||
data class ShareState(
|
||||
@@ -64,6 +75,14 @@ data class ShareState(
|
||||
val last: LastAssist? = null,
|
||||
val sending: Boolean = false,
|
||||
val error: String? = null,
|
||||
/** Where "Save to Files" would put it: the person's own folder until they choose another; null while it is not known. */
|
||||
val folder: String? = null,
|
||||
/** Something that came in was left out: its address named what another app may not have sent on ([SharedSource]). */
|
||||
val refused: Boolean = false,
|
||||
/** The files are still being asked what they are called. */
|
||||
val reading: Boolean = false,
|
||||
/** The next request waits for the phone to be unlocked and the sheet to be in front. */
|
||||
val waiting: Boolean = false,
|
||||
)
|
||||
|
||||
/** What the share sheet can do; nothing by default, for the screenshot tests. */
|
||||
@@ -71,20 +90,31 @@ interface ShareActions {
|
||||
/** Send it with [ask] (empty: the default request) to a new chat, or [toLast] to the last assistant chat. */
|
||||
fun send(ask: String, toLast: Boolean) {}
|
||||
|
||||
/** Keep what was shared as files in [ShareState.folder], asking no model anything. */
|
||||
fun saveToFiles() {}
|
||||
|
||||
/** "Save to Files" was chosen as where it goes: the instance may now be asked where the person's files open. */
|
||||
fun toFiles() {}
|
||||
|
||||
/** Choose another folder to save into. */
|
||||
fun chooseFolder() {}
|
||||
|
||||
fun cancel() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* The share sheet's contents, from [state] alone: what came in (the text, the files by name),
|
||||
* what to do with it (a line of the person's own, optional), where it goes -- a new chat, or the
|
||||
* last chat the assistant made -- and Send. Rows of unknown height stack; the two choices are
|
||||
* whole-row tap targets of at least 56 dp.
|
||||
* what to do with it (a line of the person's own, optional), where it goes -- a new chat, the
|
||||
* last chat the assistant made, or the person's Files, where nothing is asked of a model -- and
|
||||
* Send or Save. Rows of unknown height stack; the choices are whole-row tap targets of at least
|
||||
* 56 dp.
|
||||
*/
|
||||
@Composable
|
||||
fun ColumnScope.ShareSheetContent(state: ShareState, actions: ShareActions, handle: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
var ask by remember { mutableStateOf("") }
|
||||
var toLast by remember { mutableStateOf(false) }
|
||||
var toFiles by remember { mutableStateOf(false) }
|
||||
val last = state.last
|
||||
|
||||
Column(handle.fillMaxWidth()) {
|
||||
@@ -141,8 +171,19 @@ fun ColumnScope.ShareSheetContent(state: ShareState, actions: ShareActions, hand
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(file.name, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
if (file.size >= 0) {
|
||||
// The name gives; the size is short and stays whole.
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(
|
||||
Formatter.formatShortFileSize(LocalContext.current, file.size),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (state.refused) Text(stringResource(R.string.share_refused), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
|
||||
// What to do with it.
|
||||
TextField(
|
||||
@@ -157,27 +198,47 @@ fun ColumnScope.ShareSheetContent(state: ShareState, actions: ShareActions, hand
|
||||
unfocusedIndicatorColor = Color.Transparent,
|
||||
),
|
||||
maxLines = 4,
|
||||
enabled = !state.sending,
|
||||
// Files keep what was shared as it is: there is nobody to tell what to do with it.
|
||||
enabled = !state.sending && !toFiles,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp),
|
||||
)
|
||||
|
||||
// Where it goes.
|
||||
if (last != null) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = palette.surfaceRaised,
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column {
|
||||
Destination(Icons.Filled.EditNote, stringResource(R.string.new_chat), null, selected = !toLast, enabled = !state.sending) { toLast = false }
|
||||
Destination(Icons.Filled.History, stringResource(R.string.assist_continue), last.title, selected = toLast, enabled = !state.sending) {
|
||||
toLast =
|
||||
true
|
||||
Surface(
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = palette.surfaceRaised,
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column {
|
||||
Destination(Icons.Filled.EditNote, stringResource(R.string.new_chat), null, selected = !toLast && !toFiles, enabled = !state.sending) {
|
||||
toLast = false
|
||||
toFiles = false
|
||||
}
|
||||
if (last != null) {
|
||||
Destination(
|
||||
Icons.Filled.History,
|
||||
stringResource(R.string.assist_continue),
|
||||
last.title,
|
||||
selected = toLast && !toFiles,
|
||||
enabled = !state.sending,
|
||||
) {
|
||||
toLast = true
|
||||
toFiles = false
|
||||
}
|
||||
}
|
||||
Destination(Icons.Filled.Folder, stringResource(R.string.share_to_files), state.folder, selected = toFiles, enabled = !state.sending) {
|
||||
toFiles = true
|
||||
actions.toFiles()
|
||||
}
|
||||
}
|
||||
}
|
||||
if (toFiles) {
|
||||
TextButton(onClick = actions::chooseFolder, enabled = !state.sending, modifier = Modifier.heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.files_choose_folder))
|
||||
}
|
||||
}
|
||||
if (state.waiting) Text(stringResource(R.string.files_waiting), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
state.error?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger) }
|
||||
}
|
||||
|
||||
@@ -189,11 +250,21 @@ fun ColumnScope.ShareSheetContent(state: ShareState, actions: ShareActions, hand
|
||||
TextButton(onClick = actions::cancel, modifier = Modifier.heightIn(min = 48.dp)) { Text(stringResource(R.string.cancel)) }
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Button(
|
||||
onClick = { actions.send(ask, toLast && last != null) },
|
||||
enabled = !state.sending && (state.text.isNotBlank() || state.files.isNotEmpty()),
|
||||
onClick = { if (toFiles) actions.saveToFiles() else actions.send(ask, toLast && last != null) },
|
||||
enabled = !state.sending && !state.reading && (state.text.isNotBlank() || state.files.isNotEmpty()) && (!toFiles || state.folder != null),
|
||||
colors = ButtonDefaults.buttonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.heightIn(min = 48.dp),
|
||||
) { Text(stringResource(if (state.sending) R.string.share_sending else R.string.send)) }
|
||||
) {
|
||||
Text(
|
||||
stringResource(
|
||||
when {
|
||||
toFiles -> R.string.save
|
||||
state.sending -> R.string.share_sending
|
||||
else -> R.string.send
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,3 +299,7 @@ fun shareMessage(ask: String, shared: String, fallback: String): String {
|
||||
val request = ask.trim().ifBlank { fallback }
|
||||
return if (shared.isBlank()) request else "$request\n\n---\n\n${shared.trim()}"
|
||||
}
|
||||
|
||||
/** What shared text is called when it is kept as a file: `shared-20260102-030405.txt`, from the moment it was saved. */
|
||||
fun sharedNoteName(at: java.time.LocalDateTime): String =
|
||||
"shared-" + at.format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss", java.util.Locale.ROOT)) + ".txt"
|
||||
@@ -0,0 +1,77 @@
|
||||
package eu.llembas.android.share
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.system.Os
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
|
||||
/**
|
||||
* What another app may hand this one to send on. A share names its files by address, and the
|
||||
* address is the other app's word: it could as well name something of this app's own -- a file
|
||||
* in its private data, a copy in its cache through its own provider -- and have the person send
|
||||
* it to a chat without knowing. So only a `content:` address of another app's provider is taken,
|
||||
* and what it opens must not be a file of this app's.
|
||||
*/
|
||||
object SharedSource {
|
||||
/**
|
||||
* Whether an address is refused by its looks: anything that is not `content:` (a `file:`
|
||||
* path is read with this app's own rights), and a provider that is this app's ([own]: its
|
||||
* authorities). An authority may carry a user before an `@`; the provider is what follows.
|
||||
*/
|
||||
fun refused(scheme: String?, authority: String?, own: Set<String>): Boolean {
|
||||
if (!scheme.equals("content", ignoreCase = true)) return true
|
||||
val provider = authority?.substringAfterLast('@')?.lowercase().orEmpty()
|
||||
return provider.isBlank() || provider in own.map { it.lowercase() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether [resolved] -- where an opened descriptor really leads -- is inside one of [roots],
|
||||
* this app's private places. Compared by whole path segments: `/data/user/0/app` does not
|
||||
* hold `/data/user/0/app.other`.
|
||||
*/
|
||||
fun inside(resolved: String, roots: List<String>): Boolean = roots.any { root ->
|
||||
val base = root.trimEnd('/')
|
||||
base.isNotEmpty() && (resolved == base || resolved.startsWith("$base/"))
|
||||
}
|
||||
|
||||
/** This app's providers, by authority: its own FileProvider and whatever its libraries declare. */
|
||||
fun ownAuthorities(context: Context): Set<String> {
|
||||
val declared = runCatching {
|
||||
@Suppress("DEPRECATION")
|
||||
context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_PROVIDERS).providers
|
||||
}.getOrNull().orEmpty()
|
||||
return declared.flatMap { it.authority.orEmpty().split(';') }.filter { it.isNotBlank() }.toSet() + (context.packageName + ".files")
|
||||
}
|
||||
|
||||
/** This app's private places, as the paths a descriptor can lead to (the data directory under each of its names). */
|
||||
fun privateRoots(context: Context): List<String> {
|
||||
val dirs = listOfNotNull(context.dataDir, context.filesDir?.parentFile, context.cacheDir, context.codeCacheDir, context.noBackupFilesDir) +
|
||||
context.externalCacheDirs.orEmpty().filterNotNull().mapNotNull { it.parentFile } +
|
||||
context.getExternalFilesDirs(null).orEmpty().filterNotNull().mapNotNull { it.parentFile }
|
||||
return dirs.flatMap { listOf(it.absolutePath, runCatching { it.canonicalPath }.getOrDefault(it.absolutePath)) }.distinct()
|
||||
}
|
||||
|
||||
fun acceptable(context: Context, uri: Uri): Boolean = !refused(uri.scheme, uri.authority, ownAuthorities(context))
|
||||
|
||||
/**
|
||||
* Opens what [uri] names for reading, or throws: an address refused by its looks is never
|
||||
* opened, and one that opens onto a file of this app's is closed again unread. The stream
|
||||
* is of the very descriptor that was looked at, so nothing can be swapped in between.
|
||||
*/
|
||||
fun open(context: Context, uri: Uri): InputStream {
|
||||
if (!acceptable(context, uri)) throw SharedRefused()
|
||||
val opened = context.contentResolver.openAssetFileDescriptor(uri, "r") ?: throw IOException("The file could not be opened.")
|
||||
try {
|
||||
val leads = runCatching { Os.readlink("/proc/self/fd/" + opened.parcelFileDescriptor.fd) }.getOrDefault("")
|
||||
val resolved = if (leads.startsWith("/")) runCatching { File(leads).canonicalPath }.getOrDefault(leads) else leads
|
||||
if (inside(resolved, privateRoots(context)) || inside(leads, privateRoots(context))) throw SharedRefused()
|
||||
return opened.createInputStream()
|
||||
} catch (e: Throwable) {
|
||||
runCatching { opened.close() }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -94,14 +94,26 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Attachment
|
||||
import eu.llembas.android.api.Drawn
|
||||
import eu.llembas.android.api.GeneratedMedia
|
||||
import eu.llembas.android.api.MediaJob
|
||||
import eu.llembas.android.api.MediaView
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.api.ShowCard
|
||||
import eu.llembas.android.api.drawn
|
||||
import eu.llembas.android.api.editable
|
||||
import eu.llembas.android.api.unrecordedReplies
|
||||
import eu.llembas.android.ui.ModelAvatar
|
||||
import eu.llembas.android.ui.ProgressStatus
|
||||
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.FileViewer
|
||||
import eu.llembas.android.ui.viewer.PlayerDialog
|
||||
import eu.llembas.android.ui.viewer.Playing
|
||||
import kotlinx.coroutines.flow.drop
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@@ -121,6 +133,8 @@ fun ChatScreen(
|
||||
onKind: ((agent: Boolean) -> Unit)? = null,
|
||||
/** Entered from a report (its Reply): the bar says "Report: title" and has Back, to the report, where the menu is. */
|
||||
report: String? = null,
|
||||
/** Open the person's Files at a folder: where a generated file's "Open in Files" leads. */
|
||||
onFiles: (String) -> Unit = {},
|
||||
model: ChatViewModel = viewModel(key = chatId ?: if (agent) "new-agent" else "new"),
|
||||
) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
@@ -138,6 +152,17 @@ fun ChatScreen(
|
||||
LaunchedEffect(state.chat?.id) {
|
||||
if (state.chat?.id != null) lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { model.watchActivity() }
|
||||
}
|
||||
// The chat's long generations (a video, a track), read again every few seconds while the
|
||||
// screen is in front and not otherwise. An agent chat runs on a computer and makes none.
|
||||
LaunchedEffect(state.chat?.id) {
|
||||
if (state.chat?.id != null && !isAgent) lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { model.watchMedia() }
|
||||
}
|
||||
// Replies nobody asked for from this screen (a subagent that woke the main agent, a schedule,
|
||||
// a turn the linked computer started): heard on the person's events route while the screen is
|
||||
// in front, and caught up with once on every return to it.
|
||||
LaunchedEffect(state.chat?.id) {
|
||||
if (state.chat?.id != null) lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { model.watchReplies() }
|
||||
}
|
||||
LaunchedEffect(state.error, state.notice) {
|
||||
(state.error ?: state.notice)?.let {
|
||||
snackbar.showSnackbar(it)
|
||||
@@ -145,6 +170,34 @@ fun ChatScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// What a generated file's card does: the player over the chat, the folder in Files, and the
|
||||
// ways a file leaves the app. Its own transfers, as each screen that hands files out has.
|
||||
val transfers: TransferViewModel = viewModel(key = "chat-transfers")
|
||||
val saveTo = rememberSaver(transfers)
|
||||
var playing by remember { mutableStateOf<Playing?>(null) }
|
||||
val media = remember(model, transfers) {
|
||||
object : MediaActions {
|
||||
override fun play(media: GeneratedMedia) {
|
||||
playing = Playing(media.raw, media.title, media.size, video = media.view == MediaView.Video)
|
||||
}
|
||||
|
||||
override fun play(attachment: Attachment) {
|
||||
playing = Playing(Raw.Attached(attachment.id), attachment.name, attachment.size, video = attachment.kind == "video")
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
override fun download(media: GeneratedMedia) = saveTo(media.raw, media.title, media.mime)
|
||||
|
||||
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 cancel(job: MediaJob) = model.cancelJob(job)
|
||||
}
|
||||
}
|
||||
|
||||
// Read aloud on a reply, when the instance has a voice; it stops when the chat is left.
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
@@ -173,6 +226,7 @@ fun ChatScreen(
|
||||
onShow = { showing = it },
|
||||
onKind = onKind,
|
||||
report = report,
|
||||
media = media,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -183,6 +237,8 @@ fun ChatScreen(
|
||||
showing?.let { file ->
|
||||
state.chat?.id?.let { id -> FileViewer(id, file, onClose = { showing = null }) }
|
||||
}
|
||||
playing?.let { PlayerDialog(it, onClose = { playing = null }, gone = stringResource(R.string.media_gone)) }
|
||||
TransferHost(transfers)
|
||||
}
|
||||
|
||||
/** What the bar says of a chat entered from a report: "Report: title", or "Report" when the title is not known. */
|
||||
@@ -206,10 +262,13 @@ fun ChatContent(
|
||||
onShow: (ShowCard) -> Unit = {},
|
||||
onKind: ((agent: Boolean) -> Unit)? = null,
|
||||
report: String? = null,
|
||||
/** What the cards of generated media do; null draws none of them (a picture stays a picture). */
|
||||
media: MediaActions? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val chatMedia = remember(state.mediaJobs, media) { media?.let { ChatMedia(state.mediaJobs, it) } }
|
||||
// A chat opens at its end, where the conversation is, not at its first message.
|
||||
val list = rememberLazyListState(initialFirstVisibleItemIndex = maxOf(0, state.messages.size - 1 + if (state.more) 1 else 0))
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
@@ -217,6 +276,7 @@ fun ChatContent(
|
||||
var tuning by remember { mutableStateOf(false) }
|
||||
var renaming by remember { mutableStateOf(false) }
|
||||
var editing by remember { mutableStateOf<Message?>(null) }
|
||||
var discarding by remember { mutableStateOf<Message?>(null) }
|
||||
var suggestion by remember { mutableStateOf("") }
|
||||
var suggested by remember { mutableIntStateOf(0) }
|
||||
val copy: (String) -> Unit = { text ->
|
||||
@@ -228,6 +288,8 @@ fun ChatContent(
|
||||
val live = state.live
|
||||
val rows = state.messages
|
||||
val info = state.modelInfo
|
||||
// Only in an agent chat: there a turn's reply is the linked computer's, and may never have been written here.
|
||||
val unrecorded = remember(rows, chat?.isAgent, live?.messageId) { if (chat?.isAgent == true) unrecordedReplies(rows, live?.messageId) else emptySet() }
|
||||
|
||||
// The view keeps to the end while a reply is written only for a person who is there
|
||||
// (`Follow.kt` has the rule): a finger on the list ends the following at once, and where the
|
||||
@@ -235,13 +297,42 @@ fun ChatContent(
|
||||
var following by rememberSaveable { mutableStateOf(true) }
|
||||
var drawnBefore by rememberSaveable { mutableStateOf(false) }
|
||||
val slack = with(LocalDensity.current) { 48.dp.roundToPx() }
|
||||
// Whether a finger has been on the list since it last came to rest.
|
||||
val touched = remember { booleanArrayOf(false) }
|
||||
// How many of this app's own scrolls are under way (`ownScroll`): any other scroll is the person's.
|
||||
val own = remember { intArrayOf(0) }
|
||||
// The model drops the far end of a long transcript only under a person who is at its end.
|
||||
LaunchedEffect(following) { actions.reading(atEnd = following) }
|
||||
LaunchedEffect(list) {
|
||||
list.interactionSource.interactions.collect { if (it is DragInteraction.Start) following = false }
|
||||
list.interactionSource.interactions.collect {
|
||||
if (it is DragInteraction.Start) {
|
||||
touched[0] = true
|
||||
following = false
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(list) {
|
||||
var moving = false
|
||||
var fromIndex = list.firstVisibleItemIndex
|
||||
var fromOffset = list.firstVisibleItemScrollOffset
|
||||
var startedByApp = false
|
||||
snapshotFlow { list.isScrollInProgress }.collect { now ->
|
||||
if (moving && !now) following = followsAt(list.distanceToEnd(), slack)
|
||||
if (now && !moving) {
|
||||
fromIndex = list.firstVisibleItemIndex
|
||||
fromOffset = list.firstVisibleItemScrollOffset
|
||||
startedByApp = own[0] > 0
|
||||
}
|
||||
if (moving && !now) {
|
||||
// Only the person's own scroll ends the following (`restFollows`): this app's
|
||||
// scroll to the end, overtaken by a line that arrived meanwhile, does not.
|
||||
val byPerson = scrollWasPersons(
|
||||
touched = touched[0],
|
||||
wentBack = wentBack(fromIndex, fromOffset, list.firstVisibleItemIndex, list.firstVisibleItemScrollOffset),
|
||||
startedByApp = startedByApp,
|
||||
)
|
||||
following = restFollows(following, byPerson, list.distanceToEnd(), slack)
|
||||
touched[0] = false
|
||||
}
|
||||
moving = now
|
||||
}
|
||||
}
|
||||
@@ -256,21 +347,22 @@ fun ChatContent(
|
||||
// An older page above the very top: the row that was first stays first, so reading
|
||||
// goes on upwards from it. Anywhere else the list keeps its place by the rows' keys.
|
||||
val kept = keptRow(before.orEmpty(), rows)
|
||||
if (kept != null && list.firstVisibleItemIndex == 0) yielding { list.scrollToItem(kept + if (state.more) 1 else 0) }
|
||||
} else if (movesToEnd(change, following)) {
|
||||
if (kept != null && list.firstVisibleItemIndex == 0) ownScroll(own) { list.scrollToItem(kept + if (state.more) 1 else 0) }
|
||||
} else if (movesToEnd(change, following, personScrolls(list.isScrollInProgress, own[0]))) {
|
||||
// A list the person is moving is left to them: where it rests says whether it follows.
|
||||
following = true
|
||||
yielding { list.toEnd() }
|
||||
ownScroll(own) { list.toEnd() }
|
||||
}
|
||||
}
|
||||
val growth = live?.let { it.shown.size * 100_000 + (it.tail.text.length + it.tail.thinking.length) } ?: 0
|
||||
LaunchedEffect(growth) { if (growth > 0 && following && !list.isScrollInProgress) yielding { list.toEnd() } }
|
||||
LaunchedEffect(growth) { if (growth > 0 && following && !list.isScrollInProgress) ownScroll(own) { list.toEnd() } }
|
||||
// The keyboard opening takes the list's foot away: a person at the end stays at the end.
|
||||
LaunchedEffect(list) {
|
||||
// A finger on the list ends a scroll of ours by cancelling it: this follower goes on.
|
||||
snapshotFlow { list.layoutInfo.viewportSize.height }.drop(1).collect { if (following && !list.isScrollInProgress) yielding { list.toEnd() } }
|
||||
snapshotFlow { list.layoutInfo.viewportSize.height }.drop(1).collect { if (following && !list.isScrollInProgress) ownScroll(own) { list.toEnd() } }
|
||||
}
|
||||
|
||||
CompositionLocalProvider(LocalCopy provides copy) {
|
||||
CompositionLocalProvider(LocalCopy provides copy, LocalChatMedia provides chatMedia) {
|
||||
Scaffold(
|
||||
containerColor = palette.bg,
|
||||
snackbarHost = { SnackbarHost(snackbar) },
|
||||
@@ -288,7 +380,7 @@ fun ChatContent(
|
||||
title = {
|
||||
ModelTitle(
|
||||
model = info,
|
||||
fallback = state.modelId ?: stringResource(R.string.app_name),
|
||||
fallback = state.modelWord ?: stringResource(R.string.app_name),
|
||||
// A report's conversation says which report: by what it was entered with, else by
|
||||
// what the chat itself says (after the app was closed in between).
|
||||
subtitle = if (report != null || chat?.report != null) {
|
||||
@@ -402,6 +494,8 @@ fun ChatContent(
|
||||
item { TextButton(onClick = actions::older) { Text(stringResource(R.string.older)) } }
|
||||
}
|
||||
items(rows, key = { it.id }) { message ->
|
||||
// One key for a reply while it is written and once it is stored: the row
|
||||
// is the same row at `done`, so the list has nothing to put elsewhere.
|
||||
// The first row is the chat's first message only once nothing older is left to load.
|
||||
val first = !state.more && message.id == rows.firstOrNull()?.id
|
||||
when (drawn(message, first, reportChat = report != null || chat?.report != null)) {
|
||||
@@ -410,11 +504,23 @@ fun ChatContent(
|
||||
|
||||
Drawn.Note -> MachineNote(message.text.orEmpty())
|
||||
|
||||
Drawn.Person -> UserMessage(message, canEdit = live == null, onEdit = { editing = message })
|
||||
// A message that waits is sent now or discarded, never edited.
|
||||
Drawn.Person -> UserMessage(
|
||||
message,
|
||||
canEdit = message.editable(writing = live != null),
|
||||
onEdit = { editing = message },
|
||||
busy = state.acting != null,
|
||||
onSendNow = { actions.sendNow(message) },
|
||||
onDiscard = { discarding = message },
|
||||
)
|
||||
|
||||
// One call for a reply being written and the same reply finished:
|
||||
// what the person opened in it (a thinking chip) stays open at `done`.
|
||||
Drawn.Reply -> {
|
||||
// A finished reply with nothing in it, after a turn nobody typed: one
|
||||
// quiet line in its place, not a blank row with buttons.
|
||||
Drawn.Reply -> if (message.id in unrecorded) {
|
||||
MachineNote(stringResource(R.string.reply_unrecorded))
|
||||
} else {
|
||||
val writing = live?.takeIf { it.messageId == message.id && it.finished == null }
|
||||
AssistantMessage(
|
||||
message,
|
||||
@@ -423,6 +529,7 @@ fun ChatContent(
|
||||
canRegenerate = live == null && message == rows.lastOrNull(),
|
||||
onRegenerate = { actions.regenerate(message) },
|
||||
onShow = onShow,
|
||||
models = state.models,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -434,7 +541,7 @@ fun ChatContent(
|
||||
|
||||
if (picking) {
|
||||
ModalBottomSheet(onDismissRequest = { picking = false }, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {
|
||||
ModelPickerContent(state.models, state.modelId, onPick = { id ->
|
||||
ModelPickerContent(state.models, state.modelInfo?.key, onPick = { id ->
|
||||
picking = false
|
||||
if (chat == null) actions.updateDraft { it.copy(model = id) } else actions.change("model", id)
|
||||
})
|
||||
@@ -474,6 +581,21 @@ fun ChatContent(
|
||||
)
|
||||
}
|
||||
|
||||
// Discarding cannot be taken back, so it is asked once -- in the page's own words.
|
||||
discarding?.let { message ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { discarding = null },
|
||||
text = { Text(stringResource(R.string.discard_message_confirm)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
actions.discard(message)
|
||||
discarding = null
|
||||
}) { Text(stringResource(R.string.discard)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { discarding = null }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
editing?.let { message ->
|
||||
var text by remember(message.id) { mutableStateOf(message.text.orEmpty()) }
|
||||
AlertDialog(
|
||||
@@ -565,7 +687,7 @@ private fun Greeting(
|
||||
}
|
||||
TextButton(onClick = onTune) { Text(where, textAlign = TextAlign.Center, color = palette.inkMuted) }
|
||||
} else {
|
||||
ModelAvatar(state.modelInfo, state.modelId ?: "?", size = 64.dp)
|
||||
ModelAvatar(state.modelInfo, state.modelWord ?: "?", size = 64.dp)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Text(stringResource(R.string.empty_chat), style = MaterialTheme.typography.headlineSmall, textAlign = TextAlign.Center)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import android.provider.OpenableColumns
|
||||
import androidx.core.content.FileProvider
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Activity
|
||||
import eu.llembas.android.api.ActivityAgent
|
||||
import eu.llembas.android.api.ActivityFrame
|
||||
@@ -22,27 +23,38 @@ import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.ChatDetail
|
||||
import eu.llembas.android.api.DeviceDirectory
|
||||
import eu.llembas.android.api.GeneratedMedia
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.LinkedDevice
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.MediaFor
|
||||
import eu.llembas.android.api.MediaJob
|
||||
import eu.llembas.android.api.Mention
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.MessagePage
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.ReplyFrame
|
||||
import eu.llembas.android.api.StartModel
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.api.SubagentTree
|
||||
import eu.llembas.android.api.Turn
|
||||
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.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.files.noSuchRoute
|
||||
import eu.llembas.android.whileOpen
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.takeWhile
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -101,6 +113,10 @@ data class ChatState(
|
||||
val lastSent: String? = null,
|
||||
/** The model picked for this open chat, by its ref: which of two models with one id the chat is on. */
|
||||
val picked: String? = null,
|
||||
/** The chat's long generations (a video, a track, a 3D model), by id, as each was last read. */
|
||||
val mediaJobs: Map<String, JobSeen> = emptyMap(),
|
||||
/** The waiting message that is being sent now or discarded, by its id, until the instance has answered. */
|
||||
val acting: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -131,12 +147,14 @@ val ChatState.modelId: String?
|
||||
get() = chatModel ?: draft.model ?: folderModel ?: models.firstOrNull { it.default }?.key ?: models.firstOrNull()?.key
|
||||
|
||||
/**
|
||||
* An open chat's model. The chat says its model's id, which two connections may share; the one
|
||||
* picked here ([ChatState.picked], a ref) says which of them, for as long as the chat is still
|
||||
* on a model of that id.
|
||||
* An open chat's model: the connection the chat itself names (`model_ref`), where the server
|
||||
* says it. From an older server the chat says only its model's id, which two connections may
|
||||
* share; the one picked here ([ChatState.picked], a ref) then says which of them, for as long
|
||||
* as the chat is still on a model of that id.
|
||||
*/
|
||||
val ChatState.chatModel: String?
|
||||
get() {
|
||||
chat?.modelRef?.ifBlank { null }?.let { return it }
|
||||
val served = chat?.model?.ifBlank { null } ?: return null
|
||||
return picked?.takeIf { models.named(it)?.id == served } ?: served
|
||||
}
|
||||
@@ -145,7 +163,16 @@ val ChatState.chatModel: String?
|
||||
val ChatState.folderModel: String?
|
||||
get() = start?.takeIf { chat == null }?.let { models.named(it.key) ?: models.named(it.model) }?.key
|
||||
|
||||
val ChatState.modelInfo: ModelInfo? get() = models.named(modelId)
|
||||
/** The model in force, among the models offered: a chat that names its connection is on that one or on none of them. */
|
||||
val ChatState.modelInfo: ModelInfo?
|
||||
get() {
|
||||
val ref = chat?.modelRef?.ifBlank { null } ?: return models.named(modelId)
|
||||
return models.serving(ref, chat?.model)
|
||||
}
|
||||
|
||||
/** What the model in force is called where the list does not have it: the chat's own id for it, not its ref. */
|
||||
val ChatState.modelWord: String?
|
||||
get() = chat?.takeIf { !it.modelRef.isNullOrBlank() }?.model?.ifBlank { null } ?: modelId
|
||||
|
||||
/**
|
||||
* Which chat a dictation or a reply read aloud is for: this chat once it exists, else the model
|
||||
@@ -213,6 +240,52 @@ fun ChatState.withOlder(before: String, page: MessagePage): ChatState {
|
||||
return copy(messages = page.messages.distinctBy { it.id }.filterNot { it.id in have } + messages, more = page.more)
|
||||
}
|
||||
|
||||
/**
|
||||
* The transcript read again ([read]: the chat and its newest page), put where the newest page
|
||||
* was. The older pages a person loaded stay above it -- taking them away would take the row
|
||||
* they are reading from under them -- as long as the page still joins them: its first row is
|
||||
* one this screen holds, and the server says there is more above it. A page that joins nothing
|
||||
* here (the chat was rewound past it, or compacted) is the whole transcript, as before. No row
|
||||
* is there twice: the list's rows are keyed by id.
|
||||
*/
|
||||
fun ChatState.withNewest(read: ChatDetail): ChatState {
|
||||
val first = read.messages.firstOrNull()?.id
|
||||
val at = if (first == null) -1 else messages.indexOfFirst { it.id == first }
|
||||
if (at <= 0 || !read.more) return copy(chat = read.chat, messages = read.messages, more = read.more)
|
||||
val newest = read.messages.mapTo(HashSet()) { it.id }
|
||||
return copy(chat = read.chat, messages = messages.subList(0, at).filterNot { it.id in newest } + read.messages)
|
||||
}
|
||||
|
||||
/** Past this many rows a transcript left open is cut back to [KEPT_ROWS]: several times what a person scrolls through. */
|
||||
const val KEPT_MOST = 600
|
||||
|
||||
/** How many of the newest rows stay when a transcript is cut back. */
|
||||
const val KEPT_ROWS = 400
|
||||
|
||||
/**
|
||||
* The transcript, held to a size: a chat left open while replies arrive by themselves (an
|
||||
* agent's wakes, a schedule) would otherwise grow for as long as it is open. Past [most] rows
|
||||
* the oldest go, down to the newest [keep], and "older" is offered again, which reads them
|
||||
* back. Only for a person who is [atEnd]: someone reading further up is reading the very rows
|
||||
* that would go, and nothing is taken from under them.
|
||||
*/
|
||||
fun ChatState.capped(atEnd: Boolean, most: Int = KEPT_MOST, keep: Int = KEPT_ROWS): ChatState {
|
||||
if (!atEnd || messages.size <= most) return this
|
||||
return copy(messages = messages.takeLast(keep), more = true)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the events route's `reply` frame [said] is news to this screen: a reply in the chat
|
||||
* that is open here, which is neither the one being followed nor a row already drawn as
|
||||
* finished. The server says every reply that starts, this app's own too, so most frames for an
|
||||
* open chat are not news.
|
||||
*/
|
||||
fun ChatState.asksFor(said: ReplyFrame): Boolean {
|
||||
if (chat == null || chat.id != said.chatId || said.messageId.isBlank()) return false
|
||||
if (live?.messageId == said.messageId) return false
|
||||
return messages.none { it.id == said.messageId && !it.isUser && it.complete }
|
||||
}
|
||||
|
||||
/**
|
||||
* The stream of the reply [messageId] closed without a `done`. What was written stays in view:
|
||||
* the transcript as the server has it now ([reread]), or -- where that could not be read -- the
|
||||
@@ -222,7 +295,7 @@ fun ChatState.withOlder(before: String, page: MessagePage): ChatState {
|
||||
fun ChatState.closedUnfinished(messageId: String, reread: ChatDetail?): ChatState {
|
||||
val was = live?.takeIf { it.messageId == messageId }
|
||||
if (live != null && was == null) return this
|
||||
if (reread != null) return copy(chat = reread.chat, messages = reread.messages, more = reread.more, live = null)
|
||||
if (reread != null) return withNewest(reread).copy(live = null)
|
||||
if (was == null || was.shown.isEmpty()) return copy(live = null)
|
||||
val kept = was.shown.map { it.copy(open = false) }
|
||||
return copy(
|
||||
@@ -240,6 +313,12 @@ interface ChatActions {
|
||||
fun stop() {}
|
||||
fun regenerate(message: Message) {}
|
||||
fun edit(message: Message, text: String) {}
|
||||
|
||||
/** Send a message that waits ([Message.waiting]) now, as a turn with a reply of its own. */
|
||||
fun sendNow(message: Message) {}
|
||||
|
||||
/** Withdraw a message that waits: it was never given to a model, and its row goes. */
|
||||
fun discard(message: Message) {}
|
||||
fun continueChat() {}
|
||||
fun executePlan() {}
|
||||
fun answer(card: Card, answer: CardAnswer) {}
|
||||
@@ -271,6 +350,9 @@ interface ChatActions {
|
||||
fun delete(then: () -> Unit) {}
|
||||
fun older() {}
|
||||
fun clearUnsent() {}
|
||||
|
||||
/** Whether the person is at the transcript's end ([atEnd]) or reading further up: the screen's word, for what may be dropped. */
|
||||
fun reading(atEnd: Boolean) {}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -363,7 +445,8 @@ class ChatViewModel(app: Application) :
|
||||
_state.update {
|
||||
it.copy(chat = detail.chat, messages = detail.messages, more = detail.more, models = models, loading = false)
|
||||
}
|
||||
detail.live?.let { follow(it) }
|
||||
// Being written when the chat was opened: whoever started it, nobody asked for it from here just now.
|
||||
detail.live?.let { follow(it, own = false) }
|
||||
// Whether a team is offered and what runs in the background: the cheap read,
|
||||
// without the context count. A server without the panel has no answer.
|
||||
runCatching { client.activity(chatId, context = false) }.onSuccess { a ->
|
||||
@@ -401,83 +484,167 @@ class ChatViewModel(app: Application) :
|
||||
}
|
||||
}
|
||||
|
||||
/** Follow a reply to its end, then whatever the queue started after it. */
|
||||
private fun follow(messageId: String) {
|
||||
private val gate get() = getApplication<Application>().lembas.gate
|
||||
|
||||
/** The transcript's reads, one at a time and none twice for the same news. */
|
||||
private val reads = Reads()
|
||||
|
||||
/** The reply the person asked for from this screen last, by its id: the one that goes on behind a lock. */
|
||||
private var ownReply: String? = null
|
||||
|
||||
/** Whether the person is at the transcript's end, as the screen last said. */
|
||||
private var atEnd = true
|
||||
|
||||
override fun reading(atEnd: Boolean) {
|
||||
this.atEnd = atEnd
|
||||
}
|
||||
|
||||
/** How a reply's stream ended. */
|
||||
private sealed interface Through {
|
||||
/** With `done`; [next] is the reply the queue started after it. */
|
||||
data class Done(val next: String?) : Through
|
||||
|
||||
/** Without a `done`: the row is gone on the server, or it ended some way the stream did not tell. */
|
||||
data object Closed : Through
|
||||
|
||||
/** With an error, which has been said. */
|
||||
data object Failed : Through
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow a reply to its end, then whatever the queue started after it.
|
||||
*
|
||||
* [own]: the person asked for this reply from this screen (a message sent, an edit, Regenerate,
|
||||
* Continue). Its stream is the request they started, and goes on when the phone locks or the
|
||||
* app leaves the front, as any request under way does. Every other reply -- one the events
|
||||
* route said, one found being written when the chat was opened or read again, the queue's
|
||||
* next -- is followed only while the app is in front of an unlocked phone ([whileOpen]): when
|
||||
* that ends its stream is let go, and on the return one read catches up and follows what is
|
||||
* being written then. Without that an agent's chat with wakes queued would chain a read and a
|
||||
* stream for hours behind the lock.
|
||||
*
|
||||
* Whatever follows a stream is a new request and waits at the gate, the person's own reply's
|
||||
* too: a broken connection opened again, the read after `done` with a `next`, the read after
|
||||
* a stream that closed without `done`.
|
||||
*/
|
||||
private fun follow(messageId: String, own: Boolean) {
|
||||
val chat = _state.value.chat ?: return
|
||||
if (own) ownReply = messageId
|
||||
// Already followed, and still being written: the events route says this app's own replies
|
||||
// too, and a second stream for one reply would start its drawing over.
|
||||
if (following?.isActive == true && _state.value.live?.let { it.messageId == messageId && it.finished == null } == true) return
|
||||
following?.cancel()
|
||||
following = viewModelScope.launch {
|
||||
_state.update { it.copy(live = LiveReply(messageId)) }
|
||||
// Set at `done`, which is the end of the reply: from then on the stream is followed
|
||||
// only for the name a model may still give the chat (the `title` frame).
|
||||
var ended: LiveReply? = null
|
||||
try {
|
||||
StreamClient(api()).follow(chat.id, messageId).collect { frame ->
|
||||
val before = ended
|
||||
if (before != null) {
|
||||
val named = before.apply(frame.event, frame.data)
|
||||
ended = named
|
||||
if (named.title != before.title) _state.update { s -> s.copy(chat = s.chat?.let { c -> named.title?.let { c.copy(title = it) } ?: c }) }
|
||||
return@collect
|
||||
}
|
||||
val live = (_state.value.live ?: LiveReply(messageId)).apply(frame.event, frame.data)
|
||||
val finished = live.finished
|
||||
if (finished == null) {
|
||||
// The tree outlives the reply: kept for the activity sheet once it ends.
|
||||
_state.update { s -> s.copy(live = live, tree = live.tree ?: s.tree) }
|
||||
return@collect
|
||||
}
|
||||
ended = live
|
||||
_state.update { s ->
|
||||
s.copy(
|
||||
live = null,
|
||||
tree = live.tree ?: s.tree,
|
||||
messages = s.messages.map { if (it.id == finished.id) finished else it },
|
||||
chat = s.chat?.let { c -> live.title?.let { c.copy(title = it) } ?: c },
|
||||
)
|
||||
}
|
||||
// The queue handed a waiting prompt to a fresh reply: the transcript has moved
|
||||
// on the server, so it is read again rather than patched -- and that reply is
|
||||
// followed instead of this stream's tail.
|
||||
live.next?.let { next ->
|
||||
refresh()
|
||||
follow(next)
|
||||
}
|
||||
when (val through = gate.whileOpen(stays = { ownReply == messageId }) { stream(chat, messageId) }) {
|
||||
// Let go at the gate. What the stream had shown stays in the row; once the app
|
||||
// is in front again the chat is read, and what is being written then followed.
|
||||
// A stream let go after its `done` (it was open for the chat's name) left nothing unread.
|
||||
null -> {
|
||||
val mark = reads.mark()
|
||||
val unfinished = _state.value.live?.messageId == messageId
|
||||
_state.update { it.closedUnfinished(messageId, null) }
|
||||
if (unfinished) rereadAndFollow(rounds = 1, mark = mark)
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// After `done` only the name was still to come: nothing to say, nothing to redo.
|
||||
if (ended != null) return@launch
|
||||
fail(e)
|
||||
|
||||
// The queue handed a waiting prompt to a fresh reply: the transcript has moved
|
||||
// on the server, so it is read again rather than patched, and what the read says
|
||||
// is being written is followed (the stream's word for it, where the read failed).
|
||||
is Through.Done -> through.next?.let { next ->
|
||||
gate.passLater()
|
||||
val read = refresh()
|
||||
(if (read != null) read.live else next)?.let { follow(it, own = false) }
|
||||
}
|
||||
|
||||
// The transcript is read again, so what was written is still there; where it
|
||||
// cannot be read, what the stream had shown stays.
|
||||
Through.Closed -> {
|
||||
gate.passLater()
|
||||
val reread = try {
|
||||
api().chat(chat.id)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
_state.update { it.closedUnfinished(messageId, reread).capped(atEnd) }
|
||||
// Another reply is being written there (a queued turn): that one is followed.
|
||||
reread?.live?.takeIf { it != messageId }?.let { follow(it, own = false) }
|
||||
}
|
||||
|
||||
// The reply goes on on the server; what it has written so far is read back
|
||||
// rather than left half-drawn.
|
||||
_state.update { it.copy(live = null) }
|
||||
refresh()
|
||||
return@launch
|
||||
}
|
||||
// The stream closed without a `done`: the row is gone on the server, or it ended some
|
||||
// way the stream did not tell. The transcript is read again, so what was written is
|
||||
// still there; where it cannot be read, what the stream had shown stays.
|
||||
if (ended == null) {
|
||||
val reread = try {
|
||||
api().chat(chat.id)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
Through.Failed -> {
|
||||
gate.passLater()
|
||||
refresh()
|
||||
}
|
||||
_state.update { it.closedUnfinished(messageId, reread) }
|
||||
// Another reply is being written there (a queued turn): that one is followed.
|
||||
reread?.live?.takeIf { it != messageId }?.let { follow(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun refresh() {
|
||||
val chat = _state.value.chat ?: return
|
||||
runCatching { api().chat(chat.id) }.onSuccess { d ->
|
||||
_state.update { it.copy(chat = d.chat, messages = d.messages, more = d.more) }
|
||||
/** The stream of the reply [messageId], drawn as it comes, to its end; a connection that breaks is opened again at the gate. */
|
||||
private suspend fun stream(chat: Chat, messageId: String): Through {
|
||||
// Set at `done`, which is the end of the reply: from then on the stream is followed
|
||||
// only for the name a model may still give the chat (the `title` frame).
|
||||
var ended: LiveReply? = null
|
||||
var next: String? = null
|
||||
try {
|
||||
StreamClient(api()).follow(chat.id, messageId, turn = { gate.passLater() }).takeWhile { frame ->
|
||||
val before = ended
|
||||
if (before != null) {
|
||||
val named = before.apply(frame.event, frame.data)
|
||||
ended = named
|
||||
if (named.title != before.title) _state.update { s -> s.copy(chat = s.chat?.let { c -> named.title?.let { c.copy(title = it) } ?: c }) }
|
||||
return@takeWhile true
|
||||
}
|
||||
val live = (_state.value.live ?: LiveReply(messageId)).apply(frame.event, frame.data)
|
||||
val finished = live.finished
|
||||
if (finished == null) {
|
||||
// The tree outlives the reply: kept for the activity sheet once it ends.
|
||||
_state.update { s -> s.copy(live = live, tree = live.tree ?: s.tree) }
|
||||
return@takeWhile true
|
||||
}
|
||||
ended = live
|
||||
_state.update { s ->
|
||||
s.copy(
|
||||
live = null,
|
||||
tree = live.tree ?: s.tree,
|
||||
messages = s.messages.map { if (it.id == finished.id) finished else it },
|
||||
chat = s.chat?.let { c -> live.title?.let { c.copy(title = it) } ?: c },
|
||||
)
|
||||
}
|
||||
// With a `next` the queue's reply is followed instead of this stream's tail.
|
||||
next = live.next
|
||||
live.next == null
|
||||
}.collect { }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// After `done` only the name was still to come: nothing to say, nothing to redo.
|
||||
if (ended != null) return Through.Done(next)
|
||||
fail(e)
|
||||
_state.update { it.copy(live = null) }
|
||||
return Through.Failed
|
||||
}
|
||||
return if (ended != null) Through.Done(next) else Through.Closed
|
||||
}
|
||||
|
||||
/**
|
||||
* The transcript as the server has it now, or null where it could not be read. The older
|
||||
* pages the person loaded stay ([withNewest]); [whole] is for a change that rewrote the
|
||||
* transcript itself (a compaction), after which only what was read is true.
|
||||
*/
|
||||
private suspend fun refresh(whole: Boolean = false): ChatDetail? {
|
||||
val chat = _state.value.chat ?: return null
|
||||
val read = try {
|
||||
api().chat(chat.id)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
return null
|
||||
}
|
||||
_state.update { if (whole) it.copy(chat = read.chat, messages = read.messages, more = read.more) else it.withNewest(read).capped(atEnd) }
|
||||
return read
|
||||
}
|
||||
|
||||
private fun took(turn: Turn) {
|
||||
@@ -487,7 +654,7 @@ class ChatViewModel(app: Application) :
|
||||
lastSent = turn.message?.id ?: s.lastSent,
|
||||
)
|
||||
}
|
||||
turn.reply?.let { follow(it.id) }
|
||||
turn.reply?.let { follow(it.id, own = true) }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -531,7 +698,7 @@ class ChatViewModel(app: Application) :
|
||||
forceTool = if (picture) IMAGE_TOOL else null,
|
||||
)
|
||||
_state.update { it.copy(chat = made.chat, messages = listOfNotNull(made.message, made.reply), lastSent = made.message?.id) }
|
||||
made.reply?.let { follow(it.id) }
|
||||
made.reply?.let { follow(it.id, own = true) }
|
||||
} else {
|
||||
took(client.sendMessage(chat.id, text, files, forceTool = if (picture) IMAGE_TOOL else null))
|
||||
}
|
||||
@@ -552,14 +719,42 @@ class ChatViewModel(app: Application) :
|
||||
override fun regenerate(message: Message) = control { api, chat ->
|
||||
val turn = api.regenerate(chat.id, message.id)
|
||||
_state.update { s -> s.copy(messages = s.messages.map { if (it.id == message.id) turn.reply ?: it else it }) }
|
||||
turn.reply?.let { follow(it.id) }
|
||||
turn.reply?.let { follow(it.id, own = true) }
|
||||
}
|
||||
|
||||
override fun edit(message: Message, text: String) = control { api, chat ->
|
||||
val turn = api.edit(chat.id, message.id, text)
|
||||
// Everything after the edited turn is gone on the server; read it back.
|
||||
refresh()
|
||||
turn.reply?.let { follow(it.id) }
|
||||
turn.reply?.let { follow(it.id, own = true) }
|
||||
}
|
||||
|
||||
/**
|
||||
* A waiting message's two actions. Each is one request a tap starts. The reply a send
|
||||
* starts is the person's own, followed as one they typed for; a refusal's read waits until
|
||||
* nothing is being written on this screen (a reply's own stream says everything until
|
||||
* then, and a read beside it could draw a stale row over a finished one), and at the gate.
|
||||
*/
|
||||
private val waiting = WaitingActions(
|
||||
state = _state,
|
||||
read = { refresh() },
|
||||
follow = { follow(it.reply, it.own) },
|
||||
say = ::fail,
|
||||
catchUp = {
|
||||
val mark = reads.mark()
|
||||
_state.first { !it.running }
|
||||
rereadAndFollow(rounds = 1, mark = mark)
|
||||
},
|
||||
)
|
||||
|
||||
override fun sendNow(message: Message) {
|
||||
val chat = _state.value.chat ?: return
|
||||
viewModelScope.launch { waiting.sendNow(message) { api().sendWaiting(chat.id, message.id) } }
|
||||
}
|
||||
|
||||
override fun discard(message: Message) {
|
||||
val chat = _state.value.chat ?: return
|
||||
viewModelScope.launch { waiting.discard(message) { api().discardWaiting(chat.id, message.id) } }
|
||||
}
|
||||
|
||||
override fun continueChat() = control { api, chat -> took(api.continueChat(chat.id)) }
|
||||
@@ -627,7 +822,7 @@ class ChatViewModel(app: Application) :
|
||||
}
|
||||
}
|
||||
try {
|
||||
StreamClient(client).watch { client.activityEvents(chat.id) }.collect { frame ->
|
||||
StreamClient(client).watch(turn = { gate.pass() }) { client.activityEvents(chat.id) }.collect { frame ->
|
||||
if (frame.event != "activity") return@collect
|
||||
val read = runCatching { LembasJson.decodeFromString(ActivityFrame.serializer(), frame.data) }.getOrNull() ?: return@collect
|
||||
val changed = read.version != _state.value.activity?.version
|
||||
@@ -643,6 +838,216 @@ class ChatViewModel(app: Application) :
|
||||
}
|
||||
}
|
||||
|
||||
// --- Generated media's jobs -----------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Follow the chat's long generations while the screen is in front: every job of the chat once
|
||||
* (a finished one's file is drawn on its card), then the ones under way every few seconds --
|
||||
* there is no stream frame for a job. One that ends by itself wakes the chat with a reply this
|
||||
* app did not start: when a job says the chat was told, the transcript is read again and that
|
||||
* reply followed. Runs until cancelled (the screen left, or no longer in front). An instance
|
||||
* without these routes has no jobs, and nothing is asked again. Every request waits at the
|
||||
* gate; how often a finished job was asked whether the chat was told is kept for as long as
|
||||
* the chat is open ([toldWaits]), so a return to the screen does not start that count over.
|
||||
*/
|
||||
private val toldWaits = mutableMapOf<String, Int>()
|
||||
|
||||
suspend fun watchMedia() {
|
||||
val chat = _state.value.chat ?: return
|
||||
val client = runCatching { api() }.getOrNull() ?: return
|
||||
try {
|
||||
gate.pass()
|
||||
val jobs = client.mediaJobs(chat.id)
|
||||
val before = _state.value.mediaJobs
|
||||
_state.update { it.withJobs(jobs, SystemClock.elapsedRealtime()) }
|
||||
// Away and back: a job that told the chat meanwhile left a reply this screen has not read.
|
||||
if (jobs.any { woke(before[it.id]?.job, it) }) rereadAndFollow()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
// An older instance, or one out of reach: the cards say what the calls said.
|
||||
}
|
||||
while (true) {
|
||||
delay(JOB_POLL_MS)
|
||||
val now = _state.value
|
||||
val telling = now.mediaJobs.values.filter { awaitsTelling(it.job) && it.at > 0 && (toldWaits[it.job.id] ?: 0) < TELL_ROUNDS }.map { it.job.id }
|
||||
var woken = false
|
||||
for (id in (now.jobsToRead() + telling).distinct()) {
|
||||
val before = _state.value.mediaJobs[id]?.job
|
||||
// Each a request of its own: none behind a lock, or with the app not in front.
|
||||
gate.pass()
|
||||
val read = try {
|
||||
client.mediaJob(id)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: ApiException) {
|
||||
// Gone, or never this person's: the card says so in the instance's words and is not asked for again.
|
||||
if (e.status != 404) continue
|
||||
val ref = now.jobRefs.firstOrNull { it.id == id }
|
||||
MediaJob(id = id, kind = before?.kind ?: ref?.kind.orEmpty(), state = "expired", error = e.message.orEmpty(), told = true)
|
||||
} catch (_: Exception) {
|
||||
continue
|
||||
}
|
||||
if (awaitsTelling(read)) toldWaits[id] = (toldWaits[id] ?: 0) + 1
|
||||
_state.update { it.withJobs(listOf(read), SystemClock.elapsedRealtime()) }
|
||||
if (woke(before, read)) woken = true
|
||||
}
|
||||
if (woken) rereadAndFollow()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The chat has news (a job ended and told it, the events route said a reply, the app is back
|
||||
* in front): its transcript as the server has it now, and the reply being written there
|
||||
* followed. A job's telling is written a moment before the reply exists, so with two
|
||||
* [rounds], where none is live yet, the chat is read once more shortly after. While this
|
||||
* screen follows a reply nothing is touched: the news waits in the queue, and the stream's
|
||||
* `next` brings it.
|
||||
*
|
||||
* Each read waits at the gate, and goes through [reads]: [mark] is the moment the news was
|
||||
* learned, and a read that began after it has answered already is not made again -- a
|
||||
* burst of frames, or a return that several watchers notice, is one read. [wanted] is asked
|
||||
* once more when it is this one's turn.
|
||||
*/
|
||||
private suspend fun rereadAndFollow(rounds: Int = 2, mark: Long = reads.mark(), wanted: () -> Boolean = { true }) {
|
||||
val chat = _state.value.chat ?: return
|
||||
var since = mark
|
||||
for (round in 0 until rounds) {
|
||||
if (round > 0) {
|
||||
delay(WAKE_PAUSE_MS)
|
||||
// The later round is there to read after the pause: only a read from now on stands for it.
|
||||
since = reads.mark()
|
||||
}
|
||||
gate.passLater()
|
||||
var failed = false
|
||||
reads.since(since, wanted = { _state.value.live == null && wanted() }) {
|
||||
val read = try {
|
||||
api().chat(chat.id)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
failed = true
|
||||
return@since false
|
||||
}
|
||||
if (_state.value.live == null) {
|
||||
_state.update { it.withNewest(read).capped(atEnd) }
|
||||
read.live?.let { follow(it, own = false) }
|
||||
}
|
||||
true
|
||||
}
|
||||
if (failed || _state.value.live != null) return
|
||||
}
|
||||
}
|
||||
|
||||
// --- Replies this app did not start -------------------------------------------------------
|
||||
|
||||
/** Whether this chat's screen has been in front before: the next time is a return. */
|
||||
private var watchedReplies = false
|
||||
|
||||
/** The replies the events route said and that are waiting their turn, so each is taken up once. */
|
||||
private val heard = mutableSetOf<String>()
|
||||
|
||||
/**
|
||||
* Learn of replies nobody asked for from this screen -- a subagent that finished and woke the
|
||||
* main agent, a schedule's result, a helper's wake, a turn the linked computer started --
|
||||
* while the chat is in front: the person's events route says each reply as it starts
|
||||
* (`reply`), and the one for this chat that is not followed already is read and followed as
|
||||
* any reply is. Runs until cancelled (the screen left, or no longer in front).
|
||||
*
|
||||
* On a return to the front the chat is read once: a reply that started and ended meanwhile
|
||||
* is said by nobody. The route is listened to while that read is under way, so a reply that
|
||||
* starts just then is not missed; what it says then is checked against what the read found
|
||||
* before anything is read again. Nothing is asked while the phone is locked or the app is
|
||||
* not in front (`InstanceGate`); what was heard then is taken up on the return. An instance
|
||||
* that does not send the frame changes nothing here but that one read.
|
||||
*/
|
||||
suspend fun watchReplies() {
|
||||
if (_state.value.chat == null) return
|
||||
val app = getApplication<Application>().lembas
|
||||
val back = watchedReplies
|
||||
watchedReplies = true
|
||||
val returned = reads.mark()
|
||||
val frames = runCatching { app.eventFrames() }.getOrNull()
|
||||
try {
|
||||
coroutineScope {
|
||||
if (back) launch { rereadAndFollow(rounds = 1, mark = returned) }
|
||||
frames?.collect { frame ->
|
||||
if (frame.event != "reply") return@collect
|
||||
val said = runCatching { LembasJson.decodeFromString(ReplyFrame.serializer(), frame.data) }.getOrNull() ?: return@collect
|
||||
if (!_state.value.asksFor(said) || !heard.add(said.messageId)) return@collect
|
||||
val learned = reads.mark()
|
||||
// Not in the collector: the one connection is shared, and a watcher that
|
||||
// waits holds the others' frames back.
|
||||
launch {
|
||||
try {
|
||||
takeUp(said, learned)
|
||||
} finally {
|
||||
heard -= said.messageId
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
// An older instance, or the route refused: the chat is read when it is opened, as before.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A reply the events route said, for this chat -- that it started, or (`live` false) that it
|
||||
* ended. While this screen follows a reply of its own nothing is touched: what was said waits
|
||||
* in the queue behind it, and that stream's `next` brings it; once nothing is being written
|
||||
* here, and if it is still news, the transcript is read (it holds the turn the reply answers,
|
||||
* which this screen has not seen either) and the reply being written followed. News that a
|
||||
* read begun since [learned] has already brought costs nothing: the end of a reply this
|
||||
* screen followed to its `done` is no news at all ([asksFor]).
|
||||
*/
|
||||
private suspend fun takeUp(said: ReplyFrame, learned: Long) {
|
||||
gate.pass()
|
||||
_state.first { !it.running }
|
||||
if (!_state.value.asksFor(said)) return
|
||||
rereadAndFollow(rounds = 1, mark = learned) { _state.value.asksFor(said) }
|
||||
}
|
||||
|
||||
/**
|
||||
* "Open in Files" for a generated file: the instance is asked where the file is now, by its
|
||||
* id, and [open] gets that directory. One in the trash, or gone, is said; an instance that
|
||||
* cannot say where a node is opens the folder the file was written to, as before.
|
||||
*/
|
||||
fun whereIs(media: GeneratedMedia, open: (String) -> Unit) {
|
||||
viewModelScope.launch {
|
||||
val app = getApplication<Application>()
|
||||
try {
|
||||
val node = if (media.nodeId.isBlank()) null else api().fileNode(media.nodeId)
|
||||
when (val where = whereabouts(node, media.path)) {
|
||||
is Whereabouts.Folder -> open(where.path)
|
||||
Whereabouts.Trashed -> _state.update { it.copy(error = app.getString(R.string.media_in_trash)) }
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
when {
|
||||
noSuchRoute(e) -> open(media.folder)
|
||||
e is ApiException && e.status == 404 -> _state.update { it.copy(error = app.getString(R.string.media_gone)) }
|
||||
else -> fail(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop a generation: the job as it is after, in the card. One that has ended stays what it was. */
|
||||
fun cancelJob(job: MediaJob) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val after = api().cancelMediaJob(job.id)
|
||||
_state.update { it.withJobs(listOf(after), SystemClock.elapsedRealtime()) }
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var panelOpen = false
|
||||
|
||||
fun panel(open: Boolean) {
|
||||
@@ -687,7 +1092,7 @@ class ChatViewModel(app: Application) :
|
||||
_state.update { it.copy(compacting = true) }
|
||||
try {
|
||||
api().compact(chat.id)
|
||||
refresh()
|
||||
refresh(whole = true)
|
||||
loadActivity()
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
@@ -821,5 +1226,8 @@ class ChatViewModel(app: Application) :
|
||||
|
||||
private companion object {
|
||||
const val MENTION_PAUSE_MS = 250L
|
||||
|
||||
/** Between a job's "the chat was told" and the reply that telling starts. */
|
||||
const val WAKE_PAUSE_MS = 2000L
|
||||
}
|
||||
}
|
||||
@@ -60,14 +60,32 @@ fun transcriptChange(before: List<Message>?, after: List<Message>, restored: Boo
|
||||
/**
|
||||
* Whether the view goes to the end after [change], given whether it was [following]. Opening a
|
||||
* chat and sending a message always do; an older page never does; everything else -- and a reply
|
||||
* growing, a keyboard opening -- only for a person who is at the end already.
|
||||
* growing, a keyboard opening -- only for a person who is at the end already, and never while
|
||||
* the list is being scrolled by the person ([personScrolling]): a wheel, a key or a screen
|
||||
* reader moving it upwards has not come to rest yet, so the following has not ended yet, and
|
||||
* going to the end now would cancel that scroll and throw the reader back down.
|
||||
*/
|
||||
fun movesToEnd(change: TranscriptChange, following: Boolean): Boolean = when (change) {
|
||||
fun movesToEnd(change: TranscriptChange, following: Boolean, personScrolling: Boolean = false): Boolean = when (change) {
|
||||
TranscriptChange.Opened, TranscriptChange.Sent -> true
|
||||
TranscriptChange.None, TranscriptChange.Older -> false
|
||||
TranscriptChange.Appended, TranscriptChange.Changed -> following
|
||||
TranscriptChange.Appended, TranscriptChange.Changed -> following && !personScrolling
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a scroll is the person's. One that is [inProgress] and that this app did not start
|
||||
* ([ownScrolls]: how many of the app's own scrolls are under way) is theirs, whatever moved
|
||||
* the list -- a finger, a wheel, a keyboard, a screen reader. The app marks its own; everything
|
||||
* else is somebody.
|
||||
*/
|
||||
fun personScrolls(inProgress: Boolean, ownScrolls: Int): Boolean = inProgress && ownScrolls <= 0
|
||||
|
||||
/**
|
||||
* Whether a scroll that has come to rest was the person's: a finger was on the list
|
||||
* ([touched]), the list went back towards its start ([wentBack]), or the scroll began with
|
||||
* none of this app's own under way ([startedByApp] false).
|
||||
*/
|
||||
fun scrollWasPersons(touched: Boolean, wentBack: Boolean, startedByApp: Boolean): Boolean = touched || wentBack || !startedByApp
|
||||
|
||||
/**
|
||||
* Whether the view follows, once a scroll has come to rest [distance] pixels short of the end.
|
||||
* Within [slack] counts as the end: a line that arrived while the list was settling must not
|
||||
@@ -75,6 +93,25 @@ fun movesToEnd(change: TranscriptChange, following: Boolean): Boolean = when (ch
|
||||
*/
|
||||
fun followsAt(distance: Int, slack: Int): Boolean = distance <= slack
|
||||
|
||||
/**
|
||||
* Whether the view follows once a scroll has come to rest. Only a scroll the person made
|
||||
* ([byPerson]: a finger on the list, or the list gone back towards its start, which this
|
||||
* app's own scroll to the end never does) can end the following, by where it rests. Any other scroll is this
|
||||
* app's own keeping to the end; a line, a card or a picture that arrived before it settled
|
||||
* leaves it short of the end without anybody having left, and reading that as "scrolled away"
|
||||
* is what switches the following off under a person who never moved. Such a scroll can only
|
||||
* take the following up (it rested at the end), never end it.
|
||||
*/
|
||||
fun restFollows(following: Boolean, byPerson: Boolean, distance: Int, slack: Int): Boolean = if (byPerson) {
|
||||
followsAt(distance, slack)
|
||||
} else {
|
||||
following ||
|
||||
followsAt(distance, slack)
|
||||
}
|
||||
|
||||
/** Whether a list that stood at row [fromIndex], [fromOffset] pixels into it, has gone back towards its start. */
|
||||
fun wentBack(fromIndex: Int, fromOffset: Int, toIndex: Int, toOffset: Int): Boolean = toIndex < fromIndex || (toIndex == fromIndex && toOffset < fromOffset)
|
||||
|
||||
/**
|
||||
* The row that keeps its place when an older page arrives while the list stands at its very
|
||||
* top: the first row there was before, by its place in [after]. Null when it is gone.
|
||||
@@ -97,3 +134,17 @@ suspend fun yielding(scroll: suspend () -> Unit) {
|
||||
currentCoroutineContext().ensureActive()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [yielding], counted in [own] while it runs: how the list's watchers tell this app's scroll
|
||||
* from the person's ([personScrolls]). A count and not a flag: one of the app's scrolls may
|
||||
* overtake another, and the first one's end must not unmark the second.
|
||||
*/
|
||||
suspend fun ownScroll(own: IntArray, scroll: suspend () -> Unit) {
|
||||
own[0]++
|
||||
try {
|
||||
yielding(scroll)
|
||||
} finally {
|
||||
own[0]--
|
||||
}
|
||||
}
|
||||
@@ -11,12 +11,15 @@ import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
@@ -36,34 +39,52 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.GeneratedImage
|
||||
import eu.llembas.android.api.GeneratedMedia
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
/**
|
||||
* The pictures the instance made, fetched the one way the app fetches a chat's files: by
|
||||
* attachment id, from the instance it is signed in to, with its token. There is no URL to
|
||||
* follow -- a model's words can name an address, but never a picture this draws -- and nothing
|
||||
* bigger than [MAX_BYTES] is decoded.
|
||||
* The pictures the instance made, fetched the two ways the app fetches a chat's files: by
|
||||
* attachment id, or -- for a generated file with no attachment -- by its node id in the
|
||||
* person's Files; always from the instance it is signed in to, with its token. There is no URL
|
||||
* to follow -- a model's words can name an address, but never a picture this draws -- and
|
||||
* nothing bigger than [MAX_BYTES] is decoded.
|
||||
*/
|
||||
private object Pictures {
|
||||
/** Longest edge decoded: enough for a phone held either way, small enough to keep a few. */
|
||||
private const val EDGE = 1600
|
||||
private const val MAX_BYTES = 24 * 1024 * 1024
|
||||
const val MAX_BYTES = 24L * 1024 * 1024
|
||||
private val cache = LruCache<String, ImageBitmap>(8)
|
||||
private val failed = mutableSetOf<String>()
|
||||
private val gone = mutableSetOf<String>()
|
||||
|
||||
fun cached(id: String): ImageBitmap? = cache.get(id)
|
||||
fun cached(key: String): ImageBitmap? = cache.get(key)
|
||||
|
||||
suspend fun load(context: Context, id: String): ImageBitmap? {
|
||||
cache.get(id)?.let { return it }
|
||||
if (id.isBlank() || id in failed) return null
|
||||
/** Whether the instance said there is no such file (any more). */
|
||||
fun isGone(key: String): Boolean = key in gone
|
||||
|
||||
suspend fun load(context: Context, key: String, fetch: suspend (ApiClient) -> ByteArray): ImageBitmap? {
|
||||
cache.get(key)?.let { return it }
|
||||
if (key in failed) return null
|
||||
val api = context.lembas.instances.client() ?: return null
|
||||
val bytes = runCatching { api.attachmentBytes(id) }.getOrNull()?.takeIf { it.size <= MAX_BYTES }
|
||||
val bytes = try {
|
||||
fetch(api).takeIf { it.size <= MAX_BYTES }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
if (e is ApiException && e.status == 404) gone += key
|
||||
null
|
||||
}
|
||||
val image = bytes?.let { decode(it) }
|
||||
if (image == null) failed += id else cache.put(id, image)
|
||||
if (image == null) failed += key else cache.put(key, image)
|
||||
return image
|
||||
}
|
||||
|
||||
@@ -84,20 +105,57 @@ private object Pictures {
|
||||
*/
|
||||
@Composable
|
||||
fun GeneratedPicture(image: GeneratedImage, modifier: Modifier = Modifier) {
|
||||
if (image.id.isBlank()) return
|
||||
Picture("attachment:" + image.id, image.width, image.height, modifier) { api -> api.attachmentBytes(image.id) }
|
||||
}
|
||||
|
||||
/**
|
||||
* A generated picture that is a file of the person's Files and no attachment: fetched by its
|
||||
* node id from `/files/raw`, drawn the same way. One the person has since put in the trash
|
||||
* says that it is no longer there.
|
||||
*/
|
||||
@Composable
|
||||
fun GeneratedPicture(media: GeneratedMedia, modifier: Modifier = Modifier) {
|
||||
if (media.nodeId.isBlank()) return
|
||||
Picture("node:" + media.nodeId, media.width, media.height, modifier) { api ->
|
||||
// What the server says it weighs decides before a byte is asked for.
|
||||
if (media.size > Pictures.MAX_BYTES) throw ApiException(413, "")
|
||||
val held = ByteArrayOutputStream()
|
||||
api.download(api.raw(Raw.Node(media.nodeId), inline = true), held, most = Pictures.MAX_BYTES)
|
||||
held.toByteArray()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The shape a picture's place is given before its bytes are there: width over height, from the
|
||||
* size the server said, kept between a quarter and four. A size the server did not say is a
|
||||
* square. The place is that shape from its first draw to its last, so the picture arriving (or
|
||||
* not arriving) moves nothing in the transcript.
|
||||
*/
|
||||
internal fun pictureRatio(width: Int, height: Int): Float = if (width > 0 && height > 0) (width.toFloat() / height).coerceIn(0.25f, 4f) else 1f
|
||||
|
||||
@Composable
|
||||
private fun Picture(key: String, width: Int, height: Int, modifier: Modifier, fetch: suspend (ApiClient) -> ByteArray) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
val still = LocalInspectionMode.current
|
||||
var bitmap by remember(image.id) { mutableStateOf(Pictures.cached(image.id)) }
|
||||
var bitmap by remember(key) { mutableStateOf(Pictures.cached(key)) }
|
||||
var gone by remember(key) { mutableStateOf(Pictures.isGone(key)) }
|
||||
var whole by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(image.id) { if (bitmap == null && !still) bitmap = Pictures.load(context, image.id) }
|
||||
val ratio = if (image.width > 0 && image.height > 0) image.width.toFloat() / image.height else 1f
|
||||
LaunchedEffect(key) {
|
||||
if (bitmap == null && !still) {
|
||||
bitmap = Pictures.load(context, key, fetch)
|
||||
gone = Pictures.isGone(key)
|
||||
}
|
||||
}
|
||||
val ratio = pictureRatio(width, height)
|
||||
val shape = RoundedCornerShape(16.dp)
|
||||
val described = stringResource(R.string.image_generated)
|
||||
Box(
|
||||
modifier
|
||||
.widthIn(max = 480.dp)
|
||||
.fillMaxWidth()
|
||||
.aspectRatio(ratio.coerceIn(0.25f, 4f))
|
||||
.aspectRatio(ratio)
|
||||
.clip(shape)
|
||||
.background(palette.surfaceRaised)
|
||||
.border(1.dp, palette.border, shape)
|
||||
@@ -107,6 +165,8 @@ fun GeneratedPicture(image: GeneratedImage, modifier: Modifier = Modifier) {
|
||||
val shown = bitmap
|
||||
if (shown != null) {
|
||||
Image(shown, contentDescription = described, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
|
||||
} else if (gone) {
|
||||
Text(stringResource(R.string.media_gone), color = palette.inkMuted, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(16.dp))
|
||||
} else {
|
||||
Icon(Icons.Filled.Image, contentDescription = described, tint = palette.inkFaint, modifier = Modifier.size(32.dp))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.os.SystemClock
|
||||
import android.text.format.Formatter
|
||||
import androidx.compose.foundation.border
|
||||
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.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
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.OpenInNew
|
||||
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.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.PlayArrow
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material.icons.filled.ViewInAr
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.FilledIconButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.IconButtonDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableLongStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalInspectionMode
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Attachment
|
||||
import eu.llembas.android.api.GeneratedImage
|
||||
import eu.llembas.android.api.GeneratedMedia
|
||||
import eu.llembas.android.api.MediaJob
|
||||
import eu.llembas.android.api.MediaView
|
||||
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.
|
||||
// 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
|
||||
// is never over the lock screen; the assistant's sheet provides none and draws none.
|
||||
|
||||
/** What the media cards of a chat can do; nothing by default, for the screenshot tests. */
|
||||
interface MediaActions {
|
||||
/** Play a generated video or track, over the chat. */
|
||||
fun play(media: GeneratedMedia) {}
|
||||
|
||||
/** Play sound or video the person attached. */
|
||||
fun play(attachment: Attachment) {}
|
||||
|
||||
/** The folder of the person's Files the file is in. */
|
||||
fun openInFiles(media: GeneratedMedia) {}
|
||||
|
||||
/** Save it where the person chooses (the system's "Save to" page). */
|
||||
fun download(media: GeneratedMedia) {}
|
||||
|
||||
fun share(media: GeneratedMedia) {}
|
||||
|
||||
fun openWith(media: GeneratedMedia) {}
|
||||
|
||||
/** Stop a generation that is under way. */
|
||||
fun cancel(job: MediaJob) {}
|
||||
}
|
||||
|
||||
/** A chat's generated media as its cards need it: what is known of its jobs, and what a card can do. */
|
||||
class ChatMedia(val jobs: Map<String, JobSeen>, val actions: MediaActions)
|
||||
|
||||
/** Provided by the chat's screen; null anywhere else, and then no media card is drawn. */
|
||||
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
|
||||
}
|
||||
|
||||
private 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
|
||||
}
|
||||
|
||||
/** What is known of a file, in one line: what it is, how long, how large, its size in pixels. */
|
||||
@Composable
|
||||
internal fun mediaFacts(media: GeneratedMedia): String {
|
||||
val context = LocalContext.current
|
||||
return listOfNotNull(
|
||||
mediaKind(media.kind).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,
|
||||
).joinToString(" · ")
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
@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,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Four buttons of 48 dp: nothing here depends on how long a word is in any language.
|
||||
Row {
|
||||
CardButton(Icons.Filled.FolderOpen, R.string.media_open_in_files) { actions.openInFiles(media) }
|
||||
CardButton(Icons.Filled.Download, R.string.download) { actions.download(media) }
|
||||
CardButton(Icons.Filled.Share, R.string.report_share) { actions.share(media) }
|
||||
CardButton(Icons.AutoMirrored.Filled.OpenInNew, R.string.files_open_with) { actions.openWith(media) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CardButton(icon: ImageVector, label: Int, onClick: () -> Unit) {
|
||||
IconButton(onClick = onClick) { Icon(icon, contentDescription = stringResource(label), tint = LocalPalette.current.inkMuted) }
|
||||
}
|
||||
|
||||
/** The word for where a job stands; a state this app does not know is said as the server says it. */
|
||||
@Composable
|
||||
internal fun jobState(state: String): String = when (state) {
|
||||
"queued" -> stringResource(R.string.job_queued)
|
||||
"running" -> stringResource(R.string.job_running)
|
||||
"done" -> stringResource(R.string.job_done)
|
||||
"failed" -> stringResource(R.string.job_failed)
|
||||
"cancelled" -> stringResource(R.string.job_cancelled)
|
||||
"expired" -> stringResource(R.string.job_expired)
|
||||
else -> state
|
||||
}
|
||||
|
||||
/**
|
||||
* A generation that takes minutes, on the card of the call that started it: what is being made,
|
||||
* where it stands and for how long, and Cancel while it is under way. One that ended without a
|
||||
* file says why in the server's own sentence. The mark keeps its 48 dp and Cancel its own width;
|
||||
* the words between them give.
|
||||
*/
|
||||
@Composable
|
||||
fun JobCard(seen: JobSeen, actions: MediaActions, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
val still = LocalInspectionMode.current
|
||||
val job = seen.job
|
||||
var now by remember { mutableLongStateOf(if (still) seen.at else SystemClock.elapsedRealtime()) }
|
||||
// The clock on the card runs on the phone between two reads of the job.
|
||||
LaunchedEffect(job.id, job.underWay) {
|
||||
while (job.underWay && !still) {
|
||||
now = SystemClock.elapsedRealtime()
|
||||
delay(1000)
|
||||
}
|
||||
}
|
||||
Row(
|
||||
modifier.widthIn(max = 480.dp).fillMaxWidth().border(1.dp, palette.border, CardShape).padding(start = 12.dp, end = 4.dp, top = 10.dp, bottom = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) {
|
||||
when {
|
||||
// A wheel that never ends never lets a screenshot be taken: a still mark there.
|
||||
job.underWay && !still -> CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(24.dp))
|
||||
|
||||
job.underWay -> Icon(Icons.Filled.HourglassEmpty, contentDescription = null, tint = palette.inkMuted)
|
||||
|
||||
job.unsuccessful -> Icon(
|
||||
Icons.Filled.ErrorOutline,
|
||||
contentDescription = null,
|
||||
tint = if (job.state ==
|
||||
"failed"
|
||||
) {
|
||||
palette.danger
|
||||
} else {
|
||||
palette.inkMuted
|
||||
},
|
||||
)
|
||||
|
||||
else -> Icon(mediaIcon(job.kind), contentDescription = null, tint = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
listOf(mediaKind(job.kind), jobState(job.state)).filter { it.isNotBlank() }.joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = palette.ink,
|
||||
)
|
||||
val elapsed = seen.elapsed(now)
|
||||
val facts = listOfNotNull(
|
||||
if (elapsed >
|
||||
0
|
||||
) {
|
||||
playTime((elapsed * 1000).coerceAtMost(Int.MAX_VALUE.toLong()).toInt())
|
||||
} else {
|
||||
null
|
||||
},
|
||||
job.source.ifBlank { null },
|
||||
)
|
||||
if (facts.isNotEmpty()) {
|
||||
Text(
|
||||
facts.joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
// Why it was not made, in the instance's words: a sentence for the person, shown whole.
|
||||
if (job.unsuccessful && job.error.isNotBlank()) {
|
||||
Text(
|
||||
job.error,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = if (job.state == "failed") palette.danger else palette.inkMuted,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (job.underWay) {
|
||||
TextButton(onClick = { actions.cancel(job) }) { Text(stringResource(R.string.cancel)) }
|
||||
} else {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What a call that made media leaves in the reply, always in view: its file's card; or its
|
||||
* job's card, which becomes the file's once the job is done.
|
||||
*/
|
||||
@Composable
|
||||
fun CallMedia(media: GeneratedMedia?, image: GeneratedImage?, job: JobSeen?, chat: ChatMedia) {
|
||||
if (media != null) MediaCard(media, image, chat.actions)
|
||||
if (job != null) {
|
||||
val result = job.job.result
|
||||
if (result != null && job.job.state == MediaJob.DONE) MediaCard(result, null, chat.actions) else JobCard(job, chat.actions)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import eu.llembas.android.api.MediaJob
|
||||
import eu.llembas.android.api.MediaJobRef
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.ToolCall
|
||||
|
||||
// A chat's long generations as the chat keeps them. There is no stream frame for a job -- a chat
|
||||
// has no stream while no reply is being written -- so the jobs under way are read again every few
|
||||
// seconds while the chat is in front, and the chat is read again when one of them has woken it.
|
||||
|
||||
/** A job as it was last read, and when ([at], the phone's uptime clock; 0: known only from the call). */
|
||||
data class JobSeen(val job: MediaJob, val at: Long = 0) {
|
||||
/** How long it has taken, in seconds, at [now]: counted on from the read while it is under way. */
|
||||
fun elapsed(now: Long): Long {
|
||||
val said = job.seconds.toLong().coerceAtLeast(0)
|
||||
return if (job.underWay && at > 0 && now > at) said + (now - at) / 1000 else said
|
||||
}
|
||||
}
|
||||
|
||||
/** How often jobs under way are read again. */
|
||||
const val JOB_POLL_MS = 3000L
|
||||
|
||||
/** How many more reads a job that has ended is given to say that the chat was told. */
|
||||
const val TELL_ROUNDS = 20
|
||||
|
||||
private fun calls(steps: List<Step>): Sequence<ToolCall> {
|
||||
fun all(call: ToolCall): Sequence<ToolCall> = sequenceOf(call) + call.children.orEmpty().asSequence().flatMap { all(it) }
|
||||
return steps.asSequence().flatMap { it.calls.asSequence() }.flatMap { all(it) }
|
||||
}
|
||||
|
||||
/** Every job the calls of these messages (and of the steps being written, [live]) started, each once, in the order the calls come. */
|
||||
fun jobRefsOf(messages: List<Message>, live: List<Step> = emptyList()): List<MediaJobRef> {
|
||||
val all = messages.asSequence().flatMap { calls(it.steps) } + calls(live)
|
||||
return all.mapNotNull { it.mediaJob?.takeIf { ref -> ref.id.isNotBlank() } }.distinctBy { it.id }.toList()
|
||||
}
|
||||
|
||||
/** The jobs this chat's calls started (the reply being written included). */
|
||||
val ChatState.jobRefs: List<MediaJobRef> get() = jobRefsOf(messages, live?.shown.orEmpty())
|
||||
|
||||
/**
|
||||
* A job that has ended and has not said yet that the chat was told: the reply about it is still
|
||||
* to come, so it is read a few more times. A cancelled job wakes nobody.
|
||||
*/
|
||||
fun awaitsTelling(job: MediaJob): Boolean = !job.underWay && !job.told && job.state != MediaJob.CANCELLED
|
||||
|
||||
/**
|
||||
* The jobs to read again: the ones a call names that were never read (the call's own word is
|
||||
* from the moment it returned), and the ones under way. A job that has ended is left alone.
|
||||
*/
|
||||
fun ChatState.jobsToRead(): List<String> {
|
||||
val named = jobRefs.map { it.id }.filter { mediaJobs[it]?.let { seen -> seen.at == 0L || seen.job.underWay } ?: true }
|
||||
val known = mediaJobs.values.filter { it.job.underWay }.map { it.job.id }
|
||||
return (named + known).distinct()
|
||||
}
|
||||
|
||||
/** [jobs], read at [at], among what the chat knows of its jobs. */
|
||||
fun ChatState.withJobs(jobs: List<MediaJob>, at: Long): ChatState =
|
||||
if (jobs.isEmpty()) this else copy(mediaJobs = mediaJobs + jobs.filter { it.id.isNotBlank() }.associate { it.id to JobSeen(it, at) })
|
||||
|
||||
/**
|
||||
* Whether a read says the chat was woken since the last one: the job was known and had not told
|
||||
* the chat, and now has. Then there is a reply this app did not start, and the transcript is
|
||||
* read again. A job first heard of already told is part of the transcript that was just read.
|
||||
*/
|
||||
fun woke(before: MediaJob?, after: MediaJob): Boolean = before != null && !before.told && after.told
|
||||
|
||||
/** What a call's job is drawn from: what was read of it, else the call's own word. */
|
||||
fun ChatMedia.job(ref: MediaJobRef): JobSeen = jobs[ref.id] ?: JobSeen(MediaJob.of(ref))
|
||||
@@ -28,7 +28,6 @@ import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.api.titleAmong
|
||||
import eu.llembas.android.ui.ModelAvatar
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
@@ -101,8 +100,9 @@ fun ModelPickerContent(models: List<ModelInfo>, current: String?, onPick: (Strin
|
||||
modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp),
|
||||
)
|
||||
LazyColumn(Modifier.fillMaxWidth().padding(bottom = 16.dp)) {
|
||||
// By its ref: two connections may serve one id, and a row is its own key.
|
||||
val inUse = models.named(current)?.key
|
||||
// [current] is the key of the row in use, looked up by the caller, who knows how the name
|
||||
// was said: a chat's `model_ref` that is not in the list ticks no row, never one with that id.
|
||||
val inUse = current
|
||||
items(models.distinctBy { it.key }, key = { it.key }) { m ->
|
||||
val chosen = m.key == inUse
|
||||
Row(
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
|
||||
/**
|
||||
* The reads of one thing (a chat's transcript) that several pieces of news ask for, one at a
|
||||
* time and none twice for the same news. Whoever learns something that needs a read takes a
|
||||
* [mark] at that moment -- before waiting for anything -- and asks [since] it; a read that began
|
||||
* after the mark and came back has seen what the mark's news was about, so the asker's own is
|
||||
* not made. A burst of frames, or a return to the front that several watchers notice, is then
|
||||
* one read; news that arrives while a read is under way is newer than that read, and gets its own.
|
||||
*/
|
||||
class Reads {
|
||||
private val one = Mutex()
|
||||
|
||||
/** How many reads have begun. */
|
||||
private var begun = 0L
|
||||
|
||||
/** The last read that came back with an answer, by its number. */
|
||||
private var answered = 0L
|
||||
|
||||
/** The moment some news was learned: every read that begins from now on covers it. */
|
||||
fun mark(): Long = begun
|
||||
|
||||
/**
|
||||
* [read], unless a read that began after [mark] has already answered, or [wanted] says -- once
|
||||
* it is this asker's turn -- that nothing is asked for any more. [read] says whether it got
|
||||
* an answer; one that did not covers nobody. True when [read] ran.
|
||||
*/
|
||||
suspend fun since(mark: Long, wanted: () -> Boolean = { true }, read: suspend () -> Boolean): Boolean = one.withLock {
|
||||
if (answered > mark || !wanted()) return@withLock false
|
||||
val mine = ++begun
|
||||
if (read()) answered = mine
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -13,11 +13,14 @@ import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
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.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
@@ -41,6 +44,8 @@ import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
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.Psychology
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.SelectAll
|
||||
@@ -84,11 +89,15 @@ import androidx.compose.ui.unit.sp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Attachment
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.ShowCard
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.ToolCall
|
||||
import eu.llembas.android.api.Waiting
|
||||
import eu.llembas.android.api.ending
|
||||
import eu.llembas.android.api.replyModel
|
||||
import eu.llembas.android.api.shownMarkdown
|
||||
import eu.llembas.android.api.waiting
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.MarkdownText
|
||||
import eu.llembas.android.ui.Segment
|
||||
@@ -107,13 +116,32 @@ private val Bubble = RoundedCornerShape(topStart = 20.dp, topEnd = 6.dp, bottomS
|
||||
private val Block = RoundedCornerShape(12.dp)
|
||||
private val Pill = RoundedCornerShape(50)
|
||||
|
||||
/** A reply's foot: the gap above it, and the height of its row of buttons (an icon button's 48 dp). */
|
||||
private val FootTop = 2.dp
|
||||
private val FootHeight = 48.dp
|
||||
|
||||
/** A waiting message's two buttons: a tap target's height. */
|
||||
private val WaitingButton = 48.dp
|
||||
|
||||
/**
|
||||
* The person's turn: their words in a bubble on the right (never markdown), what they attached
|
||||
* above it as thumbnails. A long press offers Copy and, where the turn can still change, Edit.
|
||||
*
|
||||
* A message that waits says how it waits in words under the bubble, and -- where [onSendNow]
|
||||
* and [onDiscard] are given, which only the chat's own screen does -- offers the two things a
|
||||
* person does with it. They rest while [busy]: one of them is being asked of the instance.
|
||||
*/
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@OptIn(ExperimentalFoundationApi::class, ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun UserMessage(message: Message, canEdit: Boolean, onEdit: () -> Unit, modifier: Modifier = Modifier) {
|
||||
fun UserMessage(
|
||||
message: Message,
|
||||
canEdit: Boolean,
|
||||
onEdit: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
busy: Boolean = false,
|
||||
onSendNow: (() -> Unit)? = null,
|
||||
onDiscard: (() -> Unit)? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val copy = LocalCopy.current
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
@@ -160,14 +188,32 @@ fun UserMessage(message: Message, canEdit: Boolean, onEdit: () -> Unit, modifier
|
||||
}
|
||||
}
|
||||
}
|
||||
if (message.queued) {
|
||||
// The server's queued progress ("Queued, 2 ahead · 12s") where it sends one.
|
||||
message.waiting?.let { waiting ->
|
||||
// How it waits, in words. Queued behind a reply: the server's progress ("Queued: 2
|
||||
// ahead · 12s") where it sends one. Not for one a linked computer was handed: that
|
||||
// one waits for the person or for the computer, not for its turn here.
|
||||
Text(
|
||||
progressLineOf(message.progress) ?: stringResource(R.string.queued),
|
||||
when (waiting) {
|
||||
Waiting.Unsure -> stringResource(R.string.fate_unknown)
|
||||
Waiting.Carried -> stringResource(R.string.fate_carried)
|
||||
Waiting.Queued -> progressLineOf(message.progress) ?: stringResource(R.string.queued)
|
||||
},
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
color = if (waiting == Waiting.Unsure) palette.warning else palette.inkFaint,
|
||||
modifier = Modifier.padding(top = 4.dp, end = 4.dp),
|
||||
)
|
||||
if (onSendNow != null && onDiscard != null) {
|
||||
// Two buttons of unknown width (eight languages, any type size): they share a
|
||||
// row that wraps, each a full tap target, from the bubble's edge.
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.End)) {
|
||||
TextButton(onClick = onDiscard, enabled = !busy, modifier = Modifier.heightIn(min = WaitingButton)) {
|
||||
Text(stringResource(R.string.discard))
|
||||
}
|
||||
TextButton(onClick = onSendNow, enabled = !busy, modifier = Modifier.heightIn(min = WaitingButton)) {
|
||||
Text(stringResource(R.string.send_now))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -206,6 +252,8 @@ fun AssistantMessage(
|
||||
onRegenerate: () -> Unit,
|
||||
onShow: ((ShowCard) -> Unit)?,
|
||||
modifier: Modifier = Modifier,
|
||||
/** The models offered here: a reply by one of two that share an id says its connection. */
|
||||
models: List<ModelInfo> = emptyList(),
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val copy = LocalCopy.current
|
||||
@@ -246,7 +294,10 @@ fun AssistantMessage(
|
||||
}
|
||||
}
|
||||
if (writing) {
|
||||
Writing(Modifier.padding(top = if (steps.isEmpty()) 0.dp else 8.dp), withLine = steps.isEmpty())
|
||||
// Once there is something written, the pulse stands in the finished reply's foot --
|
||||
// the same top and the same height as its row of buttons -- so the reply ending
|
||||
// does not change the row's height under a person at the end of it.
|
||||
if (steps.isEmpty()) Writing(withLine = true) else Writing(Modifier.padding(top = FootTop), minHeight = FootHeight)
|
||||
} else {
|
||||
// How a reply that did not finish ended (display.md §4): the progress text alone --
|
||||
// "Stopped: by you", "Failed: …" -- staying at the end of the reply; an error in
|
||||
@@ -260,7 +311,7 @@ fun AssistantMessage(
|
||||
)
|
||||
}
|
||||
// The actions and the foot share one row: the icons keep their 48 dp, the foot gives.
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 2.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = FootTop)) {
|
||||
if (words.isNotBlank()) {
|
||||
IconButton(onClick = { copy(words) }) {
|
||||
Icon(
|
||||
@@ -292,7 +343,7 @@ fun AssistantMessage(
|
||||
)
|
||||
}
|
||||
}
|
||||
footLine(message)?.let { line ->
|
||||
footLine(message, models)?.let { line ->
|
||||
Text(
|
||||
line,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
@@ -334,11 +385,12 @@ fun replyText(message: Message): String = pageProjection(
|
||||
private const val PAGE_UNTITLED = "Page"
|
||||
|
||||
/** What a finished reply cost, in one quiet line: model, tokens, speed. Null when nothing was counted. */
|
||||
private fun footLine(message: Message): String? {
|
||||
val m = message.metrics ?: return message.model
|
||||
if (m.completionTokens == 0 && m.elapsedMs == 0L) return message.model
|
||||
internal fun footLine(message: Message, models: List<ModelInfo> = emptyList()): String? {
|
||||
val model = models.replyModel(message.modelRef, message.model)
|
||||
val m = message.metrics ?: return model
|
||||
if (m.completionTokens == 0 && m.elapsedMs == 0L) return model
|
||||
return buildList {
|
||||
message.model?.let { add(it) }
|
||||
model?.let { add(it) }
|
||||
if (m.completionTokens > 0) add("${if (m.estimated) "~" else ""}${m.completionTokens} tok")
|
||||
if (m.tokPerSecond > 0) add("${"%.1f".format(m.tokPerSecond)} tok/s")
|
||||
}.joinToString(" · ").ifBlank { null }
|
||||
@@ -346,13 +398,13 @@ private fun footLine(message: Message): String? {
|
||||
|
||||
/** Three dots that breathe, and (before the first word) the loading line beside them. */
|
||||
@Composable
|
||||
fun Writing(modifier: Modifier = Modifier, withLine: Boolean = false) {
|
||||
fun Writing(modifier: Modifier = Modifier, withLine: Boolean = false, minHeight: Dp = 32.dp) {
|
||||
val palette = LocalPalette.current
|
||||
// Still in a preview or a screenshot, where an animation that never ends never lets the
|
||||
// picture be taken.
|
||||
val still = LocalInspectionMode.current
|
||||
val pulse = rememberInfiniteTransition(label = "writing")
|
||||
Row(modifier.heightIn(min = 32.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Row(modifier.heightIn(min = minHeight), verticalAlignment = Alignment.CenterVertically) {
|
||||
repeat(3) { i ->
|
||||
val alpha = if (still) {
|
||||
listOf(1f, 0.6f, 0.3f)[i]
|
||||
@@ -588,9 +640,20 @@ private fun ToolsChip(step: Step, onShow: ((ShowCard) -> Unit)?) {
|
||||
}
|
||||
}
|
||||
shows.forEach { call -> ToolCallBlock(call, onShow = onShow) }
|
||||
// A picture the instance made stays in view, like a `show` card: it is the answer.
|
||||
step.calls.mapNotNull { call -> call.image?.takeIf { it.id.isNotBlank() && call.status != "error" && call.error.isNullOrEmpty() } }
|
||||
.forEach { GeneratedPicture(it) }
|
||||
// What the instance made stays in view, like a `show` card: it is the answer. A picture as
|
||||
// before; in a chat's own screen also the file's card (a player, the ways to the file) and
|
||||
// the card of a generation still under way. Elsewhere -- the assistant's sheet, which may be
|
||||
// over the lock screen -- only the picture, as before.
|
||||
val media = LocalChatMedia.current
|
||||
step.calls.filter { it.status != "error" && it.error.isNullOrEmpty() }.forEach { call ->
|
||||
val image = call.image?.takeIf { it.id.isNotBlank() }
|
||||
if (media == null) {
|
||||
image?.let { GeneratedPicture(it) }
|
||||
} else {
|
||||
if (call.media == null) image?.let { GeneratedPicture(it) }
|
||||
CallMedia(call.media, image, call.mediaJob?.takeIf { it.id.isNotBlank() }?.let { media.job(it) }, media)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -641,7 +704,17 @@ private object Thumbnails {
|
||||
fun AttachmentTile(attachment: Attachment, side: Dp, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
Box(modifier.size(side).clip(Block).background(palette.surfaceRaised).border(1.dp, palette.border, Block), contentAlignment = Alignment.Center) {
|
||||
// Sound and video the person attached are played, where a chat's screen has a player.
|
||||
val play = LocalChatMedia.current?.actions?.takeIf { attachment.kind == "audio" || attachment.kind == "video" }
|
||||
Box(
|
||||
modifier
|
||||
.size(side)
|
||||
.clip(Block)
|
||||
.background(palette.surfaceRaised)
|
||||
.border(1.dp, palette.border, Block)
|
||||
.then(if (play != null) Modifier.clickable(onClickLabel = stringResource(R.string.play)) { play.play(attachment) } else Modifier),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (attachment.image) {
|
||||
var image by remember(attachment.id) { mutableStateOf(Thumbnails.cached(attachment.id)) }
|
||||
val still = LocalInspectionMode.current
|
||||
@@ -654,7 +727,15 @@ fun AttachmentTile(attachment: Attachment, side: Dp, modifier: Modifier = Modifi
|
||||
}
|
||||
} else {
|
||||
Column(Modifier.padding(8.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Icon(Icons.Filled.Description, contentDescription = null, tint = palette.inkMuted)
|
||||
Icon(
|
||||
when (attachment.kind) {
|
||||
"audio" -> Icons.Filled.MusicNote
|
||||
"video" -> Icons.Filled.Movie
|
||||
else -> Icons.Filled.Description
|
||||
},
|
||||
contentDescription = null,
|
||||
tint = if (play != null) palette.accent else palette.inkMuted,
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
attachment.name,
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.ChatDetail
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Turn
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
|
||||
/**
|
||||
* A waiting message was sent now ([turn], the instance's answer): its row is the message as it
|
||||
* is after -- no longer waiting -- where it stood, and the reply started for it is the last row.
|
||||
* No row is there twice: the list's rows are keyed by id.
|
||||
*/
|
||||
fun ChatState.sentNow(turn: Turn): ChatState {
|
||||
val sent = turn.message
|
||||
val reply = turn.reply
|
||||
val rows = messages.filterNot { it.id == reply?.id }.map { if (it.id == sent?.id) sent else it }
|
||||
return copy(messages = rows + listOfNotNull(reply), lastSent = sent?.id ?: lastSent)
|
||||
}
|
||||
|
||||
/** A waiting message was discarded: its row is gone, and nothing else moved. */
|
||||
fun ChatState.discarded(id: String): ChatState = copy(messages = messages.filterNot { it.id == id })
|
||||
|
||||
/**
|
||||
* Whether a refusal says the screen showed a message as waiting that is not so any more, or
|
||||
* could not be acted on as shown: 409 (a reply is being written; the message no longer waits)
|
||||
* and 404 (it is not there). The chat is then read again. Anything else -- no network, a server
|
||||
* error -- says nothing about the message, and the row stays as it is.
|
||||
*/
|
||||
fun staleWaiting(e: Throwable): Boolean = e is ApiException && (e.status == 409 || e.status == 404)
|
||||
|
||||
/** A reply to follow, and whether the person asked for it from this screen. */
|
||||
data class Followed(val reply: String, val own: Boolean)
|
||||
|
||||
/**
|
||||
* Which reply is followed once a waiting message was sent now: the one the send started
|
||||
* ([reply]), as a reply the person asked for from this screen -- unless the chat, [read] after
|
||||
* the send, no longer holds it as being written. That happens by design: a linked computer
|
||||
* that still knew the message does not run it a second time, and the reply started for it is
|
||||
* removed. Then whatever else the read says is being written is followed, as nobody's.
|
||||
*/
|
||||
fun followedAfterSend(reply: String?, read: ChatDetail?): Followed? {
|
||||
if (reply != null && (read == null || read.live == reply || read.messages.any { it.id == reply && !it.complete })) {
|
||||
return Followed(reply, own = true)
|
||||
}
|
||||
return read?.live?.let { Followed(it, own = false) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The two things a person does with a message that waits, as the chat's screen does them. The
|
||||
* instance is asked through each action's own request; what the screen shows is [state].
|
||||
*
|
||||
* Sent: the row stops waiting at once, the chat is read ([read]; a chat on a linked computer
|
||||
* sorts the message to where it was sent), and the reply started for it is followed ([follow])
|
||||
* exactly as one the person asked for by typing. Discarded: the row is gone. Refused with a
|
||||
* 409 or a 404: the instance's sentence is said ([say]) and the chat is read again
|
||||
* ([catchUp]), because what the screen showed as waiting is not so any more. While one of the
|
||||
* two is under way for a message, [ChatState.acting] names it and its buttons rest.
|
||||
*/
|
||||
class WaitingActions(
|
||||
private val state: MutableStateFlow<ChatState>,
|
||||
private val read: suspend () -> ChatDetail?,
|
||||
private val follow: (Followed) -> Unit,
|
||||
private val say: (Throwable) -> Unit,
|
||||
private val catchUp: suspend () -> Unit,
|
||||
) {
|
||||
suspend fun sendNow(message: Message, send: suspend () -> Turn) = act(message) {
|
||||
val turn = send()
|
||||
state.update { it.sentNow(turn) }
|
||||
followedAfterSend(turn.reply?.id, read())?.let(follow)
|
||||
}
|
||||
|
||||
suspend fun discard(message: Message, withdraw: suspend () -> Unit) = act(message) {
|
||||
withdraw()
|
||||
state.update { it.discarded(message.id) }
|
||||
}
|
||||
|
||||
/** One action at a time: a second tap while the first is asked is not a second request. */
|
||||
private suspend fun act(message: Message, action: suspend () -> Unit) {
|
||||
if (state.value.acting != null) return
|
||||
state.update { it.copy(acting = message.id) }
|
||||
var stale = false
|
||||
try {
|
||||
action()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
say(e)
|
||||
stale = staleWaiting(e)
|
||||
} finally {
|
||||
state.update { if (it.acting == message.id) it.copy(acting = null) else it }
|
||||
}
|
||||
// After the buttons are free again: the read may wait for a reply being written here.
|
||||
if (stale) catchUp()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,538 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.files
|
||||
|
||||
import android.text.format.Formatter
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
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.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.CreateNewFolder
|
||||
import androidx.compose.material.icons.filled.DeleteForever
|
||||
import androidx.compose.material.icons.filled.DeleteSweep
|
||||
import androidx.compose.material.icons.filled.Download
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.FolderShared
|
||||
import androidx.compose.material.icons.filled.RestoreFromTrash
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.ListItem
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileEntry
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.FileVersion
|
||||
import eu.llembas.android.api.TrashItem
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.scheduled.ScheduleLogic
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
// The file manager's smaller pages: a name, a yes or no, the folder to move or copy into, the
|
||||
// trash, and a file's versions. Each is drawn from its state alone.
|
||||
|
||||
/** Ask for a name: a new folder's, a new file's, or a new one for something that has one. */
|
||||
@Composable
|
||||
fun NameDialog(title: String, ask: String?, initial: String, confirm: String, onName: (String) -> Unit, onDismiss: () -> Unit) {
|
||||
var name by remember { mutableStateOf(initial) }
|
||||
val bad = FileKinds.badName(name)
|
||||
val problem: (@Composable () -> Unit)? = if (name.isNotEmpty() && bad) {
|
||||
{ Text(stringResource(R.string.files_bad_name)) }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(title) },
|
||||
text = {
|
||||
Column {
|
||||
ask?.let { Text(it, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(bottom = 12.dp)) }
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { name = it },
|
||||
singleLine = true,
|
||||
isError = name.isNotEmpty() && bad,
|
||||
supportingText = problem,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { onName(name.trim()) }, enabled = !bad && name.trim() != initial) { Text(confirm) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
/** A question with one thing to do and a way not to. */
|
||||
@Composable
|
||||
fun ConfirmDialog(text: String, confirm: String, onConfirm: () -> Unit, onDismiss: () -> Unit) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
text = { Text(text, style = MaterialTheme.typography.bodyLarge) },
|
||||
confirmButton = { TextButton(onClick = onConfirm) { Text(confirm) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
/** Where the folder picker is: the folders of [path], on their way or refused. */
|
||||
data class FolderPickState(
|
||||
val path: String = "/",
|
||||
val parent: String? = null,
|
||||
val folders: List<FileEntry> = emptyList(),
|
||||
val loading: Boolean = true,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* Choosing a folder of the tree by walking to it: where something is moved or copied, or where
|
||||
* a share is saved. No path is typed. [hidden]: the things being moved, which cannot be their
|
||||
* own destination.
|
||||
*/
|
||||
@Composable
|
||||
fun FolderPicker(title: String, confirm: String, start: String, onPick: (String) -> Unit, onDismiss: () -> Unit, hidden: Set<String> = emptySet()) {
|
||||
val context = LocalContext.current
|
||||
var state by remember { mutableStateOf(FolderPickState(path = start)) }
|
||||
var asked by remember { mutableStateOf(start) }
|
||||
var again by remember { mutableIntStateOf(0) }
|
||||
var naming by remember { mutableStateOf(false) }
|
||||
var said by remember { mutableStateOf<String?>(null) }
|
||||
val scope = rememberCoroutineScope()
|
||||
LaunchedEffect(asked, again) {
|
||||
state = state.copy(loading = true, error = null)
|
||||
state = try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
val listing = api.files(asked)
|
||||
FolderPickState(listing.path, listing.parent, listing.entries.filter { it.isFolder && it.path !in hidden }, loading = false)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
state.copy(loading = false, error = context.filesSay(e))
|
||||
}
|
||||
}
|
||||
val up: () -> Unit = {
|
||||
val parent = state.parent
|
||||
if (parent != null) asked = parent else onDismiss()
|
||||
}
|
||||
Dialog(onDismissRequest = up, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
FolderPickContent(
|
||||
title,
|
||||
confirm,
|
||||
state,
|
||||
onOpen = { asked = it },
|
||||
onUp = up,
|
||||
onPick = { onPick(state.path) },
|
||||
onDismiss = onDismiss,
|
||||
onNewFolder = { naming = true },
|
||||
)
|
||||
}
|
||||
if (naming) {
|
||||
NameDialog(
|
||||
stringResource(R.string.folder_new),
|
||||
stringResource(R.string.files_new_folder_ask),
|
||||
"",
|
||||
stringResource(R.string.save),
|
||||
onName = { name ->
|
||||
naming = false
|
||||
val dir = state.path
|
||||
scope.launch {
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
api.makeFolder(dir, name)
|
||||
// Made, and walked into: it is most likely where the thing is meant to go.
|
||||
if (asked == FileKinds.child(dir, name)) again++ else asked = FileKinds.child(dir, name)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
said = context.filesSay(e)
|
||||
}
|
||||
}
|
||||
},
|
||||
onDismiss = { naming = false },
|
||||
)
|
||||
}
|
||||
said?.let { SaidDialog(it, onClose = { said = null }) }
|
||||
}
|
||||
|
||||
/** The folder picker's page: where it is, that folder's folders, and the one button that chooses the folder shown. */
|
||||
@Composable
|
||||
fun FolderPickContent(
|
||||
title: String,
|
||||
confirm: String,
|
||||
state: FolderPickState,
|
||||
onOpen: (String) -> Unit = {},
|
||||
onUp: () -> Unit = {},
|
||||
onPick: () -> Unit = {},
|
||||
onDismiss: () -> Unit = {},
|
||||
/** Make a folder in the one shown; null where the page cannot. */
|
||||
onNewFolder: (() -> Unit)? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
actions = {
|
||||
if (onNewFolder != null) {
|
||||
IconButton(onClick = onNewFolder, enabled = !state.loading && state.error == null) {
|
||||
Icon(Icons.Filled.CreateNewFolder, contentDescription = stringResource(R.string.folder_new))
|
||||
}
|
||||
}
|
||||
},
|
||||
navigationIcon = {
|
||||
IconButton(onClick = if (state.parent != null) onUp else onDismiss) {
|
||||
Icon(
|
||||
if (state.parent != null) Icons.AutoMirrored.Filled.ArrowBack else Icons.Filled.Close,
|
||||
contentDescription = stringResource(if (state.parent != null) R.string.back else R.string.close),
|
||||
)
|
||||
}
|
||||
},
|
||||
title = {
|
||||
Column {
|
||||
Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
state.path,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.StartEllipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
Button(
|
||||
onClick = onPick,
|
||||
enabled = !state.loading && state.error == null,
|
||||
colors = ButtonDefaults.buttonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.fillMaxWidth().padding(16.dp).heightIn(min = 48.dp),
|
||||
) { Text(confirm) }
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
when {
|
||||
state.error != null -> Text(state.error, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
|
||||
|
||||
state.loading && state.folders.isEmpty() -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||
|
||||
state.folders.isEmpty() -> Text(
|
||||
stringResource(R.string.files_no_folders),
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.align(Alignment.Center).padding(32.dp),
|
||||
)
|
||||
|
||||
else -> LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.folders, key = { it.path }) { folder ->
|
||||
ListItem(
|
||||
modifier = Modifier.fillMaxWidth().clickable { onOpen(folder.path) },
|
||||
leadingContent = {
|
||||
Icon(
|
||||
if (folder.kind == "mount") Icons.Filled.FolderShared else Icons.Filled.Folder,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
headlineContent = { Text(folder.name.ifBlank { folder.path }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The trash as the page draws it. */
|
||||
data class TrashState(val items: List<TrashItem> = emptyList(), val loading: Boolean = true, val error: String? = null)
|
||||
|
||||
/** What the trash page can do; nothing by default, for the screenshot tests. */
|
||||
interface TrashActions {
|
||||
fun restore(item: TrashItem) {}
|
||||
|
||||
fun remove(item: TrashItem) {}
|
||||
|
||||
fun empty() {}
|
||||
|
||||
fun close() {}
|
||||
}
|
||||
|
||||
/** The trash: what was deleted, each to be restored or removed for good, and all of it emptied. [onChanged]: something went back to the tree. */
|
||||
@Composable
|
||||
fun TrashDialog(onClose: () -> Unit, onChanged: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var state by remember { mutableStateOf(TrashState()) }
|
||||
var asking by remember { mutableStateOf<TrashItem?>(null) }
|
||||
var emptying by remember { mutableStateOf(false) }
|
||||
var said by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
fun act(block: suspend (ApiClient) -> List<TrashItem>) {
|
||||
scope.launch {
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
state = TrashState(block(api), loading = false)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
val words = context.filesSay(e)
|
||||
if (state.loading) state = state.copy(loading = false, error = words) else said = words
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) { act { it.trash().items } }
|
||||
val actions = remember {
|
||||
object : TrashActions {
|
||||
override fun restore(item: TrashItem) = act { api ->
|
||||
api.restoreTrashed(item.id).items.also { onChanged() }
|
||||
}
|
||||
|
||||
override fun remove(item: TrashItem) {
|
||||
asking = item
|
||||
}
|
||||
|
||||
override fun empty() {
|
||||
emptying = true
|
||||
}
|
||||
|
||||
override fun close() = onClose()
|
||||
}
|
||||
}
|
||||
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
TrashContent(state, actions)
|
||||
}
|
||||
asking?.let { item ->
|
||||
ConfirmDialog(
|
||||
stringResource(R.string.trash_remove_confirm, item.name),
|
||||
stringResource(R.string.trash_remove),
|
||||
onConfirm = {
|
||||
asking = null
|
||||
act { it.removeTrashed(item.id).items }
|
||||
},
|
||||
onDismiss = { asking = null },
|
||||
)
|
||||
}
|
||||
if (emptying) {
|
||||
ConfirmDialog(
|
||||
stringResource(R.string.trash_empty_confirm),
|
||||
stringResource(R.string.trash_empty),
|
||||
onConfirm = {
|
||||
emptying = false
|
||||
act { it.removeTrashed().items }
|
||||
},
|
||||
onDismiss = { emptying = false },
|
||||
)
|
||||
}
|
||||
said?.let { SaidDialog(it, onClose = { said = null }) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The trash's page. A row is the thing's name over where it was, and two buttons of 48 dp at
|
||||
* its end: the name gives, the buttons keep their size.
|
||||
*/
|
||||
@Composable
|
||||
fun TrashContent(state: TrashState, actions: TrashActions) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = actions::close) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = { Text(stringResource(R.string.trash), maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
actions = {
|
||||
IconButton(onClick = actions::empty, enabled = state.items.isNotEmpty()) {
|
||||
Icon(Icons.Filled.DeleteSweep, contentDescription = stringResource(R.string.trash_empty))
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
when {
|
||||
state.error != null -> Text(state.error, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
|
||||
|
||||
state.loading -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||
|
||||
state.items.isEmpty() -> Text(
|
||||
stringResource(R.string.trash_is_empty),
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.align(Alignment.Center).padding(32.dp),
|
||||
)
|
||||
|
||||
else -> LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.items, key = { it.id }) { item ->
|
||||
ListItem(
|
||||
leadingContent = { EntryIcon(if (item.kind == "file") null else item.kind, null, selected = false) },
|
||||
headlineContent = { Text(item.name.ifBlank { item.path }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
supportingContent = {
|
||||
val size = if (item.kind == "file") Formatter.formatShortFileSize(context, item.size) else null
|
||||
Text(listOfNotNull(FileKinds.parent(item.path), size).joinToString(" · "), maxLines = 1, overflow = TextOverflow.StartEllipsis)
|
||||
},
|
||||
trailingContent = {
|
||||
Row {
|
||||
IconButton(onClick = { actions.restore(item) }) {
|
||||
Icon(Icons.Filled.RestoreFromTrash, contentDescription = stringResource(R.string.restore))
|
||||
}
|
||||
IconButton(onClick = { actions.remove(item) }) {
|
||||
Icon(Icons.Filled.DeleteForever, contentDescription = stringResource(R.string.trash_remove), tint = palette.danger)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A file's versions as the page draws them. */
|
||||
data class VersionsState(val versions: List<FileVersion> = emptyList(), val loading: Boolean = true, val error: String? = null)
|
||||
|
||||
/** A file's versions, newest first; an older one can be made the file again, which adds a version and loses none. */
|
||||
@Composable
|
||||
fun VersionsDialog(path: String, onClose: () -> Unit, onRestored: () -> Unit, onDownload: ((FileVersion) -> Unit)? = null) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var state by remember(path) { mutableStateOf(VersionsState()) }
|
||||
var asking by remember { mutableStateOf<FileVersion?>(null) }
|
||||
LaunchedEffect(path) {
|
||||
state = try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
VersionsState(api.fileVersions(path).versions, loading = false)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
VersionsState(loading = false, error = context.filesSay(e))
|
||||
}
|
||||
}
|
||||
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
VersionsContent(FileKinds.name(path), state, onRestore = { asking = it }, onClose = onClose, onDownload = onDownload)
|
||||
}
|
||||
asking?.let { version ->
|
||||
ConfirmDialog(
|
||||
stringResource(R.string.version_restore_confirm),
|
||||
stringResource(R.string.version_restore),
|
||||
onConfirm = {
|
||||
asking = null
|
||||
scope.launch {
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
api.restoreVersion(path, version.id)
|
||||
onRestored()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
state = state.copy(error = context.filesSay(e))
|
||||
}
|
||||
}
|
||||
},
|
||||
onDismiss = { asking = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The versions' page: when, by whom and how large; the one the file holds now says so, the others
|
||||
* can be restored, and any of them saved to the phone as it was ([onDownload]; a 48 dp button
|
||||
* before the row's last part, so the buttons stand in one column whatever that part says).
|
||||
*/
|
||||
@Composable
|
||||
fun VersionsContent(
|
||||
name: String,
|
||||
state: VersionsState,
|
||||
onRestore: (FileVersion) -> Unit = {},
|
||||
onClose: () -> Unit = {},
|
||||
onDownload: ((FileVersion) -> Unit)? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = onClose) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = {
|
||||
Column {
|
||||
Text(stringResource(R.string.versions), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(name, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.padding(padding).fillMaxSize()) {
|
||||
state.error?.let { Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp)) }
|
||||
if (state.loading) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
|
||||
return@Column
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.versions, key = { it.id }) { version ->
|
||||
val download: (@Composable () -> Unit)? = if (onDownload != null) {
|
||||
{
|
||||
IconButton(onClick = { onDownload(version) }) {
|
||||
Icon(Icons.Filled.Download, contentDescription = stringResource(R.string.download))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
ListItem(
|
||||
headlineContent = { Text(ScheduleLogic.moment(version.at) ?: version.id, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
supportingContent = {
|
||||
val facts = listOfNotNull(version.by?.ifBlank { null }, Formatter.formatShortFileSize(context, version.size))
|
||||
Text(facts.joinToString(" · "), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
},
|
||||
leadingContent = download,
|
||||
trailingContent = {
|
||||
if (version.current) {
|
||||
Text(stringResource(R.string.version_current), style = MaterialTheme.typography.labelLarge, color = palette.inkMuted)
|
||||
} else {
|
||||
TextButton(onClick = { onRestore(version) }) { Text(stringResource(R.string.restore)) }
|
||||
}
|
||||
},
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,59 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class, androidx.compose.foundation.ExperimentalFoundationApi::class)
|
||||
|
||||
package eu.llembas.android.ui.files
|
||||
|
||||
import android.app.Application
|
||||
import android.net.Uri
|
||||
import android.text.format.Formatter
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
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.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
|
||||
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.Code
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Download
|
||||
import androidx.compose.material.icons.filled.DriveFileMove
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.FolderShared
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
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.RestoreFromTrash
|
||||
import androidx.compose.material.icons.filled.SelectAll
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material.icons.filled.TableChart
|
||||
import androidx.compose.material3.BottomAppBar
|
||||
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
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.ListItem
|
||||
import androidx.compose.material3.ListItemDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
@@ -31,10 +63,12 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
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.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
@@ -45,34 +79,136 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.BatchAnswer
|
||||
import eu.llembas.android.api.FileEntry
|
||||
import eu.llembas.android.api.FileExists
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.FileListing
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.viewer.TreeFileViewer
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** One directory of the person's tree, and whether it is on its way. */
|
||||
/**
|
||||
* One directory of the person's tree: what is in it, what is chosen in it, and what is under
|
||||
* way. [error] is a listing that could not be read (said above the list, which stays); [said] a
|
||||
* refusal of something the person did (a sentence to read, in a dialog); [notice] a word that
|
||||
* it was done.
|
||||
*/
|
||||
data class FilesState(
|
||||
val path: String = "/",
|
||||
val parent: String? = null,
|
||||
val entries: List<FileEntry> = emptyList(),
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
)
|
||||
val selected: Set<String> = emptySet(),
|
||||
/** An upload under way: which file of how many, and how far it is. */
|
||||
val upload: Transfer? = null,
|
||||
/** A write under way (a move, a rename…): the list waits for it. */
|
||||
val working: Boolean = false,
|
||||
val said: String? = null,
|
||||
val notice: String? = null,
|
||||
) {
|
||||
val selecting: Boolean get() = selected.isNotEmpty()
|
||||
|
||||
/** The chosen entries, in the list's order. */
|
||||
val chosen: List<FileEntry> get() = entries.filter { it.path in selected }
|
||||
|
||||
fun toggled(path: String): FilesState = copy(selected = if (path in selected) selected - path else selected + path)
|
||||
|
||||
fun allSelected(): FilesState = copy(selected = entries.map { it.path }.toSet())
|
||||
|
||||
/** A listing read: the directory it is of, and of what was chosen only what is still there. */
|
||||
fun listed(listing: FileListing): FilesState {
|
||||
val same = listing.path == path
|
||||
val there = listing.entries.map { it.path }.toSet()
|
||||
return copy(
|
||||
path = listing.path,
|
||||
parent = listing.parent,
|
||||
entries = listing.entries,
|
||||
loading = false,
|
||||
error = null,
|
||||
selected = if (same) selected intersect there else emptySet(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** What a batch ended in: the server's sentences for what it refused, and the word for what it did. */
|
||||
data class BatchOutcome(val said: String?, val done: Int)
|
||||
|
||||
fun outcome(answer: BatchAnswer): BatchOutcome {
|
||||
if (answer.failed == 0) return BatchOutcome(null, answer.done)
|
||||
// Where the server gave no sentence, at least which ones: their names.
|
||||
val names = answer.results.filter { !it.ok }.take(3).joinToString(", ") { FileKinds.name(it.path) }
|
||||
return BatchOutcome(answer.refusals().joinToString("\n").ifBlank { names }, answer.done)
|
||||
}
|
||||
|
||||
/** Something the Files page asks the person before it is done, or a page it opens over itself. */
|
||||
sealed interface Ask {
|
||||
data object NewFolder : Ask
|
||||
|
||||
data object NewFile : Ask
|
||||
|
||||
data object Trash : Ask
|
||||
|
||||
data class Rename(val entry: FileEntry) : Ask
|
||||
|
||||
data class Delete(val entries: List<FileEntry>) : Ask
|
||||
|
||||
data class Move(val entries: List<FileEntry>) : Ask
|
||||
|
||||
data class Copy(val entries: List<FileEntry>) : Ask
|
||||
|
||||
data class Versions(val entry: FileEntry) : Ask
|
||||
}
|
||||
|
||||
/** What the Files page can do; nothing by default, for the screenshot tests. */
|
||||
interface FilesActions {
|
||||
fun back() {}
|
||||
|
||||
fun open(entry: FileEntry) {}
|
||||
|
||||
fun reload() {}
|
||||
|
||||
fun toggle(entry: FileEntry) {}
|
||||
|
||||
fun selectAll() {}
|
||||
|
||||
fun clearSelection() {}
|
||||
|
||||
fun pickUpload() {}
|
||||
|
||||
fun ask(what: Ask) {}
|
||||
|
||||
fun download(entries: List<FileEntry>) {}
|
||||
|
||||
fun share(entries: List<FileEntry>) {}
|
||||
|
||||
fun openWith(entry: FileEntry) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* The person's files, read-only: `GET /api/v2/files` as the explorer's listing. The tree is read
|
||||
* as the person, with no chat -- their own access, the same the web UI's explorer draws by.
|
||||
* The person's files as a file manager: `GET /api/v2/files` and the explorer's writes. The tree
|
||||
* is read and changed as the person, with no chat -- their own access, the same the web UI's
|
||||
* explorer draws by -- and every refusal is the server's own sentence.
|
||||
*/
|
||||
class FilesViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(FilesState(loading = true))
|
||||
val state = _state.asStateFlow()
|
||||
private var loading: Job? = null
|
||||
private var uploading: Job? = null
|
||||
private val app: Application get() = getApplication()
|
||||
|
||||
private suspend fun api(): ApiClient = app.lembas.instances.client() ?: throw ApiException(401, app.getString(R.string.assist_signed_out))
|
||||
|
||||
/**
|
||||
* Opens a directory. A refusal (a path no longer readable, the server unreachable) keeps the
|
||||
@@ -83,16 +219,14 @@ class FilesViewModel(app: Application) : AndroidViewModel(app) {
|
||||
loading = viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val api = getApplication<Application>().lembas.instances.client()
|
||||
if (api == null) {
|
||||
_state.update { it.copy(loading = false) }
|
||||
return@launch
|
||||
}
|
||||
val listing = api.files(path)
|
||||
_state.value = FilesState(path = listing.path, parent = listing.parent, entries = listing.entries)
|
||||
// Also read again after an upload that ended behind the lock: not before the app is in front.
|
||||
app.lembas.gate.pass()
|
||||
val listing = api().files(path)
|
||||
_state.update { it.listed(listing) }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
if (e is kotlinx.coroutines.CancellationException) throw e
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
_state.update { it.copy(loading = false, error = app.explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,85 +238,464 @@ class FilesViewModel(app: Application) : AndroidViewModel(app) {
|
||||
open(parent)
|
||||
return true
|
||||
}
|
||||
|
||||
fun toggle(entry: FileEntry) = _state.update { it.toggled(entry.path) }
|
||||
|
||||
fun selectAll() = _state.update { it.allSelected() }
|
||||
|
||||
fun clearSelection() = _state.update { it.copy(selected = emptySet()) }
|
||||
|
||||
fun clearSaid() = _state.update { it.copy(said = null, notice = null) }
|
||||
|
||||
/** One write, then the directory read again: what is there is what the server says is there. */
|
||||
private fun write(block: suspend (ApiClient) -> String?) {
|
||||
if (_state.value.working) return
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(working = true, said = null, notice = null) }
|
||||
try {
|
||||
val notice = block(api())
|
||||
_state.update { it.copy(notice = notice) }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(said = app.filesSay(e)) }
|
||||
} finally {
|
||||
_state.update { it.copy(working = false) }
|
||||
}
|
||||
reload()
|
||||
}
|
||||
}
|
||||
|
||||
fun newFolder(name: String) = write { api ->
|
||||
api.makeFolder(_state.value.path, name)
|
||||
null
|
||||
}
|
||||
|
||||
/**
|
||||
* A new, empty text file, and [then] its path, to open it for writing. The instance makes it
|
||||
* only where nothing is called that (`create`): otherwise nothing is written and its own
|
||||
* sentence says what is there. An instance from before `create` would write over what is
|
||||
* there, so the directory is read first and a name it holds is refused here
|
||||
* ([ApiClient.newFile]).
|
||||
*/
|
||||
fun newFile(name: String, then: (String) -> Unit) = write { api ->
|
||||
try {
|
||||
then(api.newFile(_state.value.path, name))
|
||||
} catch (e: FileExists) {
|
||||
_state.update { it.copy(said = e.message?.ifBlank { null } ?: app.getString(R.string.files_taken, name)) }
|
||||
}
|
||||
null
|
||||
}
|
||||
|
||||
fun rename(entry: FileEntry, name: String) = write { api ->
|
||||
api.renameFile(entry.path, name)
|
||||
null
|
||||
}
|
||||
|
||||
/** Move or copy the entries into the directory [to], or with `delete` put them in the trash; each is answered for by itself. */
|
||||
fun batch(op: String, entries: List<FileEntry>, to: String? = null) = write { api ->
|
||||
val done = outcome(api.batchFiles(op, entries.map { it.path }, to))
|
||||
_state.update { it.copy(selected = emptySet(), said = done.said) }
|
||||
when {
|
||||
done.done == 0 -> null
|
||||
op == "delete" -> app.getString(R.string.files_trashed)
|
||||
op == "copy" -> app.getString(R.string.copied)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload files of the phone into the directory shown, one request each: a file the instance
|
||||
* refuses (too large: its 413 names the file) does not take the others with it. Each is
|
||||
* streamed from where it is; none is read into memory.
|
||||
*/
|
||||
fun upload(uris: List<Uri>) {
|
||||
if (uris.isEmpty() || uploading?.isActive == true) return
|
||||
val dir = _state.value.path
|
||||
uploading = viewModelScope.launch {
|
||||
val refused = mutableListOf<String>()
|
||||
var sent = 0
|
||||
try {
|
||||
val api = api()
|
||||
val files = uris.map { app.contentResolver.describe(it) }
|
||||
files.forEachIndexed { i, file ->
|
||||
val words = app.getString(R.string.files_uploading, (i + 1).toString(), files.size.toString())
|
||||
_state.update { it.copy(upload = Transfer(words, 0, file.size)) }
|
||||
var last = 0L
|
||||
try {
|
||||
// The file under way when the phone locks goes through; the next waits for the app in front, unlocked.
|
||||
app.lembas.gate.pass { waiting -> _state.update { it.copy(upload = it.upload?.copy(waiting = waiting)) } }
|
||||
api.uploadFrom(app, file, dir) { bytes ->
|
||||
if (bytes - last >= 256 * 1024) {
|
||||
last = bytes
|
||||
_state.update { it.copy(upload = it.upload?.copy(done = bytes)) }
|
||||
}
|
||||
}
|
||||
sent++
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
refused += app.filesSay(e)
|
||||
}
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
refused += app.filesSay(e)
|
||||
} finally {
|
||||
val words = refused.distinct().take(3).joinToString("\n").ifBlank { null }
|
||||
_state.update { it.copy(upload = null, said = words, notice = if (sent > 0) app.getString(R.string.files_uploaded) else null) }
|
||||
reload()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun cancelUpload() {
|
||||
uploading?.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun FilesScreen(onBack: () -> Unit, model: FilesViewModel = viewModel()) {
|
||||
fun FilesScreen(onBack: () -> Unit, start: String? = null, model: FilesViewModel = viewModel(), transfers: TransferViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
var viewing by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
LaunchedEffect(Unit) { if (state.entries.isEmpty() && state.error == null) model.open(state.path) }
|
||||
var writing by rememberSaveable { mutableStateOf(false) }
|
||||
var asked by remember { mutableStateOf<Ask?>(null) }
|
||||
var saving by remember { mutableStateOf<List<FileEntry>>(emptyList()) }
|
||||
// Opened at a folder ([start]: where a generated file is) the first time; after that, where the person walked to.
|
||||
LaunchedEffect(Unit) { if (state.entries.isEmpty() && state.error == null) model.open(start?.ifBlank { null } ?: state.path) }
|
||||
val saveVersion = rememberSaver(transfers)
|
||||
LaunchedEffect(state.notice) {
|
||||
state.notice?.let {
|
||||
Toast.makeText(context, it, Toast.LENGTH_SHORT).show()
|
||||
model.clearSaid()
|
||||
}
|
||||
}
|
||||
|
||||
// Back goes up one directory first, as a file manager's does; at the top it leaves.
|
||||
BackHandler(enabled = state.parent != null) { model.up() }
|
||||
// Back lets go of what is chosen first, then goes up one directory, as a file manager's does; at the top it leaves.
|
||||
BackHandler(enabled = state.selecting || state.parent != null) { if (state.selecting) model.clearSelection() else model.up() }
|
||||
|
||||
val pick = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { model.upload(it) }
|
||||
val saveTo = rememberLauncherForActivityResult(CreateFile()) { to ->
|
||||
val what = saving
|
||||
saving = emptyList()
|
||||
if (to != null && what.isNotEmpty()) {
|
||||
transfers.download(what.map { it.path }, zip = asZip(what), to = to)
|
||||
model.clearSelection()
|
||||
}
|
||||
}
|
||||
val actions = remember(model, transfers) {
|
||||
object : FilesActions {
|
||||
override fun back() {
|
||||
if (!model.up()) onBack()
|
||||
}
|
||||
|
||||
override fun open(entry: FileEntry) {
|
||||
if (entry.isFolder) {
|
||||
model.open(entry.path)
|
||||
} else {
|
||||
writing = false
|
||||
viewing = entry.path
|
||||
}
|
||||
}
|
||||
|
||||
override fun reload() = model.reload()
|
||||
|
||||
override fun toggle(entry: FileEntry) = model.toggle(entry)
|
||||
|
||||
override fun selectAll() = model.selectAll()
|
||||
|
||||
override fun clearSelection() = model.clearSelection()
|
||||
|
||||
override fun pickUpload() = pick.launch(arrayOf("*/*"))
|
||||
|
||||
override fun ask(what: Ask) {
|
||||
asked = what
|
||||
}
|
||||
|
||||
override fun download(entries: List<FileEntry>) {
|
||||
if (entries.isEmpty()) return
|
||||
saving = entries
|
||||
val zip = asZip(entries)
|
||||
saveTo.launch(
|
||||
CreateFile.Ask(
|
||||
if (zip) {
|
||||
TransferViewModel.zipName(
|
||||
entries.map {
|
||||
it.path
|
||||
},
|
||||
)
|
||||
} else {
|
||||
entries[0].name
|
||||
},
|
||||
if (zip) "application/zip" else entries[0].mime,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
override fun share(entries: List<FileEntry>) {
|
||||
transfers.share(entries)
|
||||
model.clearSelection()
|
||||
}
|
||||
|
||||
override fun openWith(entry: FileEntry) = transfers.openWith(entry.path, entry.name, entry.mime)
|
||||
}
|
||||
}
|
||||
|
||||
FilesContent(state, actions)
|
||||
|
||||
when (val now = asked) {
|
||||
null -> Unit
|
||||
|
||||
Ask.NewFolder -> NameDialog(
|
||||
stringResource(R.string.folder_new),
|
||||
stringResource(R.string.files_new_folder_ask),
|
||||
"",
|
||||
stringResource(R.string.save),
|
||||
onName = {
|
||||
asked = null
|
||||
model.newFolder(it)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
Ask.NewFile -> NameDialog(
|
||||
stringResource(R.string.files_new_file),
|
||||
stringResource(R.string.files_new_file_ask),
|
||||
"",
|
||||
stringResource(R.string.save),
|
||||
onName = { name ->
|
||||
asked = null
|
||||
model.newFile(name) { path ->
|
||||
writing = true
|
||||
viewing = path
|
||||
}
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
is Ask.Rename -> NameDialog(
|
||||
stringResource(R.string.rename),
|
||||
stringResource(R.string.files_new_name),
|
||||
now.entry.name,
|
||||
stringResource(R.string.rename),
|
||||
onName = {
|
||||
asked = null
|
||||
model.rename(now.entry, it)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
is Ask.Delete -> ConfirmDialog(
|
||||
if (now.entries.size == 1) {
|
||||
stringResource(R.string.files_trash_one, now.entries[0].name)
|
||||
} else {
|
||||
stringResource(R.string.files_trash_many, now.entries.size.toString())
|
||||
},
|
||||
stringResource(R.string.files_to_trash),
|
||||
onConfirm = {
|
||||
asked = null
|
||||
model.batch("delete", now.entries)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
is Ask.Move -> FolderPicker(
|
||||
stringResource(R.string.files_move_which),
|
||||
stringResource(R.string.files_move_here),
|
||||
state.path,
|
||||
onPick = {
|
||||
asked = null
|
||||
model.batch("move", now.entries, it)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
hidden = now.entries.map { it.path }.toSet(),
|
||||
)
|
||||
|
||||
is Ask.Copy -> FolderPicker(
|
||||
stringResource(R.string.files_copy_which),
|
||||
stringResource(R.string.files_copy_here),
|
||||
state.path,
|
||||
onPick = {
|
||||
asked = null
|
||||
model.batch("copy", now.entries, it)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
is Ask.Versions -> VersionsDialog(
|
||||
now.entry.path,
|
||||
onDownload = { version -> saveVersion(Raw.Path(now.entry.path, version.id), now.entry.name, now.entry.mime) },
|
||||
onClose = { asked = null },
|
||||
onRestored = {
|
||||
asked = null
|
||||
model.reload()
|
||||
},
|
||||
)
|
||||
|
||||
Ask.Trash -> TrashDialog(onClose = { asked = null }, onChanged = model::reload)
|
||||
}
|
||||
|
||||
state.upload?.let { TransferDialog(it, onCancel = model::cancelUpload) }
|
||||
state.said?.let { SaidDialog(it, onClose = model::clearSaid) }
|
||||
TransferHost(transfers)
|
||||
viewing?.let { path -> TreeFileViewer(path, onClose = { viewing = null }, startEditing = writing, onChanged = model::reload) }
|
||||
}
|
||||
|
||||
/** Several things, or a folder, leave as one zip; a single file as itself. */
|
||||
fun asZip(entries: List<FileEntry>): Boolean = entries.size > 1 || entries.any { it.isFolder }
|
||||
|
||||
/**
|
||||
* The Files page, from [state] alone. A tap opens; a long press chooses, and while anything is
|
||||
* chosen a tap chooses too and the bar at the bottom acts on all of it. Each row's own menu
|
||||
* (the three dots, 48 dp) has what can be done to that one thing.
|
||||
*/
|
||||
@Composable
|
||||
fun FilesContent(state: FilesState, actions: FilesActions) {
|
||||
val palette = LocalPalette.current
|
||||
var adding by remember { mutableStateOf(false) }
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = { if (!model.up()) onBack() }) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
|
||||
if (state.selecting) {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = actions::clearSelection) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.cancel)) }
|
||||
},
|
||||
title = { Text(stringResource(R.string.files_selected, state.selected.size.toString()), maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
actions = {
|
||||
IconButton(onClick = actions::selectAll) {
|
||||
Icon(Icons.Filled.SelectAll, contentDescription = stringResource(R.string.files_select_all))
|
||||
}
|
||||
},
|
||||
)
|
||||
} else {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = actions::back) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) }
|
||||
},
|
||||
title = {
|
||||
Column {
|
||||
Text(stringResource(R.string.files), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
if (state.parent == null) stringResource(R.string.files_all) else state.path,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontFamily = if (state.parent == null) null else FontFamily.Monospace,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.StartEllipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
Box {
|
||||
IconButton(onClick = { adding = true }) { Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.files_upload)) }
|
||||
DropdownMenu(expanded = adding, onDismissRequest = { adding = false }) {
|
||||
MenuItem(R.string.files_upload) {
|
||||
adding = false
|
||||
actions.pickUpload()
|
||||
}
|
||||
MenuItem(R.string.folder_new) {
|
||||
adding = false
|
||||
actions.ask(Ask.NewFolder)
|
||||
}
|
||||
MenuItem(R.string.files_new_file) {
|
||||
adding = false
|
||||
actions.ask(Ask.NewFile)
|
||||
}
|
||||
}
|
||||
}
|
||||
IconButton(onClick = {
|
||||
actions.ask(Ask.Trash)
|
||||
}) { Icon(Icons.Filled.RestoreFromTrash, contentDescription = stringResource(R.string.trash)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
},
|
||||
bottomBar = {
|
||||
if (state.selecting) {
|
||||
val chosen = state.chosen
|
||||
// Five actions of one size, spread evenly: none of them is a word, so none can crowd another.
|
||||
BottomAppBar {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically) {
|
||||
BarButton(Icons.Filled.DriveFileMove, R.string.files_move) { actions.ask(Ask.Move(chosen)) }
|
||||
BarButton(Icons.Filled.ContentCopy, R.string.files_copy_to) { actions.ask(Ask.Copy(chosen)) }
|
||||
BarButton(Icons.Filled.Download, if (asZip(chosen)) R.string.files_download_zip else R.string.download) { actions.download(chosen) }
|
||||
BarButton(Icons.Filled.Share, R.string.report_share) { actions.share(chosen) }
|
||||
BarButton(Icons.Filled.Delete, R.string.files_to_trash) { actions.ask(Ask.Delete(chosen)) }
|
||||
}
|
||||
},
|
||||
title = {
|
||||
Column {
|
||||
Text(stringResource(R.string.files), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
if (state.parent == null) stringResource(R.string.files_all) else state.path,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontFamily = if (state.parent == null) null else FontFamily.Monospace,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.StartEllipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.padding(padding).fillMaxSize()) {
|
||||
state.error?.let {
|
||||
Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
|
||||
}
|
||||
PullToRefreshBox(isRefreshing = state.loading, onRefresh = { model.reload() }, modifier = Modifier.fillMaxSize()) {
|
||||
if (state.working) LinearProgressIndicator(Modifier.fillMaxWidth().height(2.dp))
|
||||
state.error?.let { Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp)) }
|
||||
PullToRefreshBox(isRefreshing = state.loading, onRefresh = actions::reload, modifier = Modifier.fillMaxSize()) {
|
||||
if (state.entries.isEmpty() && !state.loading && state.error == null) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
stringResource(R.string.files_empty),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(32.dp),
|
||||
)
|
||||
Text(stringResource(R.string.files_empty), color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(32.dp))
|
||||
}
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.entries, key = { it.path }) { entry ->
|
||||
EntryRow(entry) { if (entry.isFolder) model.open(entry.path) else viewing = entry.path }
|
||||
EntryRow(entry, selected = entry.path in state.selected, selecting = state.selecting, actions = actions)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
viewing?.let { path -> TreeFileViewer(path, onClose = { viewing = null }) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EntryRow(entry: FileEntry, onOpen: () -> Unit) {
|
||||
private fun MenuItem(label: Int, onClick: () -> Unit) = DropdownMenuItem(text = { Text(stringResource(label)) }, onClick = onClick)
|
||||
|
||||
@Composable
|
||||
private fun BarButton(icon: ImageVector, label: Int, onClick: () -> Unit) {
|
||||
IconButton(onClick = onClick) { Icon(icon, contentDescription = stringResource(label)) }
|
||||
}
|
||||
|
||||
/** What an entry is, as a picture: a folder, a shared folder, or the file's kind; a tick when it is chosen. */
|
||||
@Composable
|
||||
internal fun EntryIcon(folder: String?, fileKind: String?, selected: Boolean) {
|
||||
val palette = LocalPalette.current
|
||||
val icon = when {
|
||||
selected -> Icons.Filled.CheckCircle
|
||||
|
||||
folder == "mount" -> Icons.Filled.FolderShared
|
||||
|
||||
folder != null -> Icons.Filled.Folder
|
||||
|
||||
else -> when (fileKind) {
|
||||
"image", "svg" -> Icons.Filled.Image
|
||||
"pdf" -> Icons.Filled.PictureAsPdf
|
||||
"audio" -> Icons.Filled.MusicNote
|
||||
"video" -> Icons.Filled.Movie
|
||||
"table" -> Icons.Filled.TableChart
|
||||
"code", "html", "notebook" -> Icons.Filled.Code
|
||||
"archive" -> Icons.Filled.Archive
|
||||
"model3d", "binary" -> Icons.AutoMirrored.Filled.InsertDriveFile
|
||||
else -> Icons.Filled.Description
|
||||
}
|
||||
}
|
||||
Icon(icon, contentDescription = null, tint = if (selected) palette.accent else MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EntryRow(entry: FileEntry, selected: Boolean, selecting: Boolean, actions: FilesActions) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
ListItem(
|
||||
modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen),
|
||||
leadingContent = {
|
||||
Icon(
|
||||
when (entry.kind) {
|
||||
"mount" -> Icons.Filled.FolderShared
|
||||
"dir" -> Icons.Filled.Folder
|
||||
else -> Icons.Filled.Description
|
||||
},
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.combinedClickable(
|
||||
onClick = { if (selecting) actions.toggle(entry) else actions.open(entry) },
|
||||
onLongClick = { actions.toggle(entry) },
|
||||
),
|
||||
colors = ListItemDefaults.colors(containerColor = if (selected) palette.accentSoft else palette.bg),
|
||||
leadingContent = { EntryIcon(if (entry.isFolder) entry.kind else null, entry.fileKind, selected) },
|
||||
headlineContent = { Text(entry.name.ifBlank { entry.path }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
supportingContent = if (entry.isFolder) {
|
||||
null
|
||||
@@ -192,5 +705,33 @@ private fun EntryRow(entry: FileEntry, onOpen: () -> Unit) {
|
||||
Text(line, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
},
|
||||
trailingContent = if (selecting) {
|
||||
null
|
||||
} else {
|
||||
{
|
||||
Box {
|
||||
IconButton(onClick = { menu = true }) { Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.more)) }
|
||||
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
|
||||
val one = listOf(entry)
|
||||
val then: (() -> Unit) -> (() -> Unit) = { act ->
|
||||
{
|
||||
menu = false
|
||||
act()
|
||||
}
|
||||
}
|
||||
MenuItem(R.string.rename, then { actions.ask(Ask.Rename(entry)) })
|
||||
MenuItem(R.string.files_move, then { actions.ask(Ask.Move(one)) })
|
||||
MenuItem(R.string.files_copy_to, then { actions.ask(Ask.Copy(one)) })
|
||||
MenuItem(if (entry.isFolder) R.string.files_download_zip else R.string.download, then { actions.download(one) })
|
||||
MenuItem(R.string.report_share, then { actions.share(one) })
|
||||
if (!entry.isFolder) {
|
||||
MenuItem(R.string.files_open_with, then { actions.openWith(entry) })
|
||||
MenuItem(R.string.versions, then { actions.ask(Ask.Versions(entry)) })
|
||||
}
|
||||
MenuItem(R.string.files_to_trash, then { actions.ask(Ask.Delete(one)) })
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
package eu.llembas.android.ui.files
|
||||
|
||||
import android.app.Application
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.text.format.Formatter
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileEntry
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.share.SharedRefused
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* Something on its way to or from the instance: what it is, and how far ([total] -1: not known).
|
||||
* [waiting]: its next request has not started, because the app is not in front or the phone is
|
||||
* locked ([eu.llembas.android.InstanceGate]); it goes on by itself.
|
||||
*/
|
||||
data class Transfer(val text: String, val done: Long = 0, val total: Long = -1, val waiting: Boolean = false)
|
||||
|
||||
/** A transfer under way, what it ended in, and the other app to open once a copy is ready. */
|
||||
data class TransferState(val running: Transfer? = null, val error: String? = null, val notice: String? = null, val launch: Intent? = null)
|
||||
|
||||
/** A failure of the file manager in words: an instance without these routes says so, the rest as everywhere. */
|
||||
fun Context.filesSay(e: Throwable): String = when {
|
||||
noSuchRoute(e) -> getString(R.string.viewer_unavailable)
|
||||
e is SharedRefused -> getString(R.string.share_refused)
|
||||
e is ApiException && e.message.isNullOrBlank() -> getString(R.string.files_not_shown)
|
||||
else -> explain(e)
|
||||
}
|
||||
|
||||
/**
|
||||
* Files leaving the instance for the phone: a download into a document the person chose, and a
|
||||
* copy in the private cache for another app (Open with, Share). One at a time, with its
|
||||
* progress, and it can be given up. It outlives a turn of the phone. Each request asks the gate
|
||||
* first ([turn]): none starts while the phone is locked or the app is not in front, and the one
|
||||
* under way then is let finish.
|
||||
*/
|
||||
class TransferViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(TransferState())
|
||||
val state = _state.asStateFlow()
|
||||
private var job: Job? = null
|
||||
private val app: Application get() = getApplication()
|
||||
|
||||
/** One file's bytes, or with [zip] several files and folders as one zip, into the document [to]. */
|
||||
fun download(paths: List<String>, zip: Boolean, to: Uri) = start { api, progress ->
|
||||
turn()
|
||||
api.downloadTo(app, if (zip) api.zipFiles(paths) else api.rawFile(paths.first()), to, progress)
|
||||
_state.update { it.copy(notice = app.getString(R.string.files_downloaded)) }
|
||||
}
|
||||
|
||||
/** One thing's bytes -- a version of a file, a generated file by its id, an attachment -- into the document [to]. */
|
||||
fun download(what: Raw, to: Uri) = start { api, progress ->
|
||||
turn()
|
||||
api.downloadTo(app, api.raw(what), to, progress)
|
||||
_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(what: Raw, name: String, mime: 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)) }
|
||||
}
|
||||
|
||||
/** One thing that is not named by a path (a generated file by its id), shared as itself. */
|
||||
fun share(what: Raw, name: String, mime: 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.share(app, listOf(copy), mime.ifBlank { "*/*" })) }
|
||||
}
|
||||
|
||||
/** A few files go as themselves; many, or any folder, as one zip the instance makes. */
|
||||
fun share(entries: List<FileEntry>) = start { api, progress ->
|
||||
if (entries.isEmpty()) return@start
|
||||
FileCache.sweepShared(app)
|
||||
val plain = entries.none { it.isFolder } && entries.size <= SHARE_MOST
|
||||
val copies = if (plain) {
|
||||
entries.map {
|
||||
turn()
|
||||
api.copyInto(api.rawFile(it.path), FileCache.shared(app, it.name), progress = progress)
|
||||
}
|
||||
} else {
|
||||
turn()
|
||||
listOf(api.copyInto(api.zipFiles(entries.map { it.path }), FileCache.shared(app, zipName(entries.map { it.path })), progress = progress))
|
||||
}
|
||||
val mime = if (plain) entries.map { it.mime }.distinct().singleOrNull()?.ifBlank { null } ?: "*/*" else "application/zip"
|
||||
_state.update { it.copy(launch = Handover.share(app, copies, mime)) }
|
||||
}
|
||||
|
||||
fun launched() = _state.update { it.copy(launch = null) }
|
||||
|
||||
fun say(error: String) = _state.update { it.copy(error = error) }
|
||||
|
||||
fun clear() = _state.update { it.copy(error = null, notice = null) }
|
||||
|
||||
fun cancel() {
|
||||
job?.cancel()
|
||||
}
|
||||
|
||||
/** The gate, before a request: while it is shut the dialog says the transfer is waiting. */
|
||||
private suspend fun turn() = app.lembas.gate.pass { waiting -> _state.update { it.copy(running = it.running?.copy(waiting = waiting)) } }
|
||||
|
||||
private fun start(block: suspend (ApiClient, (Long, Long) -> Unit) -> Unit) {
|
||||
if (job?.isActive == true) return
|
||||
job = viewModelScope.launch {
|
||||
_state.update { it.copy(running = Transfer(app.getString(R.string.files_downloading)), error = null, notice = null) }
|
||||
try {
|
||||
val api = app.lembas.instances.client() ?: throw ApiException(401, app.getString(R.string.assist_signed_out))
|
||||
block(api, stepped { done, total -> _state.update { it.copy(running = it.running?.copy(done = done, total = total)) } })
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = app.filesSay(e)) }
|
||||
} finally {
|
||||
_state.update { it.copy(running = null) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The copies another app was handed stay while it may be reading them: only the old ones go. */
|
||||
override fun onCleared() {
|
||||
FileCache.sweepShared(app)
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** More files than this are shared as one zip. */
|
||||
const val SHARE_MOST = 10
|
||||
|
||||
/** What a zip of [paths] is called: the one thing's name, else the folder they are in. */
|
||||
fun zipName(paths: List<String>): String {
|
||||
val one = paths.singleOrNull()?.let { FileKinds.name(it) }
|
||||
val folder = paths.firstOrNull()?.let { FileKinds.name(FileKinds.parent(it)) }?.takeIf { it != "/" }
|
||||
return (one ?: folder ?: "files").removeSuffix(".zip") + ".zip"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* "Save to" for one thing: the system's page for where it goes, and then the download into the
|
||||
* document chosen there. What is to be saved is kept while that page is open.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberSaver(transfers: TransferViewModel): (what: Raw, name: String, mime: String) -> Unit {
|
||||
var pending by remember { mutableStateOf<Raw?>(null) }
|
||||
val page = rememberLauncherForActivityResult(CreateFile()) { to ->
|
||||
val what = pending
|
||||
pending = null
|
||||
if (to != null && what != null) transfers.download(what, to)
|
||||
}
|
||||
return { what, name, mime ->
|
||||
pending = what
|
||||
page.launch(CreateFile.Ask(FileKinds.safeName(name), mime))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What a screen shows of its transfers: the one under way with Cancel, the other app once a
|
||||
* copy is ready, a failure in a dialog (it is a sentence to read), and a short word when one
|
||||
* is done -- which names no file.
|
||||
*/
|
||||
@Composable
|
||||
fun TransferHost(model: TransferViewModel) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
val context = LocalContext.current
|
||||
LaunchedEffect(state.launch) {
|
||||
val intent = state.launch ?: return@LaunchedEffect
|
||||
try {
|
||||
context.startActivity(intent)
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
model.say(context.getString(R.string.files_no_app))
|
||||
}
|
||||
model.launched()
|
||||
}
|
||||
LaunchedEffect(state.notice) {
|
||||
state.notice?.let {
|
||||
Toast.makeText(context, it, Toast.LENGTH_SHORT).show()
|
||||
model.clear()
|
||||
}
|
||||
}
|
||||
state.running?.let { TransferDialog(it, onCancel = model::cancel) }
|
||||
state.error?.let { SaidDialog(it, onClose = model::clear) }
|
||||
}
|
||||
|
||||
/** A transfer under way: what, how far, and Cancel. Drawn from [transfer] alone. */
|
||||
@Composable
|
||||
fun TransferDialog(transfer: Transfer, onCancel: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
AlertDialog(
|
||||
onDismissRequest = {},
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text(transfer.text, style = MaterialTheme.typography.bodyLarge)
|
||||
if (transfer.waiting) Text(stringResource(R.string.files_waiting), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
if (transfer.total > 0) {
|
||||
LinearProgressIndicator(progress = { (transfer.done.toFloat() / transfer.total).coerceIn(0f, 1f) }, modifier = Modifier.fillMaxWidth())
|
||||
} else {
|
||||
LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
}
|
||||
if (transfer.done > 0) {
|
||||
val done = Formatter.formatShortFileSize(context, transfer.done)
|
||||
val line = if (transfer.total > 0) done + " / " + Formatter.formatShortFileSize(context, transfer.total) else done
|
||||
Text(line, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onCancel) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
/** A sentence the person has to read (a refusal, a failure), with one way on. */
|
||||
@Composable
|
||||
fun SaidDialog(text: String, onClose: () -> Unit) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onClose,
|
||||
text = { Text(text, style = MaterialTheme.typography.bodyLarge) },
|
||||
confirmButton = { TextButton(onClick = onClose) { Text(stringResource(R.string.close)) } },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package eu.llembas.android.ui.files
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.ClipData
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.provider.DocumentsContract
|
||||
import android.provider.OpenableColumns
|
||||
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.share.SharedSource
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import okhttp3.MediaType
|
||||
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||
import okhttp3.RequestBody
|
||||
import okio.BufferedSink
|
||||
import okio.source
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* The copies of the account's files this phone holds for a moment, all in the app's private
|
||||
* cache and nowhere else: [viewing] for what a viewer needs as a file (a PDF's pages, a
|
||||
* picture's pixels), deleted when the viewer closes; [shared] for what another app is handed
|
||||
* through the FileProvider (Open with, Share). A shared copy cannot be deleted the moment it is
|
||||
* handed over, nor when the screen that made it closes or the app starts again: the other app
|
||||
* may still be reading it (a mail being written). So it goes by its age alone, [SHARED_KEPT_MS]
|
||||
* after it was written -- looked at when the app starts, when a screen with transfers closes and
|
||||
* before a new copy is made -- and all of them go at sign-out and on a switch of instance. No
|
||||
* storage permission is involved: what the person keeps, they save through the system's own
|
||||
* "Save to" page.
|
||||
*/
|
||||
object FileCache {
|
||||
private const val VIEWING = "viewing"
|
||||
private const val SHARED = "shared"
|
||||
|
||||
/** How long a copy another app was handed is kept: an hour. */
|
||||
const val SHARED_KEPT_MS = 60 * 60 * 1000L
|
||||
|
||||
private fun dir(context: Context, name: String): File = File(context.cacheDir, name).apply { mkdirs() }
|
||||
|
||||
/** A new, empty place for one viewer's copy. */
|
||||
fun viewing(context: Context, name: String): File = File(dir(context, VIEWING), UUID.randomUUID().toString() + "-" + FileKinds.safeName(name, 80))
|
||||
|
||||
/** A new place for a copy another app will read, under its own name in a folder of its own. */
|
||||
fun shared(context: Context, name: String): File =
|
||||
File(File(dir(context, SHARED), UUID.randomUUID().toString()).apply { mkdirs() }, FileKinds.safeName(name))
|
||||
|
||||
/** Every copy, gone: at sign-out and on a switch of instance. */
|
||||
fun clear(context: Context) {
|
||||
for (name in listOf(VIEWING, SHARED)) runCatching { File(context.cacheDir, name).deleteRecursively() }
|
||||
}
|
||||
|
||||
/** When the process starts: no viewer is open, so their copies go; the shared ones by their age. */
|
||||
fun atStart(context: Context) {
|
||||
runCatching { File(context.cacheDir, VIEWING).deleteRecursively() }
|
||||
sweepShared(context)
|
||||
}
|
||||
|
||||
/** The shared copies older than [olderThanMs], and no other. */
|
||||
fun sweepShared(context: Context, olderThanMs: Long = SHARED_KEPT_MS) = sweep(File(context.cacheDir, SHARED), System.currentTimeMillis(), olderThanMs)
|
||||
|
||||
/**
|
||||
* Deletes what is directly in [dir] and was last written more than [olderThanMs] before
|
||||
* [now]. A copy's folder is as old as the newest thing in it: a long download's folder was
|
||||
* made when it began.
|
||||
*/
|
||||
fun sweep(dir: File, now: Long, olderThanMs: Long) {
|
||||
dir.listFiles()?.forEach { entry ->
|
||||
val written = maxOf(entry.lastModified(), entry.listFiles()?.maxOfOrNull { it.lastModified() } ?: 0L)
|
||||
if (now - written > olderThanMs) runCatching { entry.deleteRecursively() }
|
||||
}
|
||||
}
|
||||
|
||||
/** The address another app is given for a [shared] copy: the app's FileProvider, read-only, for that one grant. */
|
||||
fun uri(context: Context, file: File): Uri = FileProvider.getUriForFile(context, context.packageName + ".files", file)
|
||||
}
|
||||
|
||||
/** "Save to": the system's page for where a file goes (the Storage Access Framework), by a suggested name and type. */
|
||||
class CreateFile : ActivityResultContract<CreateFile.Ask, Uri?>() {
|
||||
data class Ask(val name: String, val mime: String)
|
||||
|
||||
override fun createIntent(context: Context, input: Ask): Intent = Intent(Intent.ACTION_CREATE_DOCUMENT)
|
||||
.addCategory(Intent.CATEGORY_OPENABLE)
|
||||
.setType(input.mime.ifBlank { "application/octet-stream" })
|
||||
.putExtra(Intent.EXTRA_TITLE, input.name)
|
||||
|
||||
override fun parseResult(resultCode: Int, intent: Intent?): Uri? = intent?.data?.takeIf { resultCode == Activity.RESULT_OK }
|
||||
}
|
||||
|
||||
/** A file on the phone, as the picker or another app's share named it. */
|
||||
data class LocalFile(val uri: Uri, val name: String, val size: Long, val mime: String)
|
||||
|
||||
fun ContentResolver.describe(uri: Uri): LocalFile {
|
||||
var name: String? = null
|
||||
var size = -1L
|
||||
runCatching {
|
||||
query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { c ->
|
||||
if (c.moveToFirst()) {
|
||||
c.getColumnIndex(OpenableColumns.DISPLAY_NAME).takeIf { it >= 0 }?.let { name = c.getString(it) }
|
||||
c.getColumnIndex(OpenableColumns.SIZE).takeIf { it >= 0 && !c.isNull(it) }?.let { size = c.getLong(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
val said = name?.substringAfterLast('/')?.ifBlank { null } ?: uri.lastPathSegment?.substringAfterLast('/')?.ifBlank { null } ?: "upload"
|
||||
return LocalFile(uri, said, size, getType(uri) ?: "application/octet-stream")
|
||||
}
|
||||
|
||||
/**
|
||||
* A request body that reads [open]'s stream as it is sent: the file is never in memory whole.
|
||||
* [length] is its size when known (-1: sent chunked). [progress] hears how many bytes went.
|
||||
*/
|
||||
class StreamBody(
|
||||
private val type: MediaType?,
|
||||
private val length: Long,
|
||||
private val progress: (Long) -> Unit = {},
|
||||
private val open: () -> java.io.InputStream?,
|
||||
) : RequestBody() {
|
||||
override fun contentType(): MediaType? = type
|
||||
|
||||
override fun contentLength(): Long = length
|
||||
|
||||
/** The stream is read once: a failed upload is said, not silently sent again from a stream that may not open twice. */
|
||||
override fun isOneShot(): Boolean = true
|
||||
|
||||
override fun writeTo(sink: BufferedSink) {
|
||||
val stream = open() ?: throw IOException("The file could not be opened.")
|
||||
stream.source().use { source ->
|
||||
var sent = 0L
|
||||
while (true) {
|
||||
val n = source.read(sink.buffer, 64 * 1024L)
|
||||
if (n < 0) break
|
||||
sent += n
|
||||
sink.emitCompleteSegments()
|
||||
progress(sent)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload one file of the phone into [dir], streamed from its content address -- opened through
|
||||
* [SharedSource], so an address that leads to this app's own files is refused whoever named it.
|
||||
*/
|
||||
suspend fun ApiClient.uploadFrom(context: Context, file: LocalFile, dir: String, progress: (Long) -> Unit = {}): FileListing =
|
||||
uploadFile(dir, file.name, StreamBody(file.mime.toMediaTypeOrNull(), file.size, progress) { SharedSource.open(context, file.uri) })
|
||||
|
||||
/**
|
||||
* Download what [request] answers into the document [to] the person chose. A download that
|
||||
* fails or is given up leaves no half file behind where the provider lets it be removed.
|
||||
*/
|
||||
suspend fun ApiClient.downloadTo(context: Context, request: okhttp3.Request, to: Uri, progress: (Long, Long) -> Unit = { _, _ -> }) {
|
||||
try {
|
||||
withContext(Dispatchers.IO) {
|
||||
val out = context.contentResolver.openOutputStream(to, "w") ?: throw IOException("The file could not be written.")
|
||||
out.use { download(request, it, progress = progress) }
|
||||
}
|
||||
} catch (e: Throwable) {
|
||||
withContext(kotlinx.coroutines.NonCancellable + Dispatchers.IO) { runCatching { DocumentsContract.deleteDocument(context.contentResolver, to) } }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
/** A copy of what [request] answers in [file] (the private cache), at most [most] bytes. */
|
||||
suspend fun ApiClient.copyInto(request: okhttp3.Request, file: File, most: Long = Long.MAX_VALUE, progress: (Long, Long) -> Unit = { _, _ -> }): File {
|
||||
try {
|
||||
withContext(Dispatchers.IO) {
|
||||
file.parentFile?.mkdirs()
|
||||
file.outputStream().use { download(request, it, most, progress) }
|
||||
}
|
||||
} catch (e: Throwable) {
|
||||
withContext(kotlinx.coroutines.NonCancellable + Dispatchers.IO) { runCatching { file.delete() } }
|
||||
throw e
|
||||
}
|
||||
return file
|
||||
}
|
||||
|
||||
/** 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 {
|
||||
val uri = FileCache.uri(context, file)
|
||||
val intent = Intent(Intent.ACTION_VIEW).setDataAndType(uri, mime.ifBlank { "*/*" }).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
return Intent.createChooser(intent, null)
|
||||
}
|
||||
|
||||
fun share(context: Context, files: List<File>, mime: String): Intent {
|
||||
val uris = files.map { FileCache.uri(context, it) }
|
||||
val intent = if (uris.size == 1) {
|
||||
Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_STREAM, uris[0])
|
||||
} else {
|
||||
Intent(Intent.ACTION_SEND_MULTIPLE).putParcelableArrayListExtra(Intent.EXTRA_STREAM, ArrayList(uris))
|
||||
}
|
||||
intent.setType(mime.ifBlank { "*/*" }).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
// The chooser's own preview reads the address too: it is told through the clip.
|
||||
intent.clipData = ClipData.newRawUri(null, uris[0]).apply { uris.drop(1).forEach { addItem(ClipData.Item(it)) } }
|
||||
return Intent.createChooser(intent, null)
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a failure says the server has no such route at all (an older instance), rather than refusing. */
|
||||
fun noSuchRoute(e: Throwable): Boolean = e is ApiException && (e.status == 405 || (e.status == 404 && e.message == "Not Found"))
|
||||
|
||||
/** [report], heard only every quarter megabyte and at the end: a transfer does not redraw the screen for every packet. */
|
||||
fun stepped(report: (Long, Long) -> Unit): (Long, Long) -> Unit {
|
||||
var last = 0L
|
||||
return { done, total ->
|
||||
if (done - last >= 256 * 1024 || done == total) {
|
||||
last = done
|
||||
report(done, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -75,9 +75,11 @@ import androidx.lifecycle.viewModelScope
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.ChatPage
|
||||
import eu.llembas.android.api.Doorstep
|
||||
import eu.llembas.android.api.Folder
|
||||
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
|
||||
@@ -90,12 +92,17 @@ import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.put
|
||||
import java.time.Instant
|
||||
import java.time.LocalDate
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.ZoneId
|
||||
|
||||
data class ChatsState(
|
||||
@@ -124,6 +131,60 @@ fun ChatsState.reported(data: String): ChatsState {
|
||||
return copy(unreadReports = frame.unread.coerceAtLeast(0), reports = true)
|
||||
}
|
||||
|
||||
/**
|
||||
* The list's newest page read again ([page]), merged by id: the page's chats first, as the server
|
||||
* orders and marks them now (the one a reply just started in first, running or unread), then
|
||||
* every chat this list held that the page does not name, in the order it had. A chat that came
|
||||
* up from a later page a person had loaded is in the page, so it moves; the ones around its old
|
||||
* place stay. No chat is listed twice.
|
||||
*
|
||||
* The list is ordered by when a chat last changed, so the page holds every chat that changed
|
||||
* since its own last one did: a chat held here from after that moment which the page does not
|
||||
* name is no longer in the list (deleted, archived or filed away elsewhere), and goes. A page
|
||||
* with nothing after it is the whole list.
|
||||
*/
|
||||
fun ChatsState.withNewest(page: ChatPage): ChatsState {
|
||||
if (!page.more) return copy(chats = page.chats, more = false)
|
||||
val newest = page.chats.mapTo(HashSet()) { it.id }
|
||||
val floor = page.chats.lastOrNull()?.updatedAt?.let(::moment)
|
||||
val older = chats.filter { it.id !in newest && !gone(it, floor) }
|
||||
// Nothing below the page: whether there is more is the page's word.
|
||||
return copy(chats = page.chats + older, more = if (older.isEmpty()) page.more else more)
|
||||
}
|
||||
|
||||
/** Whether [chat], which the newest page does not name, changed after the page's last chat did ([floor]): it would be in the page were it still listed. */
|
||||
private fun gone(chat: Chat, floor: Instant?): Boolean {
|
||||
val changed = chat.updatedAt?.let(::moment) ?: return false
|
||||
return floor != null && changed.isAfter(floor)
|
||||
}
|
||||
|
||||
/** A time as the server writes it (ISO 8601 with an offset); null for anything else. */
|
||||
private fun moment(stamp: String): Instant? = runCatching { OffsetDateTime.parse(stamp).toInstant() }.getOrNull()
|
||||
|
||||
/**
|
||||
* Whether the events route's `reply` frame [said] asks for the list to be read again. Only
|
||||
* while something shows the list ([shown]; the drawer reads it whenever it opens), and only for
|
||||
* what the list does not show already: a reply that started in a chat whose row says it is
|
||||
* running is no news (every reconnection of the route says all of those again), and the end
|
||||
* of a reply in a chat that is listed is marked on its row without a read ([ended]). A list
|
||||
* not read yet is left to its first read.
|
||||
*/
|
||||
fun ChatsState.readsFor(said: ReplyFrame, shown: Boolean): Boolean {
|
||||
if (!shown || chats.isEmpty() || said.chatId.isBlank()) return false
|
||||
val row = chats.firstOrNull { it.id == said.chatId }
|
||||
return if (said.live) row?.running != true else row == null
|
||||
}
|
||||
|
||||
/**
|
||||
* A reply ended in the chat [said] names (`live` false): its row is no longer running, and shows
|
||||
* that it has something new -- unless it is the chat [open] on screen, where the person watched
|
||||
* it end. Nothing is read for it.
|
||||
*/
|
||||
fun ChatsState.ended(said: ReplyFrame, open: String?): ChatsState {
|
||||
if (said.live || chats.none { it.id == said.chatId }) return this
|
||||
return copy(chats = chats.map { if (it.id == said.chatId) it.copy(running = false, unread = it.unread || it.id != open) else it })
|
||||
}
|
||||
|
||||
/** The drawer's list: every chat of the instance in use, both kinds, newest first. */
|
||||
class ChatsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ChatsState())
|
||||
@@ -189,7 +250,14 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
* badge is then what the drawer's own read said.
|
||||
*/
|
||||
suspend fun watchReports() {
|
||||
val frames = runCatching { getApplication<Application>().lembas.eventFrames() }.getOrNull() ?: return
|
||||
val app = getApplication<Application>().lembas
|
||||
// What one instance proved about its frames says nothing of another.
|
||||
val instance = app.instances.current()?.id
|
||||
if (instance != endsOf) {
|
||||
ends = ReplyEnds()
|
||||
endsOf = instance
|
||||
}
|
||||
val frames = runCatching { app.eventFrames() }.getOrNull() ?: return
|
||||
try {
|
||||
frames.collect { frame ->
|
||||
// An instance this app refuses shows its refusal and nothing else.
|
||||
@@ -197,6 +265,7 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
reportsTold++
|
||||
_state.update { it.reported(frame.data) }
|
||||
}
|
||||
if (frame.event == "reply" && refused == null) replySaid(frame.data)
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
@@ -205,6 +274,89 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the list is on screen (the drawer is open): only then is it read again by itself. */
|
||||
private var shown = false
|
||||
|
||||
/** The chat open on screen, by its id: the end of its reply is not something new. */
|
||||
var open: String? = null
|
||||
|
||||
/** Whether this instance says when replies end; until it has, a running row is read again now and then. */
|
||||
private var ends = ReplyEnds()
|
||||
|
||||
/** The instance [ends] is about, by its id. */
|
||||
private var endsOf: String? = null
|
||||
|
||||
fun shown(now: Boolean) {
|
||||
shown = now
|
||||
// What was asked for while it was open is the next opening's read.
|
||||
if (!now) soon.forget()
|
||||
}
|
||||
|
||||
/**
|
||||
* The events route said a reply started or ended in one of the person's chats. An end is
|
||||
* marked on the chat's row at once, with no read; a start in a chat the list does not show
|
||||
* as running moves that chat up and gives it its dot at the list's next read, shortly --
|
||||
* while the drawer is open. Closed, nothing is read: it reads the list when it opens.
|
||||
*/
|
||||
private fun replySaid(data: String) {
|
||||
val said = runCatching { LembasJson.decodeFromString(ReplyFrame.serializer(), data) }.getOrNull() ?: return
|
||||
ends.hear(said)
|
||||
val reads = _state.value.readsFor(said, shown)
|
||||
if (!said.live) _state.update { it.ended(said, open) }
|
||||
if (reads) soon.ask()
|
||||
}
|
||||
|
||||
/**
|
||||
* The newest page of the list, read once things have been quiet for a moment: several
|
||||
* replies starting together (a queue, a team) are one read, and a run of them that never
|
||||
* falls quiet still gets one every few seconds. It waits at the gate, so a frame heard just
|
||||
* before the phone locked or the app left the front is one read on the return, not a
|
||||
* request behind the lock. A read under way is never cut short by the next frame.
|
||||
*/
|
||||
private val soon by lazy {
|
||||
Soon(viewModelScope, LIST_PAUSE_MS, LIST_MOST_MS, before = { getApplication<Application>().lembas.gate.pass() }) { readNewest() }
|
||||
}
|
||||
|
||||
private val reading = Mutex()
|
||||
|
||||
/** The list's newest page, merged into what is shown. A list not read yet is left to its first read. */
|
||||
private suspend fun readNewest() = reading.withLock {
|
||||
if (refused != null || _state.value.chats.isEmpty()) return@withLock
|
||||
val page = try {
|
||||
getApplication<Application>().lembas.instances.client()?.chats()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
} ?: return@withLock
|
||||
_state.update { it.withNewest(page) }
|
||||
}
|
||||
|
||||
/**
|
||||
* While the list is on screen and the app in front: an instance that does not say when a
|
||||
* reply ends leaves a row's running mark as old as the list's last read, so while any row
|
||||
* shows one the list is read again at a bounded rate ([runningPause]), at the gate, and no
|
||||
* more once none does. An instance that says the ends ([ReplyEnds]) is never asked: its
|
||||
* frames clear the marks. Runs until cancelled (the drawer closed, the app left the front).
|
||||
*/
|
||||
suspend fun watchRunning() {
|
||||
val gate = getApplication<Application>().lembas.gate
|
||||
var round = 0
|
||||
while (true) {
|
||||
_state.first { state -> state.chats.any { it.running } }
|
||||
if (ends.said) return
|
||||
delay(runningPause(round))
|
||||
gate.pass()
|
||||
if (ends.said) return
|
||||
if (_state.value.chats.none { it.running }) {
|
||||
round = 0
|
||||
continue
|
||||
}
|
||||
round++
|
||||
readNewest()
|
||||
}
|
||||
}
|
||||
|
||||
/** How many `reports` frames have come: a list read that began before the last one is older than it. */
|
||||
private var reportsTold = 0
|
||||
|
||||
@@ -314,6 +466,12 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
|
||||
private const val SEARCH_PAUSE_MS = 400L
|
||||
|
||||
/** Between a `reply` frame and the list's read: a reply is said about a quarter of a second after it starts. */
|
||||
private const val LIST_PAUSE_MS = 1500L
|
||||
|
||||
/** The longest a read of the list waits for the replies' frames to fall quiet. */
|
||||
private const val LIST_MOST_MS = 6000L
|
||||
|
||||
/** Where the drawer can go, besides a chat. */
|
||||
interface DrawerActions {
|
||||
fun newChat() {}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package eu.llembas.android.ui.home
|
||||
|
||||
import eu.llembas.android.api.ReplyFrame
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* Something done shortly after it was asked for, once for many askings: [work] runs when nobody
|
||||
* has asked for [pause] milliseconds, and at the latest [most] milliseconds after the first
|
||||
* asking -- so a stream of askings closer together than the pause (a team's replies starting
|
||||
* one after another) still gets its work, every [most], instead of none until it falls quiet.
|
||||
*
|
||||
* Work under way is never cancelled by a new asking; an asking that comes while it runs is
|
||||
* answered by one more run after it. [before] is what the work waits for before it starts (its
|
||||
* turn at the gate): an asking during that wait is still answered by the run it waits for.
|
||||
*
|
||||
* Everything here runs on [scope]'s one thread.
|
||||
*/
|
||||
class Soon(
|
||||
private val scope: CoroutineScope,
|
||||
private val pause: Long,
|
||||
private val most: Long,
|
||||
private val before: suspend () -> Unit = {},
|
||||
private val work: suspend () -> Unit,
|
||||
) {
|
||||
private var quiet: Job? = null
|
||||
private var latest: Job? = null
|
||||
|
||||
/** Whether a run is under way, from before its turn to its end. */
|
||||
private var running = false
|
||||
|
||||
/** Whether the run under way has started its work: an asking from then on is newer than it. */
|
||||
private var started = false
|
||||
private var again = false
|
||||
|
||||
fun ask() {
|
||||
if (running) {
|
||||
if (started) again = true
|
||||
return
|
||||
}
|
||||
quiet?.cancel()
|
||||
quiet = scope.launch {
|
||||
delay(pause)
|
||||
run()
|
||||
}
|
||||
if (latest?.isActive != true) {
|
||||
latest = scope.launch {
|
||||
delay(most)
|
||||
run()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** What was asked for and has not started is dropped (nobody is looking any more); work under way finishes. */
|
||||
fun forget() {
|
||||
quiet?.cancel()
|
||||
latest?.cancel()
|
||||
quiet = null
|
||||
latest = null
|
||||
again = false
|
||||
}
|
||||
|
||||
private fun run() {
|
||||
if (running) return
|
||||
val timers = listOf(quiet, latest)
|
||||
quiet = null
|
||||
latest = null
|
||||
started = false
|
||||
running = true
|
||||
// Not a child of either timer: cancelling them below must not reach the work.
|
||||
scope.launch {
|
||||
try {
|
||||
before()
|
||||
started = true
|
||||
work()
|
||||
} finally {
|
||||
running = false
|
||||
if (again) {
|
||||
again = false
|
||||
ask()
|
||||
}
|
||||
}
|
||||
}
|
||||
// One of the two is the caller; it has nothing left to do.
|
||||
timers.forEach { it?.cancel() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the instance says when a reply ends: the events route's `reply` frame with `live`
|
||||
* false, for a reply it had said was being written. One such frame is the proof, and from then
|
||||
* on the list's running marks are cleared by the frames alone. An instance from before that
|
||||
* never proves it, and the list is read again now and then instead ([runningPause]).
|
||||
*/
|
||||
class ReplyEnds {
|
||||
private val started = LinkedHashSet<String>()
|
||||
|
||||
var said = false
|
||||
private set
|
||||
|
||||
fun hear(frame: ReplyFrame) {
|
||||
if (frame.messageId.isBlank()) return
|
||||
if (frame.live) {
|
||||
started += frame.messageId
|
||||
if (started.size > REMEMBERED) started.remove(started.first())
|
||||
} else if (started.remove(frame.messageId)) {
|
||||
said = true
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val REMEMBERED = 64
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How long to wait before the list is read again because a row shows a reply being written and
|
||||
* nothing has said it ended: 5, 10, 20, 40 seconds, then every minute ([round] counts the
|
||||
* reads since a row last showed one). A bounded rate, and only while such a row is on screen.
|
||||
*/
|
||||
fun runningPause(round: Int): Long = (5_000L shl round.coerceIn(0, 4)).coerceAtMost(60_000L)
|
||||
@@ -39,6 +39,7 @@ import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.RunResult
|
||||
import eu.llembas.android.api.SchedulingModel
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.chat.LocalCopy
|
||||
import eu.llembas.android.ui.chat.RichMarkdown
|
||||
@@ -49,7 +50,14 @@ import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
data class RunState(val title: String = "", val result: RunResult? = null, val loading: Boolean = false, val error: String? = null)
|
||||
data class RunState(
|
||||
val title: String = "",
|
||||
val result: RunResult? = null,
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
/** The models scheduled work may run on, for naming the run's by its connection. */
|
||||
val models: List<SchedulingModel> = emptyList(),
|
||||
)
|
||||
|
||||
class RunViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(RunState())
|
||||
@@ -64,6 +72,7 @@ class RunViewModel(app: Application) : AndroidViewModel(app) {
|
||||
val result = api.scheduleRun(schedule, run)
|
||||
val title = runCatching { api.schedule(schedule).title }.getOrDefault("")
|
||||
_state.update { it.copy(result = result, title = title, loading = false) }
|
||||
runCatching { api.schedulingModels() }.onSuccess { m -> _state.update { it.copy(models = m.models) } }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
@@ -128,7 +137,7 @@ fun RunContent(state: RunState, onBack: () -> Unit = {}, onOpenChat: (String) ->
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
RunFacts(run, withPreview = false)
|
||||
RunFacts(run, withPreview = false, models = state.models)
|
||||
// What the run filed for the person, when it filed anything.
|
||||
run.reportId?.let { report -> ReportLink(onClick = { onOpenReport(report) }) }
|
||||
}
|
||||
|
||||
@@ -102,6 +102,7 @@ import eu.llembas.android.api.agentic
|
||||
import eu.llembas.android.api.computerAway
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.api.notifyChoice
|
||||
import eu.llembas.android.api.saidWithConnection
|
||||
import eu.llembas.android.api.titleAmong
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.DirectoryPicker
|
||||
@@ -116,6 +117,9 @@ import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** Whether the Scheduled list starts listening to the events route now: only [inFront], and only once ([listening]). */
|
||||
fun listens(inFront: Boolean, listening: Boolean): Boolean = inFront && !listening
|
||||
|
||||
/** A server without the scheduling routes answers 404 (or 405): it is older, not broken. */
|
||||
private fun Throwable.unsupported(): Boolean = this is ApiException && (status == 404 || status == 405)
|
||||
|
||||
@@ -136,6 +140,19 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) {
|
||||
|
||||
private var live: Job? = null
|
||||
|
||||
/**
|
||||
* Whether the list is on screen, in front. The events route is listened to only then: a read
|
||||
* that comes back after the screen was left (or the phone locked) must not open it, for
|
||||
* nothing would close it again while this model lives.
|
||||
*/
|
||||
private var front = false
|
||||
|
||||
/** The screen came to the front: the list is read, and followed until [stop]. */
|
||||
fun shown() {
|
||||
front = true
|
||||
load()
|
||||
}
|
||||
|
||||
fun load() {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
@@ -163,7 +180,7 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) {
|
||||
* Without it the list is what the last read said, and a pull reads it again.
|
||||
*/
|
||||
private fun watch() {
|
||||
if (live?.isActive == true) return
|
||||
if (!listens(front, live?.isActive == true)) return
|
||||
live = viewModelScope.launch {
|
||||
// The one connection the drawer's badge listens on too (`EventsHub`).
|
||||
val frames = runCatching { getApplication<Application>().lembas.eventFrames() }.getOrNull() ?: return@launch
|
||||
@@ -182,6 +199,7 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) {
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
front = false
|
||||
live?.cancel()
|
||||
live = null
|
||||
}
|
||||
@@ -209,7 +227,7 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) {
|
||||
fun ScheduledScreen(onBack: () -> Unit, onOpen: (String) -> Unit, onNew: () -> Unit, onModels: () -> Unit, model: ScheduledViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
LifecycleResumeEffect(Unit) {
|
||||
model.load()
|
||||
model.shown()
|
||||
onPauseOrDispose { model.stop() }
|
||||
}
|
||||
ScheduledContent(state, onBack = onBack, onOpen = onOpen, onNew = onNew, onModels = onModels, onPause = model::pause, onRetry = model::load)
|
||||
@@ -381,6 +399,8 @@ data class ScheduleState(
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
val notice: String? = null,
|
||||
/** The models scheduled work may run on: what tells two with one id apart by their connection. */
|
||||
val models: List<SchedulingModel> = emptyList(),
|
||||
)
|
||||
|
||||
class ScheduleViewModel(app: Application) : AndroidViewModel(app) {
|
||||
@@ -397,6 +417,7 @@ class ScheduleViewModel(app: Application) : AndroidViewModel(app) {
|
||||
val schedule = api.schedule(id)
|
||||
val runs = runCatching { api.scheduleRuns(id) }.getOrNull()
|
||||
_state.update { it.copy(schedule = schedule, runs = runs?.runs.orEmpty(), more = runs?.more == true, loading = false) }
|
||||
runCatching { api.schedulingModels() }.onSuccess { m -> _state.update { it.copy(models = m.models) } }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
@@ -563,7 +584,7 @@ private fun ScheduleBody(
|
||||
// An Agentic schedule with no model of its own runs on the folder's usual one.
|
||||
stringResource(
|
||||
R.string.schedule_model,
|
||||
schedule.model?.takeIf { it.isNotBlank() }
|
||||
state.models.saidWithConnection(schedule.modelRef, schedule.model)
|
||||
?: stringResource(if (schedule.agentic) R.string.schedule_folder_model else R.string.schedule_first_free_model),
|
||||
),
|
||||
modeWords(schedule.mode),
|
||||
@@ -628,7 +649,9 @@ private fun ScheduleBody(
|
||||
)
|
||||
}
|
||||
}
|
||||
items(state.runs, key = { it.id }) { run -> RunRow(run, schedule.runsOn, onOpen = { onOpenRun(run) }, onOpenReport = onOpenReport) }
|
||||
items(state.runs, key = { it.id }) { run ->
|
||||
RunRow(run, schedule.runsOn, onOpen = { onOpenRun(run) }, onOpenReport = onOpenReport, models = state.models)
|
||||
}
|
||||
if (state.more) item { LaunchedEffect(state.runs.size) { onMore() } }
|
||||
}
|
||||
}
|
||||
@@ -757,7 +780,7 @@ internal fun Header(text: String) {
|
||||
* whole row opens the run.
|
||||
*/
|
||||
@Composable
|
||||
private fun RunRow(run: ScheduleRun, runsOn: RunsOn?, onOpen: () -> Unit, onOpenReport: (String) -> Unit = {}) {
|
||||
private fun RunRow(run: ScheduleRun, runsOn: RunsOn?, onOpen: () -> Unit, onOpenReport: (String) -> Unit = {}, models: List<SchedulingModel> = emptyList()) {
|
||||
val palette = LocalPalette.current
|
||||
Surface(
|
||||
onClick = onOpen,
|
||||
@@ -777,7 +800,7 @@ private fun RunRow(run: ScheduleRun, runsOn: RunsOn?, onOpen: () -> Unit, onOpen
|
||||
ran != null -> RanOnLine(ran)
|
||||
runsOn != null -> ComputerName(runsOn, away = run.computerAway)
|
||||
}
|
||||
RunFacts(run, maxLines = 2)
|
||||
RunFacts(run, maxLines = 2, models = models)
|
||||
run.reportId?.let { report -> ReportLink(onClick = { onOpenReport(report) }) }
|
||||
}
|
||||
}
|
||||
@@ -800,9 +823,10 @@ internal fun ReportLink(onClick: () -> Unit) {
|
||||
|
||||
/** Under a run's time: the model and why, what it is doing or the trouble, then its note (or the result's first lines). */
|
||||
@Composable
|
||||
internal fun RunFacts(run: ScheduleRun, maxLines: Int = Int.MAX_VALUE, withPreview: Boolean = true) {
|
||||
internal fun RunFacts(run: ScheduleRun, maxLines: Int = Int.MAX_VALUE, withPreview: Boolean = true, models: List<SchedulingModel> = emptyList()) {
|
||||
val palette = LocalPalette.current
|
||||
val name = run.model.label
|
||||
// Which connection ran it, where the run says so and two models here share the id.
|
||||
val name = models.saidWithConnection(run.model.ref, run.model.label)
|
||||
val from = run.model.switchedFrom
|
||||
val why = runModelWhy(run.model.reason)
|
||||
val model = when {
|
||||
@@ -881,6 +905,8 @@ data class EditState(
|
||||
val wait: String = "",
|
||||
/** An Agentic schedule's model; empty: the folder's usual model. */
|
||||
val model: String = "",
|
||||
/** [model] is the schedule's own `model_ref` as read: looked up as a ref alone ([modelInfo]). A pick is not. */
|
||||
val modelIsRef: Boolean = false,
|
||||
/** The models scheduled work may run on (`GET /schedules/models`): never an interactive-only one. */
|
||||
val models: List<SchedulingModel> = emptyList(),
|
||||
/** The person changed the type or one of its fields themselves. */
|
||||
@@ -970,6 +996,9 @@ fun watchToSend(state: EditState, editing: Boolean): WatchCommand? = when {
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** The form's model among the models offered: by its ref alone where the schedule itself said one. */
|
||||
val EditState.modelInfo: SchedulingModel? get() = models.named(model, modelIsRef)
|
||||
|
||||
/** A schedule as the form holds where it runs; what the person changed meanwhile stays changed. */
|
||||
fun EditState.read(s: Schedule): EditState {
|
||||
val on = s.runsOn
|
||||
@@ -980,7 +1009,7 @@ fun EditState.read(s: Schedule): EditState {
|
||||
readWhere = on?.let {
|
||||
WhereToRun.Computer(it.device, it.cwd.trim(), it.mode.ifBlank { "edit" }, it.approvalWaitMinutes?.takeIf { minutes -> minutes > 0 })
|
||||
},
|
||||
readModel = s.model.orEmpty(),
|
||||
readModel = s.modelKey.orEmpty(),
|
||||
readWatch = watch,
|
||||
// Its own computer is in the list also when it is not linked now, so it can stay chosen.
|
||||
devices = if (on == null || known) devices else devices + LinkedDevice(id = on.device, name = on.deviceName),
|
||||
@@ -990,7 +1019,9 @@ fun EditState.read(s: Schedule): EditState {
|
||||
agentMode = if (whereTouched || on == null) agentMode else on.mode.ifBlank { agentMode },
|
||||
wait = if (whereTouched || on == null) wait else on.approvalWaitMinutes?.toString().orEmpty(),
|
||||
// A Chat schedule's own model too: made Agentic, it is shown as the model it keeps.
|
||||
model = if (whereTouched) model else s.model.orEmpty(),
|
||||
// By its connection where the server says it: the form then ticks the right one of two with one id.
|
||||
model = if (whereTouched) model else s.modelKey.orEmpty(),
|
||||
modelIsRef = if (whereTouched) modelIsRef else !s.modelRef.isNullOrBlank(),
|
||||
watchCommand = if (whereTouched) watchCommand else watch.command,
|
||||
watchTimeout = if (whereTouched) watchTimeout else watch.timeoutS?.toString().orEmpty(),
|
||||
)
|
||||
@@ -1385,7 +1416,7 @@ private fun OnComputer(state: EditState, onWhere: ((EditState) -> EditState) ->
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
state.models.named(state.model)?.titleAmong(state.models)
|
||||
state.modelInfo?.titleAmong(state.models)
|
||||
?: state.model.ifBlank { stringResource(R.string.schedule_folder_model) },
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
)
|
||||
@@ -1414,18 +1445,21 @@ private fun OnComputer(state: EditState, onWhere: ((EditState) -> EditState) ->
|
||||
title = { Text(stringResource(R.string.model)) },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
val pick: (String) -> Unit = { id ->
|
||||
onWhere { it.copy(model = id) }
|
||||
// A row of the list is picked by its key; the schedule's own model stays the ref it was read as.
|
||||
val pick: (String, Boolean) -> Unit = { id, isRef ->
|
||||
onWhere { it.copy(model = id, modelIsRef = isRef) }
|
||||
choosingModel = false
|
||||
}
|
||||
ChoiceRow(selected = state.model.isBlank(), title = stringResource(R.string.schedule_folder_model), line = null, onClick = { pick("") })
|
||||
ChoiceRow(selected = state.model.isBlank(), title = stringResource(R.string.schedule_folder_model), line = null, onClick = {
|
||||
pick("", false)
|
||||
})
|
||||
// The schedule's own model stays offered where the instance no longer lists it: the server says why on Save.
|
||||
val own = state.model.takeIf { m -> m.isNotBlank() && state.models.named(m) == null }
|
||||
own?.let { ChoiceRow(selected = true, title = it, line = null, onClick = { pick(it) }) }
|
||||
// By ref: a schedule read from the instance names its model by id, which still finds it.
|
||||
val chosen = state.models.named(state.model)?.key
|
||||
val own = state.model.takeIf { m -> m.isNotBlank() && state.modelInfo == null }
|
||||
own?.let { ChoiceRow(selected = true, title = it, line = null, onClick = { pick(it, state.modelIsRef) }) }
|
||||
// A schedule that says its connection ticks that row or none; one that says only an id, the first with it.
|
||||
val chosen = state.modelInfo?.key
|
||||
state.models.distinctBy { it.key }.forEach { m ->
|
||||
ChoiceRow(selected = chosen == m.key, title = m.titleAmong(state.models), line = null, onClick = { pick(m.key) })
|
||||
ChoiceRow(selected = chosen == m.key, title = m.titleAmong(state.models), line = null, onClick = { pick(m.key, false) })
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.settings
|
||||
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LifecycleEventEffect
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.McpServer
|
||||
import eu.llembas.android.api.signInAddress
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.files.filesSay
|
||||
import eu.llembas.android.ui.scheduled.ScheduleLogic
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.viewer.openOutside
|
||||
import kotlinx.coroutines.CancellationException
|
||||
|
||||
/** The instance's MCP servers as the page draws them: on their way, refused, or the list. */
|
||||
data class McpState(val servers: List<McpServer> = emptyList(), val loading: Boolean = true, val error: String? = null)
|
||||
|
||||
/**
|
||||
* Settings › MCP servers: the servers whose tools the person's chats may be offered, and how
|
||||
* each is signed in to. One that waits for a sign-in has a button that opens the instance's own
|
||||
* sign-in page **in the browser** -- the sign-in happens there, against the instance, with the
|
||||
* person signed in to the instance by its cookie. The app starts and finishes nothing, and sees,
|
||||
* sends and stores no token of a server; its own token is in no address it opens. The list is
|
||||
* read again whenever the page comes back to the front, which is when the browser was left.
|
||||
*/
|
||||
@Composable
|
||||
fun McpScreen(onBack: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
var state by remember { mutableStateOf(McpState()) }
|
||||
var reads by remember { mutableIntStateOf(0) }
|
||||
var base by remember { mutableStateOf("") }
|
||||
LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { reads++ }
|
||||
LaunchedEffect(reads) {
|
||||
state = state.copy(loading = true, error = null)
|
||||
state = try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
base = api.base
|
||||
McpState(api.mcpServers(), loading = false)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
state.copy(loading = false, error = context.filesSay(e))
|
||||
}
|
||||
}
|
||||
McpContent(
|
||||
state,
|
||||
onBack = onBack,
|
||||
onReload = { reads++ },
|
||||
// Only a page of the instance the app is signed in to is ever opened (signInAddress).
|
||||
onSignIn = { server -> signInAddress(base, server.auth.signinUrl)?.let { openOutside(context, it) } },
|
||||
)
|
||||
}
|
||||
|
||||
/** The words for how a server is signed in to; a state this app does not know is said as the instance says it. */
|
||||
@Composable
|
||||
internal fun mcpState(server: McpServer): String = when (server.auth.state) {
|
||||
"ready" -> stringResource(R.string.mcp_ready)
|
||||
"signed_in" -> stringResource(R.string.mcp_signed_in)
|
||||
"signed_out" -> stringResource(R.string.mcp_signed_out)
|
||||
"needs_signin" -> stringResource(R.string.mcp_needs_signin)
|
||||
else -> server.auth.state
|
||||
}
|
||||
|
||||
/** The page, from [state] alone. Each server is a card: its words stacked, and under them the one button, the card's whole width. */
|
||||
@Composable
|
||||
fun McpContent(state: McpState, onBack: () -> Unit = {}, onReload: () -> Unit = {}, onSignIn: (McpServer) -> Unit = {}) {
|
||||
val palette = LocalPalette.current
|
||||
Scaffold(
|
||||
containerColor = palette.bg,
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
colors = TopAppBarDefaults.topAppBarColors(containerColor = palette.bg, scrolledContainerColor = palette.bg),
|
||||
title = { Text(stringResource(R.string.mcp_title), maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) }
|
||||
},
|
||||
actions = { IconButton(onClick = onReload) { Icon(Icons.Filled.Refresh, contentDescription = stringResource(R.string.reload)) } },
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
when {
|
||||
state.error != null -> Text(state.error, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
|
||||
|
||||
state.loading && state.servers.isEmpty() -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||
|
||||
state.servers.isEmpty() -> Text(
|
||||
stringResource(R.string.mcp_none),
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.align(Alignment.Center).padding(32.dp),
|
||||
)
|
||||
|
||||
else -> LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
item { Text(stringResource(R.string.mcp_intro), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted) }
|
||||
items(state.servers, key = { it.id }) { server -> McpCard(server, onSignIn) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun McpCard(server: McpServer, onSignIn: (McpServer) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val auth = server.auth
|
||||
Column(
|
||||
Modifier.fillMaxWidth().border(1.dp, palette.border, RoundedCornerShape(16.dp)).padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
Text(server.label, style = MaterialTheme.typography.titleMedium, color = palette.ink)
|
||||
Text(
|
||||
listOf(mcpState(server), stringResource(R.string.mcp_tools, server.tools.toString())).joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = if (auth.needsSignIn) palette.danger else palette.inkMuted,
|
||||
)
|
||||
// Who the provider says signed in: a stranger's text, drawn as plain text.
|
||||
if (auth.account.isNotBlank()) {
|
||||
Text(stringResource(R.string.mcp_account, auth.account), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
if (!auth.needsSignIn) {
|
||||
ScheduleLogic.moment(auth.expiresAt)?.let {
|
||||
Text(stringResource(R.string.mcp_until, it), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
if (auth.needsSignIn) {
|
||||
if (auth.signinUrl.isNullOrBlank()) {
|
||||
// One sign-in for everyone, which only an administrator makes: nothing for this person to do.
|
||||
Text(stringResource(R.string.mcp_shared_note), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
} else {
|
||||
Text(stringResource(R.string.mcp_browser_note), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
Button(
|
||||
onClick = { onSignIn(server) },
|
||||
colors = ButtonDefaults.buttonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 8.dp).heightIn(min = 48.dp),
|
||||
) { Text(stringResource(R.string.mcp_sign_in)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@ import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.Dns
|
||||
import androidx.compose.material.icons.filled.Download
|
||||
import androidx.compose.material.icons.filled.ErrorOutline
|
||||
import androidx.compose.material.icons.filled.Extension
|
||||
import androidx.compose.material.icons.filled.Forum
|
||||
import androidx.compose.material.icons.filled.GraphicEq
|
||||
import androidx.compose.material.icons.filled.Hearing
|
||||
@@ -104,6 +105,7 @@ import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.notify.NotificationAccess
|
||||
import eu.llembas.android.push.Push
|
||||
import eu.llembas.android.ui.files.FileCache
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.update.AppVersion
|
||||
import eu.llembas.android.update.ReleaseCheck
|
||||
@@ -134,6 +136,9 @@ import kotlinx.coroutines.launch
|
||||
interface SettingsActions {
|
||||
fun use(instance: Instance) {}
|
||||
fun add() {}
|
||||
|
||||
/** The instance's MCP servers and their sign-ins. */
|
||||
fun mcpServers() {}
|
||||
fun signOut(instance: Instance) {}
|
||||
fun theme(value: String) {}
|
||||
fun language(value: String) {}
|
||||
@@ -206,7 +211,7 @@ data class SettingsState(
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit, onMcp: () -> Unit = {}) {
|
||||
val context = LocalContext.current
|
||||
val store = context.lembas.instances
|
||||
val scope = rememberCoroutineScope()
|
||||
@@ -255,16 +260,24 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
val actions = remember {
|
||||
object : SettingsActions {
|
||||
override fun use(instance: Instance) {
|
||||
scope.launch { store.use(instance.id) }
|
||||
scope.launch {
|
||||
store.use(instance.id)
|
||||
// Copies of one instance's files are not kept around while another is in use.
|
||||
FileCache.clear(context)
|
||||
}
|
||||
}
|
||||
|
||||
override fun add() = onAddInstance()
|
||||
|
||||
override fun mcpServers() = onMcp()
|
||||
|
||||
override fun signOut(instance: Instance) {
|
||||
scope.launch {
|
||||
Push.disable(context, instance)
|
||||
runCatching { store.clientFor(instance).signOut() }
|
||||
store.remove(instance.id)
|
||||
// The copies of the account's files this phone held for a viewer or another app go with it.
|
||||
FileCache.clear(context)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -543,6 +556,9 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
|
||||
if (state.instances.isNotEmpty()) Rule()
|
||||
SettingRow(Icons.Filled.Add, stringResource(R.string.add_instance), onClick = actions::add)
|
||||
state.active?.let { current ->
|
||||
Rule()
|
||||
// The MCP servers of the instance in use, and which of them wait for a sign-in.
|
||||
SettingRow(Icons.Filled.Extension, stringResource(R.string.mcp_title), onClick = actions::mcpServers)
|
||||
Rule()
|
||||
SettingRow(Icons.AutoMirrored.Filled.Logout, stringResource(R.string.sign_out), tint = palette.danger, onClick = {
|
||||
actions.signOut(current)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.15. Do not edit.
|
||||
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.18. Do not edit.
|
||||
package eu.llembas.android.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
@@ -0,0 +1,394 @@
|
||||
package eu.llembas.android.ui.viewer
|
||||
|
||||
import android.text.format.Formatter
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.gestures.detectTransformGestures
|
||||
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.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.Pause
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material3.FilledIconButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButtonDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Slider
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableFloatStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clipToBounds
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ArchiveListing
|
||||
import eu.llembas.android.api.Notebook
|
||||
import eu.llembas.android.api.Table
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import java.util.Locale
|
||||
|
||||
// What the viewer draws for each kind of file, each from its state alone (the screenshot tests
|
||||
// draw these). Everything a file holds is drawn as text or as pixels the app decoded itself:
|
||||
// nothing here interprets a file -- no HTML, no script, no WebView.
|
||||
|
||||
/** What the details page can do; nothing by default, for the screenshot tests. */
|
||||
interface FileActions {
|
||||
fun download() {}
|
||||
|
||||
fun openWith() {}
|
||||
|
||||
fun share() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* A file there is nothing to draw of (an archive, a 3D model, a binary, or one a viewer could
|
||||
* not show): what it is, [note] saying why it is not shown, and the three ways out. The
|
||||
* buttons stack: their words are of unknown length in nine languages.
|
||||
*/
|
||||
@Composable
|
||||
fun DetailsBody(name: String, type: String, size: Long, note: String?, actions: FileActions) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
Column(
|
||||
Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Icon(Icons.AutoMirrored.Filled.InsertDriveFile, contentDescription = null, tint = palette.inkFaint, modifier = Modifier.size(56.dp))
|
||||
Text(name, style = MaterialTheme.typography.titleMedium, textAlign = TextAlign.Center)
|
||||
Column(Modifier.fillMaxWidth().border(1.dp, palette.border, RoundedCornerShape(16.dp)).padding(horizontal = 16.dp, vertical = 8.dp)) {
|
||||
Fact(stringResource(R.string.files_type), type)
|
||||
Fact(stringResource(R.string.files_size), Formatter.formatShortFileSize(context, size))
|
||||
}
|
||||
note?.takeIf { it.isNotBlank() }?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted, textAlign = TextAlign.Center) }
|
||||
OutlinedButton(onClick = actions::download, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) { Text(stringResource(R.string.download)) }
|
||||
OutlinedButton(onClick = actions::openWith, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) { Text(stringResource(R.string.files_open_with)) }
|
||||
OutlinedButton(onClick = actions::share, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) { Text(stringResource(R.string.report_share)) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What an archive holds, as the instance lists it: every name is the archive's own text and is
|
||||
* drawn as text; nothing is unpacked, here or there. How many, the names with their sizes (a
|
||||
* name wraps, its size keeps its width), a line when there are more than are listed, and the
|
||||
* three ways out.
|
||||
*/
|
||||
@Composable
|
||||
fun ArchiveBody(archive: ArchiveListing, actions: FileActions) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp)) {
|
||||
item {
|
||||
Text(
|
||||
stringResource(R.string.archive_entries, (archive.total ?: archive.entries.size).toString()),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(bottom = 8.dp),
|
||||
)
|
||||
}
|
||||
itemsIndexed(archive.entries) { _, entry ->
|
||||
Row(Modifier.fillMaxWidth().heightIn(min = 40.dp).padding(vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
if (entry.dir) Icons.Filled.Folder else Icons.AutoMirrored.Filled.InsertDriveFile,
|
||||
contentDescription = null,
|
||||
tint = palette.inkFaint,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(entry.name, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
|
||||
entry.size?.takeIf { !entry.dir }?.let {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(Formatter.formatShortFileSize(context, it), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (archive.truncated) {
|
||||
item {
|
||||
Text(
|
||||
stringResource(R.string.archive_cut, archive.entries.size.toString()),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
item {
|
||||
Column(Modifier.fillMaxWidth().padding(top = 12.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
OutlinedButton(onClick = actions::download, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.download))
|
||||
}
|
||||
OutlinedButton(onClick = actions::openWith, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.files_open_with))
|
||||
}
|
||||
OutlinedButton(onClick = actions::share, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.report_share))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A label and its value on one line: the label keeps its width, the value takes the rest and wraps. */
|
||||
@Composable
|
||||
private fun Fact(label: String, value: String) {
|
||||
val palette = LocalPalette.current
|
||||
Row(Modifier.fillMaxWidth().padding(vertical = 6.dp)) {
|
||||
Text(label, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted, modifier = Modifier.width(96.dp))
|
||||
Text(value, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
|
||||
/** The width every column of a table has: fixed, so a row's cells line up whatever they hold. */
|
||||
private val COLUMN = 148.dp
|
||||
|
||||
/**
|
||||
* A CSV or TSV file as a grid: every cell one line in a column of one width, the first row as
|
||||
* the heading, the whole grid scrolling sideways as one and down as a list. Cells are text.
|
||||
*/
|
||||
@Composable
|
||||
fun TableBody(table: Table) {
|
||||
val palette = LocalPalette.current
|
||||
val sideways = rememberScrollState()
|
||||
val style = TextStyle(fontSize = 13.sp, lineHeight = 18.sp, color = palette.ink)
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
if (table.cut) Note(stringResource(R.string.table_cut))
|
||||
Box(Modifier.fillMaxSize().horizontalScroll(sideways)) {
|
||||
LazyColumn(Modifier.width(COLUMN * table.columns.coerceAtLeast(1))) {
|
||||
itemsIndexed(table.rows) { i, row ->
|
||||
Row(Modifier.background(if (i == 0) palette.bgSunken else palette.bg)) {
|
||||
for (c in 0 until table.columns.coerceAtLeast(1)) {
|
||||
Text(
|
||||
row.getOrElse(c) { "" },
|
||||
style = if (i == 0) style.copy(fontWeight = FontWeight.SemiBold) else style,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.width(COLUMN).border(0.5.dp, palette.border).padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A quiet line above a body, saying what is not shown. */
|
||||
@Composable
|
||||
internal fun Note(text: String) {
|
||||
val palette = LocalPalette.current
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.fillMaxWidth().background(palette.bgSunken).padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/** A notebook, read-only: each cell's source as text, and under it the plain text it printed. */
|
||||
@Composable
|
||||
fun NotebookBody(notebook: Notebook) {
|
||||
val palette = LocalPalette.current
|
||||
val mono = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 13.sp, lineHeight = 18.sp, color = palette.ink)
|
||||
if (notebook.cells.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.notebook_empty), color = palette.inkMuted, modifier = Modifier.padding(32.dp))
|
||||
}
|
||||
return
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
itemsIndexed(notebook.cells) { _, cell ->
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
if (cell.count != null) "${cell.kind} [${cell.count}]" else cell.kind,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
modifier = Modifier.padding(bottom = 4.dp),
|
||||
)
|
||||
val code = cell.kind == "code"
|
||||
Text(
|
||||
cell.source.ifEmpty { " " },
|
||||
style = if (code) mono else MaterialTheme.typography.bodyMedium.copy(color = palette.ink),
|
||||
// Code sits on the code's ground; a cell of prose is prose on the page.
|
||||
modifier = Modifier.fillMaxWidth().then(
|
||||
if (code) Modifier.background(palette.codeBg, RoundedCornerShape(8.dp)).padding(10.dp) else Modifier,
|
||||
),
|
||||
)
|
||||
if (cell.output.isNotEmpty()) {
|
||||
Text(cell.output, style = mono.copy(color = palette.inkMuted), modifier = Modifier.fillMaxWidth().padding(start = 10.dp, top = 6.dp))
|
||||
}
|
||||
if (cell.cut) Text(stringResource(R.string.notebook_cell_cut), style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
|
||||
}
|
||||
}
|
||||
if (notebook.more > 0) {
|
||||
item {
|
||||
Text(stringResource(R.string.notebook_more, notebook.more.toString()), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** How far a picture zoomed to [scale] may be moved inside a view of [size]: never past its own edge. */
|
||||
fun clampPan(offset: Offset, scale: Float, size: IntSize): Offset {
|
||||
val x = size.width * (scale - 1f) / 2f
|
||||
val y = size.height * (scale - 1f) / 2f
|
||||
return Offset(offset.x.coerceIn(-x, x), offset.y.coerceIn(-y, y))
|
||||
}
|
||||
|
||||
const val ZOOM_MAX = 8f
|
||||
|
||||
/** A picture, whole: two fingers zoom and move it, a double tap zooms in and back. */
|
||||
@Composable
|
||||
fun ZoomableImage(bitmap: ImageBitmap, description: String) {
|
||||
val palette = LocalPalette.current
|
||||
var scale by remember(bitmap) { mutableFloatStateOf(1f) }
|
||||
var offset by remember(bitmap) { mutableStateOf(Offset.Zero) }
|
||||
var size by remember { mutableStateOf(IntSize.Zero) }
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(palette.bgSunken)
|
||||
.clipToBounds()
|
||||
.onSizeChanged { size = it }
|
||||
.pointerInput(bitmap) {
|
||||
detectTransformGestures { _, pan, zoom, _ ->
|
||||
scale = (scale * zoom).coerceIn(1f, ZOOM_MAX)
|
||||
offset = clampPan(offset + pan, scale, size)
|
||||
}
|
||||
}
|
||||
.pointerInput(bitmap) {
|
||||
detectTapGestures(
|
||||
onDoubleTap = {
|
||||
scale = if (scale > 1f) 1f else 3f
|
||||
offset = Offset.Zero
|
||||
},
|
||||
)
|
||||
},
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Image(
|
||||
bitmap,
|
||||
contentDescription = description,
|
||||
contentScale = ContentScale.Fit,
|
||||
modifier = Modifier.fillMaxSize().graphicsLayer {
|
||||
scaleX = scale
|
||||
scaleY = scale
|
||||
translationX = offset.x
|
||||
translationY = offset.y
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** What a player shows: whether it can play yet, is playing, where it is and how long the file is. */
|
||||
data class PlayerUi(val ready: Boolean = false, val playing: Boolean = false, val positionMs: Int = 0, val durationMs: Int = 0)
|
||||
|
||||
/** `m:ss`, or `h:mm:ss` from an hour on: a time read off a player, the same in every language. */
|
||||
fun playTime(ms: Int): String {
|
||||
val all = (ms.coerceAtLeast(0) / 1000)
|
||||
val h = all / 3600
|
||||
val m = all % 3600 / 60
|
||||
val s = all % 60
|
||||
return if (h > 0) String.format(Locale.ROOT, "%d:%02d:%02d", h, m, s) else String.format(Locale.ROOT, "%d:%02d", m, s)
|
||||
}
|
||||
|
||||
/**
|
||||
* A player's controls: the place in the file as a slider the whole width, the two times under
|
||||
* its two ends, and Play or Pause in the middle (56 dp). Nothing here depends on a text's length.
|
||||
*/
|
||||
@Composable
|
||||
fun PlayerControls(ui: PlayerUi, onToggle: () -> Unit, onSeek: (Int) -> Unit, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
var dragging by remember { mutableStateOf<Float?>(null) }
|
||||
val length = ui.durationMs.coerceAtLeast(1).toFloat()
|
||||
Column(modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Slider(
|
||||
value = (dragging ?: ui.positionMs.toFloat()).coerceIn(0f, length),
|
||||
onValueChange = { dragging = it },
|
||||
onValueChangeFinished = {
|
||||
dragging?.let { onSeek(it.toInt()) }
|
||||
dragging = null
|
||||
},
|
||||
valueRange = 0f..length,
|
||||
enabled = ui.ready && ui.durationMs > 0,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
Text(playTime((dragging ?: ui.positionMs.toFloat()).toInt()), style = MaterialTheme.typography.labelMedium, color = palette.inkMuted)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(playTime(ui.durationMs), style = MaterialTheme.typography.labelMedium, color = palette.inkMuted)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
FilledIconButton(
|
||||
onClick = onToggle,
|
||||
enabled = ui.ready,
|
||||
colors = IconButtonDefaults.filledIconButtonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.size(56.dp),
|
||||
) {
|
||||
Icon(
|
||||
if (ui.playing) Icons.Filled.Pause else Icons.Filled.PlayArrow,
|
||||
contentDescription = stringResource(if (ui.playing) R.string.pause else R.string.play),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A text file being edited: the whole text in one field, in the code's type. The field is the
|
||||
* screen; saving and leaving are the bar's.
|
||||
*/
|
||||
@Composable
|
||||
fun EditorBody(text: String, onChange: (String) -> Unit, enabled: Boolean = true) {
|
||||
val palette = LocalPalette.current
|
||||
BasicTextField(
|
||||
value = text,
|
||||
onValueChange = onChange,
|
||||
enabled = enabled,
|
||||
textStyle = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 14.sp, lineHeight = 20.sp, color = palette.ink),
|
||||
cursorBrush = SolidColor(palette.accent),
|
||||
modifier = Modifier.fillMaxSize().background(palette.codeBg).padding(12.dp),
|
||||
)
|
||||
}
|
||||
@@ -112,31 +112,6 @@ fun FileViewer(chatId: String, show: ShowCard, onClose: () -> Unit) {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A file of the person's tree (the Files screen), in the same viewer and under the same rules:
|
||||
* the person's own files are no more trusted than a model's, since a model may have written
|
||||
* them. A file the server withholds (not text, over 1 MB) says why, and offers the web UI.
|
||||
*/
|
||||
@Composable
|
||||
fun TreeFileViewer(path: String, onClose: () -> Unit) {
|
||||
Viewer(
|
||||
file = Viewed(path.substringAfterLast('/').ifBlank { path }, path, 0, "text"),
|
||||
key = path,
|
||||
webUrl = { it.webFile(path) },
|
||||
load = { api, context ->
|
||||
val file = api.fileContent(path)
|
||||
val withheld = file.withheld
|
||||
when {
|
||||
withheld == null -> Loaded.Text(file.text, file.viewKind, file.language)
|
||||
withheld.message.isNotBlank() -> Loaded.Failed(withheld.message)
|
||||
withheld.reason == "too_large" -> Loaded.Failed(context.getString(R.string.viewer_too_large))
|
||||
else -> Loaded.Failed(context.getString(R.string.viewer_not_text))
|
||||
}
|
||||
},
|
||||
onClose = onClose,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Viewer(file: Viewed, key: Any, webUrl: (ApiClient) -> String?, load: suspend (ApiClient, Context) -> Loaded, onClose: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
@@ -321,12 +296,12 @@ private fun linesOf(text: AnnotatedString): List<AnnotatedString> {
|
||||
}
|
||||
}
|
||||
|
||||
private fun copy(context: Context, label: String, text: String) {
|
||||
internal fun copy(context: Context, label: String, text: String) {
|
||||
context.getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText(label, text))
|
||||
}
|
||||
|
||||
/** The web UI's viewer, in the browser (a Custom Tab), where the person's own session is. */
|
||||
private fun openOutside(context: Context, url: String) {
|
||||
internal fun openOutside(context: Context, url: String) {
|
||||
val uri = Uri.parse(url)
|
||||
if (uri.scheme?.lowercase() !in setOf("http", "https")) return
|
||||
runCatching { CustomTabsIntent.Builder().build().launchUrl(context, uri) }
|
||||
|
||||
@@ -0,0 +1,532 @@
|
||||
package eu.llembas.android.ui.viewer
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.pdf.PdfRenderer
|
||||
import android.media.AudioAttributes
|
||||
import android.media.MediaDataSource
|
||||
import android.media.MediaPlayer
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.MusicNote
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LifecycleEventEffect
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.RangeReader
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.api.sampleFor
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.files.FileCache
|
||||
import eu.llembas.android.ui.files.copyInto
|
||||
import eu.llembas.android.ui.files.stepped
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.unreachable
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
|
||||
// The viewers that need the file's bytes: a picture, a PDF, sound and video. The bytes come
|
||||
// from the instance the app is signed in to, with the token in the Authorization header -- the
|
||||
// address handed to nothing: the platform's player reads through [RemoteMedia], which asks the
|
||||
// app's own HTTP client for each piece. No player library is added for this.
|
||||
|
||||
/** The most a picture's file may weigh to be decoded on the phone, and a PDF's to be copied for its pages. */
|
||||
const val IMAGE_MAX_BYTES = 64L * 1024 * 1024
|
||||
const val PDF_MAX_BYTES = 100L * 1024 * 1024
|
||||
|
||||
/** The most pages of a PDF that are laid out; a longer one is read to there and downloaded for the rest. */
|
||||
const val PDF_MAX_PAGES = 2000
|
||||
|
||||
/** How a viewer's bytes came: on their way ([done] of [total], -1 unknown), there, or not shown. */
|
||||
sealed interface Fetched<out T> {
|
||||
data class Loading(val done: Long = 0, val total: Long = -1) : Fetched<Nothing>
|
||||
|
||||
data class Ready<T>(val value: T) : Fetched<T>
|
||||
|
||||
/** [message]: the server's sentence or the network's; null: this phone could not draw it. */
|
||||
data class Failed(val message: String?) : Fetched<Nothing>
|
||||
}
|
||||
|
||||
/**
|
||||
* [file] decoded for the screen: its bounds are read first, and it is sampled down
|
||||
* ([sampleFor]) so neither edge nor the pixel count is more than a phone shows -- a picture
|
||||
* that claims a huge size costs a bounded amount of memory, or is not decoded at all.
|
||||
*/
|
||||
fun decodeCapped(file: File): Bitmap? {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(file.path, bounds)
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
|
||||
var sample = sampleFor(bounds.outWidth, bounds.outHeight)
|
||||
repeat(3) {
|
||||
try {
|
||||
return BitmapFactory.decodeFile(file.path, BitmapFactory.Options().apply { inSampleSize = sample })
|
||||
} catch (e: OutOfMemoryError) {
|
||||
sample *= 2
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** A picture of the tree: copied into the private cache (at most [IMAGE_MAX_BYTES]), decoded small, and the copy deleted at once. */
|
||||
@Composable
|
||||
fun ImageBody(path: String, name: String, size: Long, fallback: @Composable (String?) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val picture by produceState<Fetched<ImageBitmap>>(Fetched.Loading(), path) {
|
||||
if (size > IMAGE_MAX_BYTES) {
|
||||
value = Fetched.Failed(null)
|
||||
return@produceState
|
||||
}
|
||||
val copy = FileCache.viewing(context, name)
|
||||
value = try {
|
||||
val api = context.lembas.instances.client() ?: throw IOException(context.getString(R.string.assist_signed_out))
|
||||
context.lembas.gate.pass()
|
||||
api.copyInto(api.rawFile(path), copy, IMAGE_MAX_BYTES, stepped { done, total -> value = Fetched.Loading(done, total) })
|
||||
val bitmap = withContext(Dispatchers.Default) { decodeCapped(copy) }
|
||||
if (bitmap == null) Fetched.Failed(null) else Fetched.Ready(bitmap.asImageBitmap())
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Fetched.Failed(viewerSays(context, e))
|
||||
} finally {
|
||||
copy.delete()
|
||||
}
|
||||
}
|
||||
when (val now = picture) {
|
||||
is Fetched.Loading -> Progress(now)
|
||||
is Fetched.Failed -> fallback(now.message)
|
||||
is Fetched.Ready -> ZoomableImage(now.value, name)
|
||||
}
|
||||
}
|
||||
|
||||
/** A transfer under way, in the middle of the page: how far, when the size is known. */
|
||||
@Composable
|
||||
internal fun Progress(now: Fetched.Loading) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
if (now.total > 0) CircularProgressIndicator(progress = { (now.done.toFloat() / now.total).coerceIn(0f, 1f) }) else CircularProgressIndicator()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A PDF's pages, drawn by the platform's own renderer from a copy in the private cache. One page
|
||||
* is open at a time, and at most [PDF_MAX_PAGES] are offered. The renderer cannot be stopped in
|
||||
* the middle of a page, and closing it waits for the page being drawn: so [close] is never
|
||||
* called on the main thread -- [closeLater] is.
|
||||
*/
|
||||
class PdfPages(private val copy: File) {
|
||||
private val descriptor = ParcelFileDescriptor.open(copy, ParcelFileDescriptor.MODE_READ_ONLY)
|
||||
private val renderer = try {
|
||||
PdfRenderer(descriptor)
|
||||
} catch (e: Throwable) {
|
||||
descriptor.close()
|
||||
throw e
|
||||
}
|
||||
|
||||
/** Set before the lock is asked for: a page not yet begun is not begun any more. */
|
||||
@Volatile
|
||||
private var closing = false
|
||||
private var closed = false
|
||||
val count: Int = renderer.pageCount.coerceAtMost(PDF_MAX_PAGES)
|
||||
|
||||
/** Page [index] as pixels [width] wide; null once closed or when it cannot be drawn. */
|
||||
fun page(index: Int, width: Int): ImageBitmap? {
|
||||
if (closing || index !in 0 until count || width <= 0) return null
|
||||
return synchronized(this) {
|
||||
if (closed || closing) return@synchronized null
|
||||
runCatching {
|
||||
renderer.openPage(index).use { page ->
|
||||
var w = width
|
||||
var h = (page.height.toLong() * w / page.width.coerceAtLeast(1)).toInt().coerceAtLeast(1)
|
||||
// A page of an odd shape (a long receipt) is drawn smaller rather than as a huge bitmap.
|
||||
while (w.toLong() * h > PAGE_MAX_PIXELS) {
|
||||
w /= 2
|
||||
h /= 2
|
||||
}
|
||||
val bitmap = Bitmap.createBitmap(w.coerceAtLeast(1), h.coerceAtLeast(1), Bitmap.Config.ARGB_8888)
|
||||
// The paper: a PDF draws on transparent, and print is read on white in either theme.
|
||||
bitmap.eraseColor(PAPER)
|
||||
page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
|
||||
bitmap.asImageBitmap()
|
||||
}
|
||||
}.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
/** Lets go of the renderer, the descriptor and the copy, after the page being drawn. Blocks for that long. */
|
||||
fun close() {
|
||||
closing = true
|
||||
synchronized(this) {
|
||||
if (closed) return
|
||||
closed = true
|
||||
runCatching { renderer.close() }
|
||||
runCatching { descriptor.close() }
|
||||
copy.delete()
|
||||
}
|
||||
}
|
||||
|
||||
/** [close] from the main thread: no page is begun from now on, and the rest happens on a thread of its own. */
|
||||
fun closeLater() {
|
||||
closing = true
|
||||
Thread({ close() }, "pdf-close").start()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val PAGE_MAX_PIXELS = 6_000_000L
|
||||
const val PAPER = android.graphics.Color.WHITE
|
||||
}
|
||||
}
|
||||
|
||||
/** A PDF, page by page, as wide as the screen. */
|
||||
@Composable
|
||||
fun PdfBody(path: String, name: String, size: Long, fallback: @Composable (String?) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
var pages by remember(path) { mutableStateOf<Fetched<PdfPages>>(Fetched.Loading()) }
|
||||
DisposableEffect(path) {
|
||||
// Back during a slow page must not wait for it: the closing is not done on this thread.
|
||||
onDispose { (pages as? Fetched.Ready)?.value?.closeLater() }
|
||||
}
|
||||
LaunchedEffect(path) {
|
||||
if (size > PDF_MAX_BYTES) {
|
||||
pages = Fetched.Failed(null)
|
||||
return@LaunchedEffect
|
||||
}
|
||||
val copy = FileCache.viewing(context, name)
|
||||
// Held here too: a viewer closed while the renderer is being made never sees it in `pages`.
|
||||
var made: PdfPages? = null
|
||||
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) })
|
||||
withContext(Dispatchers.IO) { made = PdfPages(copy) }
|
||||
Fetched.Ready(checkNotNull(made))
|
||||
} catch (e: CancellationException) {
|
||||
made?.closeLater()
|
||||
copy.delete()
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
when (val now = pages) {
|
||||
is Fetched.Loading -> Progress(now)
|
||||
is Fetched.Failed -> fallback(now.message)
|
||||
is Fetched.Ready -> PdfPagesList(now.value)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PdfPagesList(pages: PdfPages) {
|
||||
val palette = LocalPalette.current
|
||||
val list = rememberLazyListState()
|
||||
// Read through a derived state: the line is drawn again when the page changes, not at every pixel of a scroll.
|
||||
val first by remember { derivedStateOf { list.firstVisibleItemIndex + 1 } }
|
||||
Column(Modifier.fillMaxSize().background(palette.bgSunken)) {
|
||||
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
|
||||
val width = with(LocalDensity.current) { maxWidth.toPx() }.toInt().coerceIn(1, 1600)
|
||||
LazyColumn(
|
||||
state = list,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(vertical = 8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
items(pages.count) { index ->
|
||||
val page by produceState<ImageBitmap?>(null, pages, index, width) {
|
||||
value = withContext(Dispatchers.Default) { pages.page(index, width) }
|
||||
}
|
||||
val drawn = page
|
||||
if (drawn != null) {
|
||||
Image(drawn, contentDescription = null, contentScale = ContentScale.FillWidth, modifier = Modifier.fillMaxWidth())
|
||||
} else {
|
||||
// Until it is drawn: a sheet of the usual shape, so the list does not jump far.
|
||||
Box(Modifier.fillMaxWidth().aspectRatio(0.707f).background(palette.surfaceRaised))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.viewer_page, first.toString(), pages.count.toString()),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.fillMaxWidth().background(palette.bg).padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A file on the instance as the platform's player reads it: piece by piece, each a `Range`
|
||||
* request made by the app's own HTTP client with the token in its header. The player is never
|
||||
* given an address, so the token is never in one. [what] is a file by its path or by its node
|
||||
* id (what a generated file's result carries).
|
||||
*/
|
||||
class RemoteMedia(api: ApiClient, what: Raw, private val length: Long) : MediaDataSource() {
|
||||
private val reader = RangeReader(length) { from, to -> api.rawBytes(what, from, to) }
|
||||
|
||||
override fun readAt(position: Long, buffer: ByteArray, offset: Int, size: Int): Int = reader.read(position, buffer, offset, size)
|
||||
|
||||
override fun getSize(): Long = length
|
||||
|
||||
override fun close() = reader.close()
|
||||
}
|
||||
|
||||
/** The most a chat's attachment may weigh to be copied for the player. */
|
||||
const val ATTACHED_MAX_BYTES = 512L * 1024 * 1024
|
||||
|
||||
/**
|
||||
* Sound or video, played by the platform's player. A file of the tree ([Raw.Path], [Raw.Node])
|
||||
* is streamed: it starts before the file is there, and seeking asks for the piece it lands in.
|
||||
* A chat's attachment ([Raw.Attached]) is answered whole by the instance, so it is copied into
|
||||
* the private cache first and played from there; the copy goes when the player does. Leaving
|
||||
* the app pauses it; leaving the viewer lets go of it.
|
||||
*/
|
||||
@Composable
|
||||
fun MediaBody(what: Raw, size: Long, video: Boolean, fallback: @Composable (String?) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var ui by remember(what) { mutableStateOf(PlayerUi()) }
|
||||
var failed by remember(what) { mutableStateOf(false) }
|
||||
var said by remember(what) { mutableStateOf<String?>(null) }
|
||||
var player by remember(what) { mutableStateOf<MediaPlayer?>(null) }
|
||||
var surface by remember(what) { mutableStateOf<SurfaceHolder?>(null) }
|
||||
var ratio by remember(what) { mutableStateOf(16f / 9f) }
|
||||
|
||||
DisposableEffect(what) {
|
||||
var held: MediaPlayer? = null
|
||||
var source: RemoteMedia? = null
|
||||
var copy: File? = null
|
||||
val starting = scope.launch {
|
||||
val api = context.lembas.instances.client()
|
||||
if (api == null || (size <= 0 && what !is Raw.Attached)) {
|
||||
failed = true
|
||||
return@launch
|
||||
}
|
||||
try {
|
||||
val made = MediaPlayer().also { held = it }
|
||||
made.setAudioAttributes(
|
||||
AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.setContentType(if (video) AudioAttributes.CONTENT_TYPE_MOVIE else AudioAttributes.CONTENT_TYPE_MUSIC)
|
||||
.build(),
|
||||
)
|
||||
if (what is Raw.Attached) {
|
||||
val local = FileCache.viewing(context, "attachment").also { copy = it }
|
||||
// A copy is a request with the account's file in it: not while the phone is locked.
|
||||
context.lembas.gate.pass()
|
||||
api.copyInto(api.raw(what), local, ATTACHED_MAX_BYTES)
|
||||
made.setDataSource(local.path)
|
||||
} else {
|
||||
made.setDataSource(RemoteMedia(api, what, size).also { source = it })
|
||||
}
|
||||
made.setOnPreparedListener {
|
||||
ui = ui.copy(ready = true, durationMs = it.duration.coerceAtLeast(0))
|
||||
player = it
|
||||
}
|
||||
made.setOnCompletionListener { ui = ui.copy(playing = false, positionMs = ui.durationMs) }
|
||||
made.setOnErrorListener { _, _, _ ->
|
||||
failed = true
|
||||
true
|
||||
}
|
||||
made.setOnVideoSizeChangedListener { _, w, h -> if (w > 0 && h > 0) ratio = (w.toFloat() / h).coerceIn(0.3f, 4f) }
|
||||
made.prepareAsync()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// The instance's refusal of a copy is a sentence to read; the player's own failure is not.
|
||||
said = if (e is ApiException || unreachable(e)) viewerSays(context, e) else null
|
||||
failed = true
|
||||
}
|
||||
}
|
||||
onDispose {
|
||||
starting.cancel()
|
||||
player = null
|
||||
held?.runCatching { release() }
|
||||
source?.runCatching { close() }
|
||||
copy?.runCatching { delete() }
|
||||
}
|
||||
}
|
||||
|
||||
// The picture goes where the surface is, for as long as there is one.
|
||||
LaunchedEffect(player, surface) { player?.runCatching { setDisplay(surface) } }
|
||||
LaunchedEffect(player, ui.playing) {
|
||||
while (ui.playing) {
|
||||
player?.runCatching { currentPosition }?.getOrNull()?.let { ui = ui.copy(positionMs = it) }
|
||||
delay(500)
|
||||
}
|
||||
}
|
||||
LifecycleEventEffect(Lifecycle.Event.ON_STOP) {
|
||||
player?.runCatching { if (isPlaying) pause() }
|
||||
ui = ui.copy(playing = false)
|
||||
}
|
||||
|
||||
if (failed) {
|
||||
fallback(said)
|
||||
return
|
||||
}
|
||||
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
if (video) {
|
||||
AndroidView(
|
||||
factory = { viewContext ->
|
||||
SurfaceView(viewContext).apply {
|
||||
holder.addCallback(
|
||||
object : SurfaceHolder.Callback {
|
||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||
surface = holder
|
||||
}
|
||||
|
||||
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) = Unit
|
||||
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) {
|
||||
player?.runCatching { setDisplay(null) }
|
||||
surface = null
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth().weight(1f, fill = false).aspectRatio(ratio),
|
||||
)
|
||||
} else {
|
||||
Icon(Icons.Filled.MusicNote, contentDescription = null, tint = palette.inkFaint, modifier = Modifier.padding(24.dp).size(72.dp))
|
||||
}
|
||||
PlayerControls(
|
||||
ui,
|
||||
onToggle = {
|
||||
val now = player ?: return@PlayerControls
|
||||
runCatching {
|
||||
if (now.isPlaying) {
|
||||
now.pause()
|
||||
ui = ui.copy(playing = false)
|
||||
} else {
|
||||
if (ui.durationMs > 0 && ui.positionMs >= ui.durationMs) now.seekTo(0)
|
||||
now.start()
|
||||
ui = ui.copy(playing = true)
|
||||
}
|
||||
}
|
||||
},
|
||||
onSeek = { to ->
|
||||
player?.runCatching { seekTo(to) }
|
||||
ui = ui.copy(positionMs = to)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 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)
|
||||
|
||||
/** How a player's file was found before it was handed to the player. */
|
||||
private sealed interface Probed {
|
||||
data object Asking : Probed
|
||||
|
||||
data object There : Probed
|
||||
|
||||
data class Refused(val message: String?) : Probed
|
||||
}
|
||||
|
||||
/**
|
||||
* A player over the whole screen, for a file a chat names: a generated video or track (by its
|
||||
* node id) or an attachment. A file of the tree is asked for its first byte before the player
|
||||
* gets it, so one that is no longer there says so in a sentence rather than as a player that
|
||||
* does not start. Back or the cross closes it and lets go of the player.
|
||||
*/
|
||||
@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun PlayerDialog(playing: Playing, onClose: () -> Unit, gone: String) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
val probed by produceState<Probed>(Probed.Asking, playing.what) {
|
||||
if (playing.what is Raw.Attached) {
|
||||
value = Probed.There
|
||||
return@produceState
|
||||
}
|
||||
value = try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
context.lembas.gate.pass()
|
||||
withContext(Dispatchers.IO) { api.rawBytes(playing.what, 0, 0) }
|
||||
Probed.There
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// By its id the instance's own refusal names the id; "no longer there" is what a person reads.
|
||||
Probed.Refused(if (e is ApiException && e.status == 404) gone else viewerSays(context, e))
|
||||
}
|
||||
}
|
||||
val unplayable: @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(playing.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
when (val now = probed) {
|
||||
Probed.Asking -> Progress(Fetched.Loading())
|
||||
is Probed.Refused -> unplayable(now.message)
|
||||
Probed.There -> MediaBody(playing.what, playing.size, playing.video, unplayable)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.viewer
|
||||
|
||||
import android.content.Context
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileContent
|
||||
import eu.llembas.android.api.FileEntry
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.FileView
|
||||
import eu.llembas.android.api.Notebook
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.api.SaveConflict
|
||||
import eu.llembas.android.api.Table
|
||||
import eu.llembas.android.api.parseNotebook
|
||||
import eu.llembas.android.api.parseTable
|
||||
import eu.llembas.android.api.tableDelimiter
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.files.CreateFile
|
||||
import eu.llembas.android.ui.files.SaidDialog
|
||||
import eu.llembas.android.ui.files.TransferHost
|
||||
import eu.llembas.android.ui.files.TransferViewModel
|
||||
import eu.llembas.android.ui.files.VersionsDialog
|
||||
import eu.llembas.android.ui.files.filesSay
|
||||
import eu.llembas.android.ui.files.noSuchRoute
|
||||
import eu.llembas.android.ui.files.rememberSaver
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/** What a viewer says of a failure: the server's or the network's sentence; null for "too large for this phone". */
|
||||
internal fun viewerSays(context: Context, e: Throwable): String? {
|
||||
val tooLarge = e is ApiException && e.status == 413 && e.message.isNullOrBlank()
|
||||
return if (tooLarge) null else context.explain(e)
|
||||
}
|
||||
|
||||
/**
|
||||
* The text being edited, kept apart from the screen: a megabyte does not fit what Android saves
|
||||
* of a screen when the phone is turned, and unsaved words must not go with it. [draft] is null
|
||||
* while nothing is edited; [touched] once a key was pressed.
|
||||
*/
|
||||
class EditViewModel : ViewModel() {
|
||||
var draft by mutableStateOf<String?>(null)
|
||||
private set
|
||||
var touched by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/** The `sha` the text had when it was read: a save says it, so somebody else's change is not written over. */
|
||||
var base: String = ""
|
||||
private set
|
||||
|
||||
fun start(text: String, sha: String) {
|
||||
draft = text
|
||||
base = sha
|
||||
touched = false
|
||||
}
|
||||
|
||||
fun type(text: String) {
|
||||
draft = text
|
||||
touched = true
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
draft = null
|
||||
touched = false
|
||||
}
|
||||
}
|
||||
|
||||
/** A file of the tree, opened: on its way, not to be had, or what the server says of it. */
|
||||
private sealed interface Opened {
|
||||
data object Loading : Opened
|
||||
|
||||
data class Failed(val message: String) : Opened
|
||||
|
||||
data class Ready(val file: FileContent) : Opened
|
||||
}
|
||||
|
||||
/**
|
||||
* A file of the person's tree, full screen, drawn by what the server says it is (`file_kind`):
|
||||
* text kinds as text (and edited as text), a picture, a PDF's pages, sound and video streamed, a
|
||||
* table's grid, a notebook's cells, and for the rest what it is with Download, Open with and
|
||||
* Share. The person's own files are no more trusted than a model's, since a model may have
|
||||
* written them: **nothing is rendered as HTML and nothing a file holds is run** -- an HTML page
|
||||
* and an SVG are their source. [onChanged]: the file was saved or a version restored, so a
|
||||
* listing behind this is stale.
|
||||
*/
|
||||
@Composable
|
||||
fun TreeFileViewer(path: String, onClose: () -> Unit, startEditing: Boolean = false, onChanged: () -> Unit = {}) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val edit: EditViewModel = viewModel(key = "edit:$path")
|
||||
// Its own, not the Files page's: two hosts of one would each open the other app.
|
||||
val transfers: TransferViewModel = viewModel(key = "viewer-transfers")
|
||||
var opened by remember(path) { mutableStateOf<Opened>(Opened.Loading) }
|
||||
var reads by remember(path) { mutableIntStateOf(0) }
|
||||
var web by remember(path) { mutableStateOf<String?>(null) }
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
var versions by remember { mutableStateOf(false) }
|
||||
var leaving by remember { mutableStateOf(false) }
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
var conflict by remember { mutableStateOf<String?>(null) }
|
||||
var said by remember { mutableStateOf<String?>(null) }
|
||||
var wantsEdit by remember(path) { mutableStateOf(startEditing) }
|
||||
// A table can be read as the text it is, as well as laid out.
|
||||
var tableAsText by remember(path) { mutableStateOf(false) }
|
||||
val saveVersion = rememberSaver(transfers)
|
||||
val name = FileKinds.name(path)
|
||||
|
||||
LaunchedEffect(path, reads) {
|
||||
val api = context.lembas.instances.client()
|
||||
if (api == null) {
|
||||
opened = Opened.Failed(context.getString(R.string.assist_signed_out))
|
||||
return@LaunchedEffect
|
||||
}
|
||||
web = api.webFile(path)
|
||||
opened = try {
|
||||
val file = api.fileContent(path)
|
||||
// A new file opens ready to be written in; so does one whose text was read again after a conflict.
|
||||
if (wantsEdit && FileKinds.editable(file.fileKind, file.writable, file.withheld != null)) edit.start(file.text, file.sha)
|
||||
wantsEdit = false
|
||||
Opened.Ready(file)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Opened.Failed(context.filesSay(e))
|
||||
}
|
||||
}
|
||||
|
||||
val file = (opened as? Opened.Ready)?.file
|
||||
val draft = edit.draft
|
||||
val saveTo = rememberLauncherForActivityResult(CreateFile()) { to -> if (to != null) transfers.download(listOf(path), zip = false, to = to) }
|
||||
val actions = remember(path, file?.mime) {
|
||||
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 share() = transfers.share(listOf(FileEntry(name = name, path = path, mime = file?.mime.orEmpty())))
|
||||
}
|
||||
}
|
||||
|
||||
fun save(force: Boolean) {
|
||||
val text = edit.draft ?: return
|
||||
saving = true
|
||||
scope.launch {
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
val saved = api.saveFile(path, text, base = edit.base, force = force)
|
||||
edit.stop()
|
||||
opened = Opened.Ready(saved)
|
||||
onChanged()
|
||||
} catch (e: SaveConflict) {
|
||||
// Nothing was written. The server's sentence, with the two ways on.
|
||||
conflict = e.message?.ifBlank { null } ?: context.getString(R.string.files_conflict)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
said = context.filesSay(e)
|
||||
} finally {
|
||||
saving = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Leaving with words that were not saved asks first: Back, the cross, and a tap outside all come here.
|
||||
fun close() {
|
||||
when {
|
||||
draft != null && edit.touched -> leaving = true
|
||||
draft != null -> edit.stop()
|
||||
else -> onClose()
|
||||
}
|
||||
}
|
||||
|
||||
Dialog(onDismissRequest = { close() }, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = { close() }) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = {
|
||||
Column {
|
||||
Text(name, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
path,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.StartEllipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
if (draft != null) {
|
||||
IconButton(onClick = { save(force = false) }, enabled = !saving && edit.touched) {
|
||||
Icon(Icons.Filled.Check, contentDescription = stringResource(R.string.save))
|
||||
}
|
||||
} else if (file != null) {
|
||||
if (FileKinds.editable(file.fileKind, file.writable, file.withheld != null)) {
|
||||
IconButton(onClick = {
|
||||
edit.start(file.text, file.sha)
|
||||
}) { Icon(Icons.Filled.Edit, contentDescription = stringResource(R.string.edit)) }
|
||||
}
|
||||
Box {
|
||||
IconButton(onClick = { menu = true }) { Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.more)) }
|
||||
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
|
||||
val then: (() -> Unit) -> (() -> Unit) = { act ->
|
||||
{
|
||||
menu = false
|
||||
act()
|
||||
}
|
||||
}
|
||||
val text = file.text.takeIf { file.withheld == null && it.isNotEmpty() }
|
||||
if (text != null) MenuEntry(R.string.viewer_copy, then { copy(context, name, text) })
|
||||
if (text != null && FileKinds.viewer(file.fileKind) == FileView.Table) {
|
||||
MenuEntry(if (tableAsText) R.string.table_as_table else R.string.table_as_text, then { tableAsText = !tableAsText })
|
||||
}
|
||||
if (file.fileKind != null) {
|
||||
MenuEntry(R.string.download, then { actions.download() })
|
||||
MenuEntry(R.string.files_open_with, then { actions.openWith() })
|
||||
MenuEntry(R.string.report_share, then { actions.share() })
|
||||
MenuEntry(R.string.versions, then { versions = true })
|
||||
}
|
||||
web?.let { url -> MenuEntry(R.string.viewer_open_browser, then { openOutside(context, url) }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.padding(padding).fillMaxSize()) {
|
||||
if (saving) LinearProgressIndicator(Modifier.fillMaxWidth().height(2.dp))
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
when (val now = opened) {
|
||||
Opened.Loading -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||
is Opened.Failed -> Text(now.message, color = palette.inkMuted, modifier = Modifier.align(Alignment.Center).padding(32.dp))
|
||||
is Opened.Ready -> if (draft != null) EditorBody(draft, edit::type, enabled = !saving) else Shown(path, now.file, actions, tableAsText)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (leaving) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { leaving = false },
|
||||
text = { Text(stringResource(R.string.files_unsaved)) },
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
leaving = false
|
||||
edit.stop()
|
||||
},
|
||||
) { Text(stringResource(R.string.discard)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { leaving = false }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
conflict?.let { sentence ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { conflict = null },
|
||||
text = { Text(sentence) },
|
||||
// Two ways on, and neither is the default: the words stack, so each is a whole row.
|
||||
confirmButton = {
|
||||
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.End) {
|
||||
TextButton(
|
||||
onClick = {
|
||||
conflict = null
|
||||
// What the file holds now, in place of what was typed here.
|
||||
edit.stop()
|
||||
wantsEdit = true
|
||||
reads++
|
||||
},
|
||||
) { Text(stringResource(R.string.reload)) }
|
||||
TextButton(
|
||||
onClick = {
|
||||
conflict = null
|
||||
save(force = true)
|
||||
},
|
||||
) { Text(stringResource(R.string.files_save_anyway)) }
|
||||
TextButton(onClick = { conflict = null }) { Text(stringResource(R.string.cancel)) }
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
said?.let { SaidDialog(it, onClose = { said = null }) }
|
||||
if (versions) {
|
||||
VersionsDialog(
|
||||
path,
|
||||
onDownload = { version -> saveVersion(Raw.Path(path, version.id), name, file?.mime.orEmpty()) },
|
||||
onClose = { versions = false },
|
||||
onRestored = {
|
||||
versions = false
|
||||
reads++
|
||||
onChanged()
|
||||
},
|
||||
)
|
||||
}
|
||||
TransferHost(transfers)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MenuEntry(label: Int, onClick: () -> Unit) = DropdownMenuItem(text = { Text(stringResource(label)) }, onClick = onClick)
|
||||
|
||||
/** A file that was read, by its kind. What cannot be drawn falls back to the details page, saying why. */
|
||||
@Composable
|
||||
private fun Shown(path: String, file: FileContent, actions: FileActions, tableAsText: Boolean = false) {
|
||||
val context = LocalContext.current
|
||||
val name = file.name.ifBlank { FileKinds.name(path) }
|
||||
val type = listOf(file.fileKind.orEmpty(), file.mime).filter { it.isNotBlank() }.joinToString(" · ")
|
||||
val details: @Composable (String?) -> Unit = { note -> DetailsBody(name, type, file.size, note ?: stringResource(R.string.files_not_shown), actions) }
|
||||
val withheld = file.withheld
|
||||
when (FileKinds.viewer(file.fileKind)) {
|
||||
FileView.Text -> when {
|
||||
withheld != null -> {
|
||||
val why = if (withheld.reason == "too_large") R.string.viewer_too_large else R.string.viewer_not_text
|
||||
details(withheld.message.ifBlank { stringResource(why) })
|
||||
}
|
||||
|
||||
file.fileKind == "svg" -> Column(Modifier.fillMaxSize()) {
|
||||
Note(stringResource(R.string.files_svg_source))
|
||||
FileBody("code", "xml", 0, file.text)
|
||||
}
|
||||
|
||||
else -> FileBody(file.viewKind, file.language, 0, file.text)
|
||||
}
|
||||
|
||||
FileView.Image -> ImageBody(path, name, file.size, details)
|
||||
|
||||
FileView.Pdf -> PdfBody(path, name, file.size, details)
|
||||
|
||||
FileView.Audio -> MediaBody(Raw.Path(path), file.size, video = false, fallback = details)
|
||||
|
||||
FileView.Video -> MediaBody(Raw.Path(path), file.size, video = true, fallback = details)
|
||||
|
||||
FileView.Table -> if (tableAsText && withheld == null) {
|
||||
FileBody("text", "", 0, file.text)
|
||||
} else {
|
||||
val table by produceState<Fetched<Table>>(Fetched.Loading(), path, file.sha) {
|
||||
value = try {
|
||||
// Up to 1 MB the server sent the text; of a longer table the first megabyte is asked for.
|
||||
val text = if (withheld == null) {
|
||||
file.text
|
||||
} else {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
withContext(Dispatchers.IO) { api.rawBytes(path, 0, TABLE_HEAD - 1).toString(Charsets.UTF_8) }
|
||||
}
|
||||
Fetched.Ready(withContext(Dispatchers.Default) { parseTable(text, tableDelimiter(name, text), partial = withheld != null) })
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Fetched.Failed(if (noSuchRoute(e)) null else viewerSays(context, e))
|
||||
}
|
||||
}
|
||||
when (val now = table) {
|
||||
is Fetched.Loading -> Progress(now)
|
||||
is Fetched.Failed -> details(now.message)
|
||||
is Fetched.Ready -> if (now.value.rows.isEmpty()) FileBody("text", "", 0, file.text) else TableBody(now.value)
|
||||
}
|
||||
}
|
||||
|
||||
FileView.Notebook -> {
|
||||
// Up to a megabyte of JSON: read off the main thread, not while the page is being drawn.
|
||||
val notebook by produceState<Fetched<Notebook>>(Fetched.Loading(), file.sha, file.text) {
|
||||
val parsed = if (withheld == null) withContext(Dispatchers.Default) { parseNotebook(file.text) } else null
|
||||
value = if (parsed != null) Fetched.Ready(parsed) else Fetched.Failed(withheld?.message?.ifBlank { null })
|
||||
}
|
||||
when (val now = notebook) {
|
||||
is Fetched.Loading -> Progress(now)
|
||||
is Fetched.Failed -> details(now.message)
|
||||
is Fetched.Ready -> NotebookBody(now.value)
|
||||
}
|
||||
}
|
||||
|
||||
FileView.Details -> {
|
||||
val archive = file.archive
|
||||
when {
|
||||
// An instance that lists what the archive holds: the names, as text, and nothing unpacked.
|
||||
archive != null && archive.problem == null -> ArchiveBody(archive, actions)
|
||||
|
||||
archive != null -> details(archive.message.ifBlank { stringResource(R.string.archive_unreadable) })
|
||||
|
||||
else -> details(stringResource(if (file.fileKind == "archive") R.string.archive_note else R.string.files_no_viewer))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** How much of a table too long to be sent as text is read for its first rows. */
|
||||
private const val TABLE_HEAD = 1024L * 1024
|
||||
@@ -51,6 +51,11 @@
|
||||
<string name="continue_reply">Pokračovat</string>
|
||||
<string name="older">Starší zprávy</string>
|
||||
<string name="queued">Čeká na odeslání</string>
|
||||
<string name="fate_unknown">Není známo, zda se tato zpráva dostala do počítače. Odešlete ji znovu, nebo ji zahoďte.</string>
|
||||
<string name="fate_carried">Počítač tuto zprávu má a převezme ji při svém dalším tahu.</string>
|
||||
<string name="send_now">Odeslat teď</string>
|
||||
<string name="discard_message_confirm">Zahodit tuto zprávu?</string>
|
||||
<string name="reply_unrecorded">Odpověď na toto nebyla zaznamenána.</string>
|
||||
<string name="thinking">Přemýšlí</string>
|
||||
<string name="thought">Přemýšlel</string>
|
||||
<string name="output_cut">Výstup je zde zkrácen. Celý ho najdete na webové stránce.</string>
|
||||
@@ -348,6 +353,100 @@
|
||||
<string name="files">Soubory</string>
|
||||
<string name="files_all">Všechny soubory</string>
|
||||
<string name="files_empty">Zatím tu nic není. Ani hobití nora.</string>
|
||||
<string name="files_upload">Nahrát</string>
|
||||
<string name="files_new_file">Nový soubor</string>
|
||||
<string name="files_new_file_ask">Jak se má soubor jmenovat? I s příponou, například notes.md.</string>
|
||||
<string name="files_new_folder_ask">Jak se má složka jmenovat?</string>
|
||||
<string name="files_bad_name">Název nesmí být prázdný ani obsahovat lomítko.</string>
|
||||
<string name="files_taken">Něco s názvem %1$s tu už je.</string>
|
||||
<string name="rename">Přejmenovat</string>
|
||||
<string name="files_new_name">Nový název</string>
|
||||
<string name="files_move">Přesunout</string>
|
||||
<string name="files_copy_to">Kopírovat do…</string>
|
||||
<string name="files_move_here">Přesunout sem</string>
|
||||
<string name="files_copy_here">Kopírovat sem</string>
|
||||
<string name="files_move_which">Do které složky přesunout?</string>
|
||||
<string name="files_copy_which">Do které složky kopírovat?</string>
|
||||
<string name="files_choose_folder">Vybrat složku</string>
|
||||
<string name="files_save_here">Uložit sem</string>
|
||||
<string name="files_no_folders">Nejsou tu žádné složky.</string>
|
||||
<string name="files_to_trash">Přesunout do koše</string>
|
||||
<string name="files_trash_one">Přesunout „%1$s“ do koše? Odtamtud ho lze obnovit.</string>
|
||||
<string name="files_trash_many">Přesunout vybrané (%1$s) do koše? Odtud je lze obnovit.</string>
|
||||
<string name="files_trashed">Přesunuto do koše.</string>
|
||||
<string name="files_selected">Vybráno: %1$s</string>
|
||||
<string name="files_select_all">Vybrat vše</string>
|
||||
<string name="download">Stáhnout</string>
|
||||
<string name="files_download_zip">Stáhnout jako zip</string>
|
||||
<string name="files_downloading">Stahuje se…</string>
|
||||
<string name="files_downloaded">Staženo.</string>
|
||||
<string name="files_uploading">Nahrává se %1$s z %2$s…</string>
|
||||
<string name="files_uploaded">Nahráno.</string>
|
||||
<string name="files_open_with">Otevřít v…</string>
|
||||
<string name="files_no_app">Žádná aplikace v tomto telefonu tento druh souboru neotevře.</string>
|
||||
<string name="trash">Koš</string>
|
||||
<string name="trash_is_empty">Koš je prázdný.</string>
|
||||
<string name="trash_empty">Vysypat koš</string>
|
||||
<string name="trash_empty_confirm">Trvale odstranit vše v koši? Nelze to vrátit zpět.</string>
|
||||
<string name="trash_remove">Odstranit trvale</string>
|
||||
<string name="trash_remove_confirm">Trvale odstranit „%1$s“? Nelze to vrátit zpět.</string>
|
||||
<string name="restore">Obnovit</string>
|
||||
<string name="versions">Verze</string>
|
||||
<string name="version_restore">Obnovit tuto verzi</string>
|
||||
<string name="version_restore_confirm">Udělat z této verze aktuální? Ta současná zůstane v seznamu.</string>
|
||||
<string name="version_current">Aktuální</string>
|
||||
<string name="files_type">Typ</string>
|
||||
<string name="files_size">Velikost</string>
|
||||
<string name="files_no_viewer">Pro tento druh souboru není prohlížeč.</string>
|
||||
<string name="files_not_shown">Tento soubor se zde nepodařilo zobrazit. Stále jej lze stáhnout.</string>
|
||||
<string name="files_svg_source">Toto je zdroj obrázku. Chcete-li vidět obrázek, otevřete jej v jiné aplikaci.</string>
|
||||
<string name="archive_note">Obsah tohoto druhu archivu zde nelze vypsat.</string>
|
||||
<string name="archive_entries">Položek: %1$s. Nic se zde nerozbaluje.</string>
|
||||
<string name="archive_cut">Vypsáno je jen prvních %1$s položek.</string>
|
||||
<string name="archive_unreadable">Tento archiv se nepodařilo přečíst.</string>
|
||||
<string name="files_waiting">Čeká se, až bude aplikace otevřená a telefon odemčený.</string>
|
||||
<string name="share_refused">Něco ze sdíleného odsud odeslat nelze a bylo vynecháno.</string>
|
||||
<string name="media_in_trash">Tento soubor je v koši.</string>
|
||||
<string name="table_cut">Do tabulky jsou rozloženy jen první řádky a sloupce. Text obsahuje vše.</string>
|
||||
<string name="table_as_text">Zobrazit jako text</string>
|
||||
<string name="table_as_table">Zobrazit jako tabulku</string>
|
||||
<string name="media_open_in_files">Otevřít v Souborech</string>
|
||||
<string name="media_image">Obrázek</string>
|
||||
<string name="media_video">Video</string>
|
||||
<string name="media_music">Hudba</string>
|
||||
<string name="media_model">3D model</string>
|
||||
<string name="media_gone">Tento soubor už neexistuje.</string>
|
||||
<string name="job_queued">Ve frontě</string>
|
||||
<string name="job_running">Běží</string>
|
||||
<string name="job_done">Hotovo</string>
|
||||
<string name="job_failed">Selhalo</string>
|
||||
<string name="job_cancelled">Zrušeno</string>
|
||||
<string name="job_expired">Vypršelo</string>
|
||||
<string name="mcp_title">Servery MCP</string>
|
||||
<string name="mcp_intro">Servery, jejichž nástroje mohou být nabídnuty ve vašich chatech. Některé se používají s vaším vlastním účtem u nich: jejich nástroje jsou nabízeny, dokud jste přihlášeni.</string>
|
||||
<string name="mcp_none">Na této instanci vám nejsou nabízeny žádné servery MCP.</string>
|
||||
<string name="mcp_ready">Připraveno</string>
|
||||
<string name="mcp_signed_in">Přihlášeno</string>
|
||||
<string name="mcp_signed_out">Nepřihlášeno</string>
|
||||
<string name="mcp_needs_signin">Je potřeba nové přihlášení</string>
|
||||
<string name="mcp_tools">Nástroje: %1$s</string>
|
||||
<string name="mcp_account">Přihlášeno jako %1$s</string>
|
||||
<string name="mcp_until">Přihlášeno do %1$s</string>
|
||||
<string name="mcp_shared_note">Tento server má jedno společné přihlášení, které provádí správce.</string>
|
||||
<string name="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.</string>
|
||||
<string name="mcp_sign_in">Přihlásit se</string>
|
||||
<string name="notebook_empty">Tento zápisník nemá žádné buňky.</string>
|
||||
<string name="notebook_more">Dalších %1$s buněk se nezobrazuje.</string>
|
||||
<string name="notebook_cell_cut">Tato buňka je delší, než se zde zobrazuje.</string>
|
||||
<string name="viewer_page">Strana %1$s z %2$s</string>
|
||||
<string name="play">Přehrát</string>
|
||||
<string name="pause">Pozastavit</string>
|
||||
<string name="files_conflict">Soubor se od otevření změnil. Načtěte ho znovu, nebo přesto uložte.</string>
|
||||
<string name="files_save_anyway">Přesto uložit</string>
|
||||
<string name="reload">Načíst znovu</string>
|
||||
<string name="discard">Zahodit</string>
|
||||
<string name="files_unsaved">Zahodit změny v tomto souboru?</string>
|
||||
<string name="share_to_files">Uložit do Souborů</string>
|
||||
<string name="settings">Nastavení</string>
|
||||
<string name="settings_instances">Instance</string>
|
||||
<string name="sign_out">Odhlásit se</string>
|
||||
|
||||
@@ -51,6 +51,11 @@
|
||||
<string name="continue_reply">Fortsetzen</string>
|
||||
<string name="older">Frühere Nachrichten</string>
|
||||
<string name="queued">Wartet auf das Senden</string>
|
||||
<string name="fate_unknown">Es ist nicht bekannt, ob dies den Computer erreicht hat. Senden Sie es erneut oder verwerfen Sie es.</string>
|
||||
<string name="fate_carried">Der Computer hat diese Nachricht und übernimmt sie bei seinem nächsten Zug.</string>
|
||||
<string name="send_now">Jetzt senden</string>
|
||||
<string name="discard_message_confirm">Diese Nachricht verwerfen?</string>
|
||||
<string name="reply_unrecorded">Die Antwort darauf wurde nicht aufgezeichnet.</string>
|
||||
<string name="thinking">Denkt nach</string>
|
||||
<string name="thought">Nachgedacht</string>
|
||||
<string name="output_cut">Die Ausgabe ist hier verkürzt. Vollständig finden Sie sie auf der Webseite.</string>
|
||||
@@ -348,6 +353,100 @@
|
||||
<string name="files">Dateien</string>
|
||||
<string name="files_all">Alle Dateien</string>
|
||||
<string name="files_empty">Hier ist noch nichts. Nicht einmal eine Hobbithöhle.</string>
|
||||
<string name="files_upload">Hochladen</string>
|
||||
<string name="files_new_file">Neue Datei</string>
|
||||
<string name="files_new_file_ask">Wie soll die Datei heißen? Mit Endung, etwa notes.md.</string>
|
||||
<string name="files_new_folder_ask">Wie soll der Ordner heißen?</string>
|
||||
<string name="files_bad_name">Ein Name darf weder leer sein noch einen Schrägstrich enthalten.</string>
|
||||
<string name="files_taken">Hier gibt es schon etwas namens %1$s.</string>
|
||||
<string name="rename">Umbenennen</string>
|
||||
<string name="files_new_name">Neuer Name</string>
|
||||
<string name="files_move">Verschieben</string>
|
||||
<string name="files_copy_to">Kopieren nach…</string>
|
||||
<string name="files_move_here">Hierher verschieben</string>
|
||||
<string name="files_copy_here">Hierher kopieren</string>
|
||||
<string name="files_move_which">In welchen Ordner verschieben?</string>
|
||||
<string name="files_copy_which">In welchen Ordner kopieren?</string>
|
||||
<string name="files_choose_folder">Ordner wählen</string>
|
||||
<string name="files_save_here">Hier speichern</string>
|
||||
<string name="files_no_folders">Hier gibt es keine Ordner.</string>
|
||||
<string name="files_to_trash">In den Papierkorb</string>
|
||||
<string name="files_trash_one">„%1$s“ in den Papierkorb verschieben? Von dort lässt es sich wiederherstellen.</string>
|
||||
<string name="files_trash_many">Die %1$s ausgewählten in den Papierkorb verschieben? Von dort lassen sie sich wiederherstellen.</string>
|
||||
<string name="files_trashed">In den Papierkorb verschoben.</string>
|
||||
<string name="files_selected">%1$s ausgewählt</string>
|
||||
<string name="files_select_all">Alle auswählen</string>
|
||||
<string name="download">Herunterladen</string>
|
||||
<string name="files_download_zip">Als Zip herunterladen</string>
|
||||
<string name="files_downloading">Wird heruntergeladen…</string>
|
||||
<string name="files_downloaded">Heruntergeladen.</string>
|
||||
<string name="files_uploading">%1$s von %2$s wird hochgeladen…</string>
|
||||
<string name="files_uploaded">Hochgeladen.</string>
|
||||
<string name="files_open_with">Öffnen mit…</string>
|
||||
<string name="files_no_app">Keine App auf diesem Telefon öffnet diese Art von Datei.</string>
|
||||
<string name="trash">Papierkorb</string>
|
||||
<string name="trash_is_empty">Der Papierkorb ist leer.</string>
|
||||
<string name="trash_empty">Papierkorb leeren</string>
|
||||
<string name="trash_empty_confirm">Alles im Papierkorb endgültig entfernen? Das lässt sich nicht rückgängig machen.</string>
|
||||
<string name="trash_remove">Endgültig entfernen</string>
|
||||
<string name="trash_remove_confirm">„%1$s“ endgültig entfernen? Das lässt sich nicht rückgängig machen.</string>
|
||||
<string name="restore">Wiederherstellen</string>
|
||||
<string name="versions">Versionen</string>
|
||||
<string name="version_restore">Diese Version wiederherstellen</string>
|
||||
<string name="version_restore_confirm">Diese Version zur aktuellen machen? Die jetzige bleibt in der Liste.</string>
|
||||
<string name="version_current">Aktuell</string>
|
||||
<string name="files_type">Typ</string>
|
||||
<string name="files_size">Größe</string>
|
||||
<string name="files_no_viewer">Für diese Art von Datei gibt es keinen Betrachter.</string>
|
||||
<string name="files_not_shown">Diese Datei konnte hier nicht gezeigt werden. Sie lässt sich weiterhin herunterladen.</string>
|
||||
<string name="files_svg_source">Das ist der Quelltext des Bildes. Öffne es mit einer anderen App, um das Bild zu sehen.</string>
|
||||
<string name="archive_note">Der Inhalt dieser Art von Archiv kann hier nicht aufgelistet werden.</string>
|
||||
<string name="archive_entries">%1$s Einträge. Hier wird nichts entpackt.</string>
|
||||
<string name="archive_cut">Nur die ersten %1$s Einträge sind aufgelistet.</string>
|
||||
<string name="archive_unreadable">Dieses Archiv konnte nicht gelesen werden.</string>
|
||||
<string name="files_waiting">Wartet, bis die App geöffnet und das Telefon entsperrt ist.</string>
|
||||
<string name="share_refused">Etwas vom Geteilten kann von hier nicht gesendet werden und wurde ausgelassen.</string>
|
||||
<string name="media_in_trash">Diese Datei liegt im Papierkorb.</string>
|
||||
<string name="table_cut">Nur die ersten Zeilen und Spalten sind als Tabelle gesetzt. Der Text enthält alles.</string>
|
||||
<string name="table_as_text">Als Text zeigen</string>
|
||||
<string name="table_as_table">Als Tabelle zeigen</string>
|
||||
<string name="media_open_in_files">In Dateien öffnen</string>
|
||||
<string name="media_image">Bild</string>
|
||||
<string name="media_video">Video</string>
|
||||
<string name="media_music">Musik</string>
|
||||
<string name="media_model">3D-Modell</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>
|
||||
<string name="job_done">Fertig</string>
|
||||
<string name="job_failed">Fehlgeschlagen</string>
|
||||
<string name="job_cancelled">Abgebrochen</string>
|
||||
<string name="job_expired">Abgelaufen</string>
|
||||
<string name="mcp_title">MCP-Server</string>
|
||||
<string name="mcp_intro">Die Server, deren Werkzeuge in den eigenen Chats angeboten werden können. Manche werden mit einem eigenen Konto dort genutzt: Deren Werkzeuge werden angeboten, solange die Anmeldung besteht.</string>
|
||||
<string name="mcp_none">Auf dieser Instanz werden keine MCP-Server angeboten.</string>
|
||||
<string name="mcp_ready">Bereit</string>
|
||||
<string name="mcp_signed_in">Angemeldet</string>
|
||||
<string name="mcp_signed_out">Nicht angemeldet</string>
|
||||
<string name="mcp_needs_signin">Neue Anmeldung nötig</string>
|
||||
<string name="mcp_tools">Werkzeuge: %1$s</string>
|
||||
<string name="mcp_account">Angemeldet als %1$s</string>
|
||||
<string name="mcp_until">Angemeldet bis %1$s</string>
|
||||
<string name="mcp_shared_note">Dieser Server hat eine gemeinsame Anmeldung, die ein Administrator vornimmt.</string>
|
||||
<string name="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.</string>
|
||||
<string name="mcp_sign_in">Anmelden</string>
|
||||
<string name="notebook_empty">Dieses Notebook hat keine Zellen.</string>
|
||||
<string name="notebook_more">%1$s weitere Zellen werden nicht gezeigt.</string>
|
||||
<string name="notebook_cell_cut">Diese Zelle ist länger, als hier gezeigt wird.</string>
|
||||
<string name="viewer_page">Seite %1$s von %2$s</string>
|
||||
<string name="play">Abspielen</string>
|
||||
<string name="pause">Pausieren</string>
|
||||
<string name="files_conflict">Die Datei hat sich geändert, seit Sie sie geöffnet haben. Laden Sie sie neu oder speichern Sie trotzdem.</string>
|
||||
<string name="files_save_anyway">Trotzdem speichern</string>
|
||||
<string name="reload">Neu laden</string>
|
||||
<string name="discard">Verwerfen</string>
|
||||
<string name="files_unsaved">Die Änderungen an dieser Datei verwerfen?</string>
|
||||
<string name="share_to_files">In Dateien speichern</string>
|
||||
<string name="settings">Einstellungen</string>
|
||||
<string name="settings_instances">Instanzen</string>
|
||||
<string name="sign_out">Abmelden</string>
|
||||
|
||||
@@ -51,6 +51,11 @@
|
||||
<string name="continue_reply">Continuar</string>
|
||||
<string name="older">Mensajes anteriores</string>
|
||||
<string name="queued">Esperando para enviarse</string>
|
||||
<string name="fate_unknown">No se sabe si esto llegó al ordenador. Envíalo de nuevo o descártalo.</string>
|
||||
<string name="fate_carried">El ordenador tiene este mensaje y lo incorporará en su próximo turno.</string>
|
||||
<string name="send_now">Enviar ahora</string>
|
||||
<string name="discard_message_confirm">¿Descartar este mensaje?</string>
|
||||
<string name="reply_unrecorded">La respuesta a esto no se registró.</string>
|
||||
<string name="thinking">Pensando</string>
|
||||
<string name="thought">Pensamiento</string>
|
||||
<string name="output_cut">La salida está acortada aquí. La tiene completa en la página web.</string>
|
||||
@@ -348,6 +353,100 @@
|
||||
<string name="files">Archivos</string>
|
||||
<string name="files_all">Todos los archivos</string>
|
||||
<string name="files_empty">Aquí aún no hay nada. Ni siquiera un agujero hobbit.</string>
|
||||
<string name="files_upload">Subir</string>
|
||||
<string name="files_new_file">Nuevo archivo</string>
|
||||
<string name="files_new_file_ask">¿Cómo debe llamarse el archivo? Con su extensión, por ejemplo notes.md.</string>
|
||||
<string name="files_new_folder_ask">¿Cómo debe llamarse la carpeta?</string>
|
||||
<string name="files_bad_name">Un nombre no puede estar vacío ni contener una barra.</string>
|
||||
<string name="files_taken">Ya hay algo llamado %1$s aquí.</string>
|
||||
<string name="rename">Renombrar</string>
|
||||
<string name="files_new_name">Nombre nuevo</string>
|
||||
<string name="files_move">Mover</string>
|
||||
<string name="files_copy_to">Copiar a…</string>
|
||||
<string name="files_move_here">Mover aquí</string>
|
||||
<string name="files_copy_here">Copiar aquí</string>
|
||||
<string name="files_move_which">¿A qué carpeta mover?</string>
|
||||
<string name="files_copy_which">¿A qué carpeta copiar?</string>
|
||||
<string name="files_choose_folder">Elegir una carpeta</string>
|
||||
<string name="files_save_here">Guardar aquí</string>
|
||||
<string name="files_no_folders">Aquí no hay carpetas.</string>
|
||||
<string name="files_to_trash">Mover a la papelera</string>
|
||||
<string name="files_trash_one">¿Mover «%1$s» a la papelera? Se puede restaurar desde allí.</string>
|
||||
<string name="files_trash_many">¿Mover los %1$s seleccionados a la papelera? Desde allí se pueden restaurar.</string>
|
||||
<string name="files_trashed">Movido a la papelera.</string>
|
||||
<string name="files_selected">Seleccionados: %1$s</string>
|
||||
<string name="files_select_all">Seleccionar todo</string>
|
||||
<string name="download">Descargar</string>
|
||||
<string name="files_download_zip">Descargar como zip</string>
|
||||
<string name="files_downloading">Descargando…</string>
|
||||
<string name="files_downloaded">Descargado.</string>
|
||||
<string name="files_uploading">Subiendo %1$s de %2$s…</string>
|
||||
<string name="files_uploaded">Subido.</string>
|
||||
<string name="files_open_with">Abrir con…</string>
|
||||
<string name="files_no_app">Ninguna aplicación de este teléfono abre este tipo de archivo.</string>
|
||||
<string name="trash">Papelera</string>
|
||||
<string name="trash_is_empty">La papelera está vacía.</string>
|
||||
<string name="trash_empty">Vaciar la papelera</string>
|
||||
<string name="trash_empty_confirm">¿Eliminar para siempre todo lo que hay en la papelera? No se puede deshacer.</string>
|
||||
<string name="trash_remove">Eliminar para siempre</string>
|
||||
<string name="trash_remove_confirm">¿Eliminar «%1$s» para siempre? No se puede deshacer.</string>
|
||||
<string name="restore">Restaurar</string>
|
||||
<string name="versions">Versiones</string>
|
||||
<string name="version_restore">Restaurar esta versión</string>
|
||||
<string name="version_restore_confirm">¿Hacer actual esta versión? La actual se queda en la lista.</string>
|
||||
<string name="version_current">Actual</string>
|
||||
<string name="files_type">Tipo</string>
|
||||
<string name="files_size">Tamaño</string>
|
||||
<string name="files_no_viewer">No hay visor para este tipo de archivo.</string>
|
||||
<string name="files_not_shown">Este archivo no se pudo mostrar aquí. Aún se puede descargar.</string>
|
||||
<string name="files_svg_source">Este es el código fuente de la imagen. Ábrela con otra aplicación para ver la imagen.</string>
|
||||
<string name="archive_note">El contenido de este tipo de archivo comprimido no se puede listar aquí.</string>
|
||||
<string name="archive_entries">%1$s entradas. Aquí no se descomprime nada.</string>
|
||||
<string name="archive_cut">Solo se listan las primeras %1$s entradas.</string>
|
||||
<string name="archive_unreadable">No se pudo leer este archivo comprimido.</string>
|
||||
<string name="files_waiting">Esperando a que la aplicación esté abierta y el teléfono desbloqueado.</string>
|
||||
<string name="share_refused">Algo de lo compartido no se puede enviar desde aquí y se ha omitido.</string>
|
||||
<string name="media_in_trash">Ese archivo está en la papelera.</string>
|
||||
<string name="table_cut">Solo las primeras filas y columnas se disponen como tabla. El texto lo contiene todo.</string>
|
||||
<string name="table_as_text">Mostrar como texto</string>
|
||||
<string name="table_as_table">Mostrar como tabla</string>
|
||||
<string name="media_open_in_files">Abrir en Archivos</string>
|
||||
<string name="media_image">Imagen</string>
|
||||
<string name="media_video">Vídeo</string>
|
||||
<string name="media_music">Música</string>
|
||||
<string name="media_model">Modelo 3D</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>
|
||||
<string name="job_done">Hecho</string>
|
||||
<string name="job_failed">Fallidos</string>
|
||||
<string name="job_cancelled">Cancelado</string>
|
||||
<string name="job_expired">Caducado</string>
|
||||
<string name="mcp_title">Servidores MCP</string>
|
||||
<string name="mcp_intro">Los servidores cuyas herramientas pueden ofrecerse en sus chats. Algunos se usan con una cuenta propia en ellos: sus herramientas se ofrecen mientras la sesión esté iniciada.</string>
|
||||
<string name="mcp_none">En esta instancia no se le ofrece ningún servidor MCP.</string>
|
||||
<string name="mcp_ready">Listo</string>
|
||||
<string name="mcp_signed_in">Sesión iniciada</string>
|
||||
<string name="mcp_signed_out">Sin sesión iniciada</string>
|
||||
<string name="mcp_needs_signin">Hace falta iniciar sesión de nuevo</string>
|
||||
<string name="mcp_tools">Herramientas: %1$s</string>
|
||||
<string name="mcp_account">Sesión iniciada como %1$s</string>
|
||||
<string name="mcp_until">Sesión iniciada hasta %1$s</string>
|
||||
<string name="mcp_shared_note">Este servidor tiene un inicio de sesión compartido, que hace un administrador.</string>
|
||||
<string name="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í.</string>
|
||||
<string name="mcp_sign_in">Iniciar sesión</string>
|
||||
<string name="notebook_empty">Este cuaderno no tiene celdas.</string>
|
||||
<string name="notebook_more">No se muestran %1$s celdas más.</string>
|
||||
<string name="notebook_cell_cut">Esta celda es más larga de lo que se muestra aquí.</string>
|
||||
<string name="viewer_page">Página %1$s de %2$s</string>
|
||||
<string name="play">Reproducir</string>
|
||||
<string name="pause">Pausar</string>
|
||||
<string name="files_conflict">El archivo ha cambiado desde que lo abrió. Vuelva a cargarlo o guárdelo de todos modos.</string>
|
||||
<string name="files_save_anyway">Guardar de todos modos</string>
|
||||
<string name="reload">Recargar</string>
|
||||
<string name="discard">Descartar</string>
|
||||
<string name="files_unsaved">¿Descartar los cambios en este archivo?</string>
|
||||
<string name="share_to_files">Guardar en Archivos</string>
|
||||
<string name="settings">Ajustes</string>
|
||||
<string name="settings_instances">Instancias</string>
|
||||
<string name="sign_out">Cerrar sesión</string>
|
||||
|
||||
@@ -51,6 +51,11 @@
|
||||
<string name="continue_reply">Continuer</string>
|
||||
<string name="older">Messages précédents</string>
|
||||
<string name="queued">En attente d\'envoi</string>
|
||||
<string name="fate_unknown">On ne sait pas si ce message est parvenu à l’ordinateur. Renvoyez-le ou supprimez-le.</string>
|
||||
<string name="fate_carried">L’ordinateur a ce message et le prendra en compte à son prochain tour.</string>
|
||||
<string name="send_now">Envoyer maintenant</string>
|
||||
<string name="discard_message_confirm">Abandonner ce message ?</string>
|
||||
<string name="reply_unrecorded">La réponse à ceci n’a pas été enregistrée.</string>
|
||||
<string name="thinking">Réflexion</string>
|
||||
<string name="thought">Réflexion</string>
|
||||
<string name="output_cut">La sortie est raccourcie ici. Vous la trouverez en entier sur la page web.</string>
|
||||
@@ -348,6 +353,100 @@
|
||||
<string name="files">Fichiers</string>
|
||||
<string name="files_all">Tous les fichiers</string>
|
||||
<string name="files_empty">Rien ici pour l\'instant. Pas même un trou de hobbit.</string>
|
||||
<string name="files_upload">Envoyer</string>
|
||||
<string name="files_new_file">Nouveau fichier</string>
|
||||
<string name="files_new_file_ask">Comment le fichier doit-il s’appeler ? Avec son extension, par exemple notes.md.</string>
|
||||
<string name="files_new_folder_ask">Comment le dossier doit-il s\'appeler ?</string>
|
||||
<string name="files_bad_name">Un nom ne peut être ni vide ni contenir de barre oblique.</string>
|
||||
<string name="files_taken">Il y a déjà quelque chose nommé %1$s ici.</string>
|
||||
<string name="rename">Renommer</string>
|
||||
<string name="files_new_name">Nouveau nom</string>
|
||||
<string name="files_move">Déplacer</string>
|
||||
<string name="files_copy_to">Copier vers…</string>
|
||||
<string name="files_move_here">Déplacer ici</string>
|
||||
<string name="files_copy_here">Copier ici</string>
|
||||
<string name="files_move_which">Déplacer vers quel dossier ?</string>
|
||||
<string name="files_copy_which">Copier vers quel dossier ?</string>
|
||||
<string name="files_choose_folder">Choisir un dossier</string>
|
||||
<string name="files_save_here">Enregistrer ici</string>
|
||||
<string name="files_no_folders">Aucun dossier ici.</string>
|
||||
<string name="files_to_trash">Placer dans la corbeille</string>
|
||||
<string name="files_trash_one">Placer « %1$s » dans la corbeille ? On peut l\'y restaurer.</string>
|
||||
<string name="files_trash_many">Placer les %1$s éléments sélectionnés dans la corbeille ? Ils peuvent y être restaurés.</string>
|
||||
<string name="files_trashed">Placé dans la corbeille.</string>
|
||||
<string name="files_selected">Sélectionnés : %1$s</string>
|
||||
<string name="files_select_all">Tout sélectionner</string>
|
||||
<string name="download">Télécharger</string>
|
||||
<string name="files_download_zip">Télécharger en zip</string>
|
||||
<string name="files_downloading">Téléchargement…</string>
|
||||
<string name="files_downloaded">Téléchargé.</string>
|
||||
<string name="files_uploading">Envoi de %1$s sur %2$s…</string>
|
||||
<string name="files_uploaded">Envoyé.</string>
|
||||
<string name="files_open_with">Ouvrir avec…</string>
|
||||
<string name="files_no_app">Aucune application de ce téléphone n’ouvre ce type de fichier.</string>
|
||||
<string name="trash">Corbeille</string>
|
||||
<string name="trash_is_empty">La corbeille est vide.</string>
|
||||
<string name="trash_empty">Vider la corbeille</string>
|
||||
<string name="trash_empty_confirm">Supprimer définitivement tout le contenu de la corbeille ? C’est irréversible.</string>
|
||||
<string name="trash_remove">Supprimer définitivement</string>
|
||||
<string name="trash_remove_confirm">Supprimer définitivement « %1$s » ? C’est irréversible.</string>
|
||||
<string name="restore">Restaurer</string>
|
||||
<string name="versions">Versions</string>
|
||||
<string name="version_restore">Restaurer cette version</string>
|
||||
<string name="version_restore_confirm">Faire de cette version l\'actuelle ? L\'actuelle reste dans la liste.</string>
|
||||
<string name="version_current">Actuelle</string>
|
||||
<string name="files_type">Type</string>
|
||||
<string name="files_size">Taille</string>
|
||||
<string name="files_no_viewer">Il n\'y a pas de visionneuse pour ce type de fichier.</string>
|
||||
<string name="files_not_shown">Ce fichier n\'a pas pu être affiché ici. Il peut toujours être téléchargé.</string>
|
||||
<string name="files_svg_source">Ceci est la source de l’image. Ouvrez-la avec une autre application pour voir l’image.</string>
|
||||
<string name="archive_note">Le contenu de ce type d\'archive ne peut pas être listé ici.</string>
|
||||
<string name="archive_entries">%1$s entrées. Rien n\'est décompressé ici.</string>
|
||||
<string name="archive_cut">Seules les %1$s premières entrées sont listées.</string>
|
||||
<string name="archive_unreadable">Cette archive n\'a pas pu être lue.</string>
|
||||
<string name="files_waiting">En attente que l\'application soit ouverte et le téléphone déverrouillé.</string>
|
||||
<string name="share_refused">Un élément partagé ne peut pas être envoyé d\'ici et a été laissé de côté.</string>
|
||||
<string name="media_in_trash">Ce fichier est dans la corbeille.</string>
|
||||
<string name="table_cut">Seules les premières lignes et colonnes sont mises en tableau. Le texte contient tout.</string>
|
||||
<string name="table_as_text">Afficher comme texte</string>
|
||||
<string name="table_as_table">Afficher comme tableau</string>
|
||||
<string name="media_open_in_files">Ouvrir dans Fichiers</string>
|
||||
<string name="media_image">Image</string>
|
||||
<string name="media_video">Vidéo</string>
|
||||
<string name="media_music">Musique</string>
|
||||
<string name="media_model">Modèle 3D</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>
|
||||
<string name="job_done">Terminé</string>
|
||||
<string name="job_failed">Échecs</string>
|
||||
<string name="job_cancelled">Annulé</string>
|
||||
<string name="job_expired">Expiré</string>
|
||||
<string name="mcp_title">Serveurs MCP</string>
|
||||
<string name="mcp_intro">Les serveurs dont les outils peuvent être proposés dans vos discussions. Certains s’utilisent avec un compte à vous chez eux : leurs outils sont proposés tant que vous y êtes connecté.</string>
|
||||
<string name="mcp_none">Aucun serveur MCP ne vous est proposé sur cette instance.</string>
|
||||
<string name="mcp_ready">Prêt</string>
|
||||
<string name="mcp_signed_in">Connecté</string>
|
||||
<string name="mcp_signed_out">Non connecté</string>
|
||||
<string name="mcp_needs_signin">Nouvelle connexion nécessaire</string>
|
||||
<string name="mcp_tools">Outils : %1$s</string>
|
||||
<string name="mcp_account">Connecté en tant que %1$s</string>
|
||||
<string name="mcp_until">Connecté jusqu’au %1$s</string>
|
||||
<string name="mcp_shared_note">Ce serveur a une connexion partagée, établie par un administrateur.</string>
|
||||
<string name="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.</string>
|
||||
<string name="mcp_sign_in">Se connecter</string>
|
||||
<string name="notebook_empty">Ce notebook n\'a aucune cellule.</string>
|
||||
<string name="notebook_more">%1$s autres cellules ne sont pas affichées.</string>
|
||||
<string name="notebook_cell_cut">Cette cellule est plus longue que ce qui est affiché ici.</string>
|
||||
<string name="viewer_page">Page %1$s sur %2$s</string>
|
||||
<string name="play">Lire</string>
|
||||
<string name="pause">Mettre en pause</string>
|
||||
<string name="files_conflict">Le fichier a changé depuis que vous l\'avez ouvert. Rechargez-le, ou enregistrez quand même.</string>
|
||||
<string name="files_save_anyway">Enregistrer quand même</string>
|
||||
<string name="reload">Recharger</string>
|
||||
<string name="discard">Abandonner</string>
|
||||
<string name="files_unsaved">Abandonner les modifications de ce fichier ?</string>
|
||||
<string name="share_to_files">Enregistrer dans Fichiers</string>
|
||||
<string name="settings">Paramètres</string>
|
||||
<string name="settings_instances">Instances</string>
|
||||
<string name="sign_out">Se déconnecter</string>
|
||||
|
||||
@@ -51,6 +51,11 @@
|
||||
<string name="continue_reply">Folytatás</string>
|
||||
<string name="older">Korábbi üzenetek</string>
|
||||
<string name="queued">Küldésre vár</string>
|
||||
<string name="fate_unknown">Nem tudni, hogy ez eljutott-e a számítógéphez. Küldje el újra, vagy vesse el.</string>
|
||||
<string name="fate_carried">A számítógépnél van ez az üzenet, és a következő körében veszi figyelembe.</string>
|
||||
<string name="send_now">Küldés most</string>
|
||||
<string name="discard_message_confirm">Elveti ezt az üzenetet?</string>
|
||||
<string name="reply_unrecorded">Az erre adott válasz nem lett rögzítve.</string>
|
||||
<string name="thinking">Gondolkodás</string>
|
||||
<string name="thought">Gondolkodott</string>
|
||||
<string name="output_cut">A kimenet itt lerövidítve jelenik meg. A teljes szöveg a weblapon található.</string>
|
||||
@@ -348,6 +353,100 @@
|
||||
<string name="files">Fájlok</string>
|
||||
<string name="files_all">Minden fájl</string>
|
||||
<string name="files_empty">Itt még nincs semmi. Még egy hobbitlyuk sem.</string>
|
||||
<string name="files_upload">Feltöltés</string>
|
||||
<string name="files_new_file">Új fájl</string>
|
||||
<string name="files_new_file_ask">Mi legyen a fájl neve? Kiterjesztéssel együtt, például notes.md.</string>
|
||||
<string name="files_new_folder_ask">Mi legyen a mappa neve?</string>
|
||||
<string name="files_bad_name">A név nem lehet üres, és nem tartalmazhat perjelet.</string>
|
||||
<string name="files_taken">Már van itt valami %1$s néven.</string>
|
||||
<string name="rename">Átnevezés</string>
|
||||
<string name="files_new_name">Új név</string>
|
||||
<string name="files_move">Áthelyezés</string>
|
||||
<string name="files_copy_to">Másolás ide…</string>
|
||||
<string name="files_move_here">Áthelyezés ide</string>
|
||||
<string name="files_copy_here">Másolás ide</string>
|
||||
<string name="files_move_which">Melyik mappába kerüljön át?</string>
|
||||
<string name="files_copy_which">Melyik mappába másolja?</string>
|
||||
<string name="files_choose_folder">Mappa választása</string>
|
||||
<string name="files_save_here">Mentés ide</string>
|
||||
<string name="files_no_folders">Itt nincsenek könyvtárak.</string>
|
||||
<string name="files_to_trash">Áthelyezés a lomtárba</string>
|
||||
<string name="files_trash_one">Áthelyezi a lomtárba: „%1$s”? Onnan visszaállítható.</string>
|
||||
<string name="files_trash_many">A lomtárba helyezi a kijelölteket (%1$s)? Onnan visszaállíthatók.</string>
|
||||
<string name="files_trashed">A lomtárba került.</string>
|
||||
<string name="files_selected">Kijelölve: %1$s</string>
|
||||
<string name="files_select_all">Összes kijelölése</string>
|
||||
<string name="download">Letöltés</string>
|
||||
<string name="files_download_zip">Letöltés zipként</string>
|
||||
<string name="files_downloading">Letöltés…</string>
|
||||
<string name="files_downloaded">Letöltve.</string>
|
||||
<string name="files_uploading">Feltöltés: %1$s / %2$s…</string>
|
||||
<string name="files_uploaded">Feltöltve.</string>
|
||||
<string name="files_open_with">Megnyitás ezzel…</string>
|
||||
<string name="files_no_app">Ezen a telefonon egyetlen alkalmazás sem nyitja meg az ilyen fájlt.</string>
|
||||
<string name="trash">Lomtár</string>
|
||||
<string name="trash_is_empty">A lomtár üres.</string>
|
||||
<string name="trash_empty">Lomtár ürítése</string>
|
||||
<string name="trash_empty_confirm">Véglegesen eltávolítja a lomtár teljes tartalmát? Ez nem vonható vissza.</string>
|
||||
<string name="trash_remove">Végleges eltávolítás</string>
|
||||
<string name="trash_remove_confirm">Véglegesen eltávolítja ezt: „%1$s”? Ez nem vonható vissza.</string>
|
||||
<string name="restore">Visszaállítás</string>
|
||||
<string name="versions">Változatok</string>
|
||||
<string name="version_restore">Változat visszaállítása</string>
|
||||
<string name="version_restore_confirm">Legyen ez az aktuális változat? A mostani a listában marad.</string>
|
||||
<string name="version_current">Jelenlegi</string>
|
||||
<string name="files_type">Típus</string>
|
||||
<string name="files_size">Méret</string>
|
||||
<string name="files_no_viewer">Ehhez a fájlfajtához nincs megjelenítő.</string>
|
||||
<string name="files_not_shown">Ezt a fájlt itt nem sikerült megjeleníteni. Továbbra is letölthető.</string>
|
||||
<string name="files_svg_source">Ez a kép forrása. A kép megtekintéséhez nyissa meg egy másik alkalmazással.</string>
|
||||
<string name="archive_note">Az ilyen fajta archívum tartalma itt nem listázható.</string>
|
||||
<string name="archive_entries">%1$s bejegyzés. Itt semmi sincs kicsomagolva.</string>
|
||||
<string name="archive_cut">Csak az első %1$s bejegyzés szerepel a listában.</string>
|
||||
<string name="archive_unreadable">Ezt az archívumot nem sikerült beolvasni.</string>
|
||||
<string name="files_waiting">Várakozás, amíg az alkalmazás meg van nyitva és a telefon fel van oldva.</string>
|
||||
<string name="share_refused">A megosztottak közül valami innen nem küldhető el, ezért kimaradt.</string>
|
||||
<string name="media_in_trash">Ez a fájl a lomtárban van.</string>
|
||||
<string name="table_cut">Csak az első sorok és oszlopok kerültek táblázatba. A szöveg mindent tartalmaz.</string>
|
||||
<string name="table_as_text">Megjelenítés szövegként</string>
|
||||
<string name="table_as_table">Megjelenítés táblázatként</string>
|
||||
<string name="media_open_in_files">Megnyitás a Fájlokban</string>
|
||||
<string name="media_image">Kép</string>
|
||||
<string name="media_video">Videó</string>
|
||||
<string name="media_music">Zene</string>
|
||||
<string name="media_model">3D-modell</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>
|
||||
<string name="job_done">Kész</string>
|
||||
<string name="job_failed">Sikertelen</string>
|
||||
<string name="job_cancelled">Megszakítva</string>
|
||||
<string name="job_expired">Lejárt</string>
|
||||
<string name="mcp_title">MCP-szerverek</string>
|
||||
<string name="mcp_intro">Azok a szerverek, amelyek eszközei felkínálhatók a csevegéseiben. Némelyik az ottani saját fiókjával használható: az eszközeik addig érhetők el, amíg be van jelentkezve.</string>
|
||||
<string name="mcp_none">Ezen a példányon nincs Önnek felkínált MCP-szerver.</string>
|
||||
<string name="mcp_ready">Kész</string>
|
||||
<string name="mcp_signed_in">Bejelentkezve</string>
|
||||
<string name="mcp_signed_out">Nincs bejelentkezve</string>
|
||||
<string name="mcp_needs_signin">Új bejelentkezés szükséges</string>
|
||||
<string name="mcp_tools">Eszközök: %1$s</string>
|
||||
<string name="mcp_account">Bejelentkezve mint %1$s</string>
|
||||
<string name="mcp_until">Bejelentkezve eddig: %1$s</string>
|
||||
<string name="mcp_shared_note">Ennek a szervernek egy közös bejelentkezése van, amelyet egy rendszergazda végez el.</string>
|
||||
<string name="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.</string>
|
||||
<string name="mcp_sign_in">Bejelentkezés</string>
|
||||
<string name="notebook_empty">Ennek a jegyzetfüzetnek nincsenek cellái.</string>
|
||||
<string name="notebook_more">További %1$s cella nem jelenik meg.</string>
|
||||
<string name="notebook_cell_cut">Ez a cella hosszabb, mint ami itt látszik.</string>
|
||||
<string name="viewer_page">%1$s. / %2$s oldal</string>
|
||||
<string name="play">Lejátszás</string>
|
||||
<string name="pause">Szüneteltetés</string>
|
||||
<string name="files_conflict">A fájl megváltozott, mióta megnyitotta. Töltse be újra, vagy mentse mégis.</string>
|
||||
<string name="files_save_anyway">Mentés mégis</string>
|
||||
<string name="reload">Újratöltés</string>
|
||||
<string name="discard">Elvetés</string>
|
||||
<string name="files_unsaved">Elveti a fájl módosításait?</string>
|
||||
<string name="share_to_files">Mentés a Fájlokba</string>
|
||||
<string name="settings">Beállítások</string>
|
||||
<string name="settings_instances">Példányok</string>
|
||||
<string name="sign_out">Kijelentkezés</string>
|
||||
|
||||
@@ -51,6 +51,11 @@
|
||||
<string name="continue_reply">Continua</string>
|
||||
<string name="older">Messaggi precedenti</string>
|
||||
<string name="queued">In attesa di invio</string>
|
||||
<string name="fate_unknown">Non si sa se questo messaggio abbia raggiunto il computer. Invialo di nuovo o scartalo.</string>
|
||||
<string name="fate_carried">Il computer ha questo messaggio e lo accoglierà al suo prossimo turno.</string>
|
||||
<string name="send_now">Invia ora</string>
|
||||
<string name="discard_message_confirm">Scartare questo messaggio?</string>
|
||||
<string name="reply_unrecorded">La risposta a questo non è stata registrata.</string>
|
||||
<string name="thinking">Ragionamento</string>
|
||||
<string name="thought">Ha ragionato</string>
|
||||
<string name="output_cut">L\'output qui è abbreviato. Lo trovi per intero sulla pagina web.</string>
|
||||
@@ -348,6 +353,100 @@
|
||||
<string name="files">File</string>
|
||||
<string name="files_all">Tutti i file</string>
|
||||
<string name="files_empty">Ancora niente qui. Nemmeno una caverna hobbit.</string>
|
||||
<string name="files_upload">Carica</string>
|
||||
<string name="files_new_file">Nuovo file</string>
|
||||
<string name="files_new_file_ask">Come deve chiamarsi il file? Con l’estensione, ad esempio notes.md.</string>
|
||||
<string name="files_new_folder_ask">Come deve chiamarsi la cartella?</string>
|
||||
<string name="files_bad_name">Un nome non può essere vuoto né contenere una barra.</string>
|
||||
<string name="files_taken">Qui c’è già qualcosa chiamato %1$s.</string>
|
||||
<string name="rename">Rinomina</string>
|
||||
<string name="files_new_name">Nuovo nome</string>
|
||||
<string name="files_move">Sposta</string>
|
||||
<string name="files_copy_to">Copia in…</string>
|
||||
<string name="files_move_here">Sposta qui</string>
|
||||
<string name="files_copy_here">Copia qui</string>
|
||||
<string name="files_move_which">In quale cartella spostare?</string>
|
||||
<string name="files_copy_which">In quale cartella copiare?</string>
|
||||
<string name="files_choose_folder">Scegli una cartella</string>
|
||||
<string name="files_save_here">Salva qui</string>
|
||||
<string name="files_no_folders">Nessuna cartella qui.</string>
|
||||
<string name="files_to_trash">Sposta nel cestino</string>
|
||||
<string name="files_trash_one">Spostare «%1$s» nel cestino? Si può ripristinare da lì.</string>
|
||||
<string name="files_trash_many">Spostare i %1$s selezionati nel cestino? Da lì si possono ripristinare.</string>
|
||||
<string name="files_trashed">Spostato nel cestino.</string>
|
||||
<string name="files_selected">Selezionati: %1$s</string>
|
||||
<string name="files_select_all">Seleziona tutto</string>
|
||||
<string name="download">Scarica</string>
|
||||
<string name="files_download_zip">Scarica come zip</string>
|
||||
<string name="files_downloading">Download in corso…</string>
|
||||
<string name="files_downloaded">Scaricato.</string>
|
||||
<string name="files_uploading">Caricamento di %1$s su %2$s…</string>
|
||||
<string name="files_uploaded">Caricato.</string>
|
||||
<string name="files_open_with">Apri con…</string>
|
||||
<string name="files_no_app">Nessuna app su questo telefono apre questo tipo di file.</string>
|
||||
<string name="trash">Cestino</string>
|
||||
<string name="trash_is_empty">Il cestino è vuoto.</string>
|
||||
<string name="trash_empty">Svuota il cestino</string>
|
||||
<string name="trash_empty_confirm">Rimuovere definitivamente tutto ciò che è nel cestino? Non si può annullare.</string>
|
||||
<string name="trash_remove">Rimuovi definitivamente</string>
|
||||
<string name="trash_remove_confirm">Rimuovere definitivamente «%1$s»? Non si può annullare.</string>
|
||||
<string name="restore">Ripristina</string>
|
||||
<string name="versions">Versioni</string>
|
||||
<string name="version_restore">Ripristina questa versione</string>
|
||||
<string name="version_restore_confirm">Rendere questa versione quella attuale? Quella attuale resta nell\'elenco.</string>
|
||||
<string name="version_current">Attuale</string>
|
||||
<string name="files_type">Tipo</string>
|
||||
<string name="files_size">Dimensione</string>
|
||||
<string name="files_no_viewer">Non c\'è un visualizzatore per questo tipo di file.</string>
|
||||
<string name="files_not_shown">Non è stato possibile mostrare qui questo file. Si può comunque scaricare.</string>
|
||||
<string name="files_svg_source">Questo è il sorgente dell’immagine. Aprila con un’altra app per vedere l’immagine.</string>
|
||||
<string name="archive_note">Il contenuto di questo tipo di archivio non può essere elencato qui.</string>
|
||||
<string name="archive_entries">%1$s voci. Qui non viene estratto nulla.</string>
|
||||
<string name="archive_cut">Sono elencate solo le prime %1$s voci.</string>
|
||||
<string name="archive_unreadable">Non è stato possibile leggere questo archivio.</string>
|
||||
<string name="files_waiting">In attesa che l\'app sia aperta e il telefono sbloccato.</string>
|
||||
<string name="share_refused">Qualcosa di ciò che è stato condiviso non può essere inviato da qui ed è stato escluso.</string>
|
||||
<string name="media_in_trash">Questo file è nel cestino.</string>
|
||||
<string name="table_cut">Solo le prime righe e colonne sono disposte in tabella. Il testo contiene tutto.</string>
|
||||
<string name="table_as_text">Mostra come testo</string>
|
||||
<string name="table_as_table">Mostra come tabella</string>
|
||||
<string name="media_open_in_files">Apri in File</string>
|
||||
<string name="media_image">Immagine</string>
|
||||
<string name="media_video">Video</string>
|
||||
<string name="media_music">Musica</string>
|
||||
<string name="media_model">Modello 3D</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>
|
||||
<string name="job_done">Fatto</string>
|
||||
<string name="job_failed">Non riusciti</string>
|
||||
<string name="job_cancelled">Annullato</string>
|
||||
<string name="job_expired">Scaduto</string>
|
||||
<string name="mcp_title">Server MCP</string>
|
||||
<string name="mcp_intro">I server i cui strumenti possono essere offerti nelle tue chat. Alcuni si usano con un tuo account presso di loro: i loro strumenti sono offerti finché hai effettuato l’accesso.</string>
|
||||
<string name="mcp_none">Su questa istanza non ti è offerto alcun server MCP.</string>
|
||||
<string name="mcp_ready">Pronto</string>
|
||||
<string name="mcp_signed_in">Accesso effettuato</string>
|
||||
<string name="mcp_signed_out">Accesso non effettuato</string>
|
||||
<string name="mcp_needs_signin">Serve un nuovo accesso</string>
|
||||
<string name="mcp_tools">Strumenti: %1$s</string>
|
||||
<string name="mcp_account">Accesso effettuato come %1$s</string>
|
||||
<string name="mcp_until">Accesso valido fino a %1$s</string>
|
||||
<string name="mcp_shared_note">Questo server ha un accesso condiviso, che viene eseguito da un amministratore.</string>
|
||||
<string name="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.</string>
|
||||
<string name="mcp_sign_in">Accedi</string>
|
||||
<string name="notebook_empty">Questo notebook non ha celle.</string>
|
||||
<string name="notebook_more">Altre %1$s celle non vengono mostrate.</string>
|
||||
<string name="notebook_cell_cut">Questa cella è più lunga di quanto mostrato qui.</string>
|
||||
<string name="viewer_page">Pagina %1$s di %2$s</string>
|
||||
<string name="play">Riproduci</string>
|
||||
<string name="pause">Metti in pausa</string>
|
||||
<string name="files_conflict">Il file è cambiato da quando l\'hai aperto. Ricaricalo o salva comunque.</string>
|
||||
<string name="files_save_anyway">Salva comunque</string>
|
||||
<string name="reload">Ricarica</string>
|
||||
<string name="discard">Scarta</string>
|
||||
<string name="files_unsaved">Scartare le modifiche a questo file?</string>
|
||||
<string name="share_to_files">Salva in File</string>
|
||||
<string name="settings">Impostazioni</string>
|
||||
<string name="settings_instances">Istanze</string>
|
||||
<string name="sign_out">Esci</string>
|
||||
|
||||
@@ -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.15 (moria). Do not edit. -->
|
||||
<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.18 (moria). Do not edit. -->
|
||||
<resources>
|
||||
<color name="token_bg">#FF0B0D10</color>
|
||||
<color name="token_surface">#FF11151A</color>
|
||||
|
||||
@@ -51,6 +51,11 @@
|
||||
<string name="continue_reply">Kontynuuj</string>
|
||||
<string name="older">Wcześniejsze wiadomości</string>
|
||||
<string name="queued">Czeka na wysłanie</string>
|
||||
<string name="fate_unknown">Nie wiadomo, czy ta wiadomość dotarła do komputera. Wyślij ją ponownie albo odrzuć.</string>
|
||||
<string name="fate_carried">Komputer ma tę wiadomość i uwzględni ją w swojej następnej turze.</string>
|
||||
<string name="send_now">Wyślij teraz</string>
|
||||
<string name="discard_message_confirm">Odrzucić tę wiadomość?</string>
|
||||
<string name="reply_unrecorded">Odpowiedź na to nie została zapisana.</string>
|
||||
<string name="thinking">Rozumowanie</string>
|
||||
<string name="thought">Rozumowanie</string>
|
||||
<string name="output_cut">Wynik jest tu skrócony. Cały znajduje się na stronie internetowej.</string>
|
||||
@@ -348,6 +353,100 @@
|
||||
<string name="files">Pliki</string>
|
||||
<string name="files_all">Wszystkie pliki</string>
|
||||
<string name="files_empty">Jeszcze nic tu nie ma. Nawet hobbiciej norki.</string>
|
||||
<string name="files_upload">Prześlij</string>
|
||||
<string name="files_new_file">Nowy plik</string>
|
||||
<string name="files_new_file_ask">Jak ma się nazywać plik? Z rozszerzeniem, na przykład notes.md.</string>
|
||||
<string name="files_new_folder_ask">Jak ma się nazywać folder?</string>
|
||||
<string name="files_bad_name">Nazwa nie może być pusta ani zawierać ukośnika.</string>
|
||||
<string name="files_taken">Coś o nazwie %1$s już tu jest.</string>
|
||||
<string name="rename">Zmień nazwę</string>
|
||||
<string name="files_new_name">Nowa nazwa</string>
|
||||
<string name="files_move">Przenieś</string>
|
||||
<string name="files_copy_to">Kopiuj do…</string>
|
||||
<string name="files_move_here">Przenieś tutaj</string>
|
||||
<string name="files_copy_here">Kopiuj tutaj</string>
|
||||
<string name="files_move_which">Do którego folderu przenieść?</string>
|
||||
<string name="files_copy_which">Do którego folderu skopiować?</string>
|
||||
<string name="files_choose_folder">Wybierz folder</string>
|
||||
<string name="files_save_here">Zapisz tutaj</string>
|
||||
<string name="files_no_folders">Brak katalogów.</string>
|
||||
<string name="files_to_trash">Przenieś do kosza</string>
|
||||
<string name="files_trash_one">Przenieść „%1$s” do kosza? Można go stamtąd przywrócić.</string>
|
||||
<string name="files_trash_many">Przenieść zaznaczone (%1$s) do kosza? Stamtąd można je przywrócić.</string>
|
||||
<string name="files_trashed">Przeniesiono do kosza.</string>
|
||||
<string name="files_selected">Zaznaczone: %1$s</string>
|
||||
<string name="files_select_all">Zaznacz wszystko</string>
|
||||
<string name="download">Pobierz</string>
|
||||
<string name="files_download_zip">Pobierz jako zip</string>
|
||||
<string name="files_downloading">Pobieranie…</string>
|
||||
<string name="files_downloaded">Pobrano.</string>
|
||||
<string name="files_uploading">Przesyłanie %1$s z %2$s…</string>
|
||||
<string name="files_uploaded">Przesłano.</string>
|
||||
<string name="files_open_with">Otwórz za pomocą…</string>
|
||||
<string name="files_no_app">Żadna aplikacja na tym telefonie nie otwiera tego rodzaju pliku.</string>
|
||||
<string name="trash">Kosz</string>
|
||||
<string name="trash_is_empty">Kosz jest pusty.</string>
|
||||
<string name="trash_empty">Opróżnij kosz</string>
|
||||
<string name="trash_empty_confirm">Usunąć na stałe wszystko z kosza? Tego nie da się cofnąć.</string>
|
||||
<string name="trash_remove">Usuń na stałe</string>
|
||||
<string name="trash_remove_confirm">Usunąć „%1$s” na stałe? Tego nie da się cofnąć.</string>
|
||||
<string name="restore">Przywróć</string>
|
||||
<string name="versions">Wersje</string>
|
||||
<string name="version_restore">Przywróć tę wersję</string>
|
||||
<string name="version_restore_confirm">Uczynić tę wersję bieżącą? Obecna zostanie na liście.</string>
|
||||
<string name="version_current">Bieżąca</string>
|
||||
<string name="files_type">Typ</string>
|
||||
<string name="files_size">Rozmiar</string>
|
||||
<string name="files_no_viewer">Nie ma przeglądarki dla tego rodzaju pliku.</string>
|
||||
<string name="files_not_shown">Nie udało się tu pokazać tego pliku. Nadal można go pobrać.</string>
|
||||
<string name="files_svg_source">To jest źródło obrazu. Otwórz je w innej aplikacji, aby zobaczyć obraz.</string>
|
||||
<string name="archive_note">Zawartości tego rodzaju archiwum nie można tu wypisać.</string>
|
||||
<string name="archive_entries">Pozycji: %1$s. Nic nie jest tu rozpakowywane.</string>
|
||||
<string name="archive_cut">Wypisano tylko pierwszych %1$s pozycji.</string>
|
||||
<string name="archive_unreadable">Nie udało się odczytać tego archiwum.</string>
|
||||
<string name="files_waiting">Oczekiwanie, aż aplikacja będzie otwarta, a telefon odblokowany.</string>
|
||||
<string name="share_refused">Czegoś z udostępnionych rzeczy nie można stąd wysłać i zostało pominięte.</string>
|
||||
<string name="media_in_trash">Ten plik jest w koszu.</string>
|
||||
<string name="table_cut">W tabeli ułożono tylko pierwsze wiersze i kolumny. Tekst zawiera wszystko.</string>
|
||||
<string name="table_as_text">Pokaż jako tekst</string>
|
||||
<string name="table_as_table">Pokaż jako tabelę</string>
|
||||
<string name="media_open_in_files">Otwórz w Plikach</string>
|
||||
<string name="media_image">Obraz</string>
|
||||
<string name="media_video">Wideo</string>
|
||||
<string name="media_music">Muzyka</string>
|
||||
<string name="media_model">Model 3D</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>
|
||||
<string name="job_done">Gotowe</string>
|
||||
<string name="job_failed">Nieudane</string>
|
||||
<string name="job_cancelled">Anulowane</string>
|
||||
<string name="job_expired">Wygasło</string>
|
||||
<string name="mcp_title">Serwery MCP</string>
|
||||
<string name="mcp_intro">Serwery, których narzędzia mogą być oferowane w Twoich czatach. Niektóre działają z Twoim własnym kontem u nich: ich narzędzia są oferowane, dopóki trwa zalogowanie.</string>
|
||||
<string name="mcp_none">Na tej instancji nie są oferowane żadne serwery MCP.</string>
|
||||
<string name="mcp_ready">Gotowy</string>
|
||||
<string name="mcp_signed_in">Zalogowano</string>
|
||||
<string name="mcp_signed_out">Nie zalogowano</string>
|
||||
<string name="mcp_needs_signin">Wymaga ponownego zalogowania</string>
|
||||
<string name="mcp_tools">Narzędzia: %1$s</string>
|
||||
<string name="mcp_account">Zalogowano jako %1$s</string>
|
||||
<string name="mcp_until">Zalogowano do %1$s</string>
|
||||
<string name="mcp_shared_note">Ten serwer ma jedno wspólne logowanie, które wykonuje administrator.</string>
|
||||
<string name="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.</string>
|
||||
<string name="mcp_sign_in">Zaloguj się</string>
|
||||
<string name="notebook_empty">Ten notatnik nie ma komórek.</string>
|
||||
<string name="notebook_more">Kolejnych %1$s komórek nie pokazano.</string>
|
||||
<string name="notebook_cell_cut">Ta komórka jest dłuższa, niż tu pokazano.</string>
|
||||
<string name="viewer_page">Strona %1$s z %2$s</string>
|
||||
<string name="play">Odtwórz</string>
|
||||
<string name="pause">Wstrzymaj</string>
|
||||
<string name="files_conflict">Plik zmienił się od otwarcia. Wczytaj go ponownie albo zapisz mimo to.</string>
|
||||
<string name="files_save_anyway">Zapisz mimo to</string>
|
||||
<string name="reload">Przeładuj</string>
|
||||
<string name="discard">Odrzuć</string>
|
||||
<string name="files_unsaved">Odrzucić zmiany w tym pliku?</string>
|
||||
<string name="share_to_files">Zapisz w Plikach</string>
|
||||
<string name="settings">Ustawienia</string>
|
||||
<string name="settings_instances">Instancje</string>
|
||||
<string name="sign_out">Wyloguj się</string>
|
||||
|
||||
@@ -51,6 +51,11 @@
|
||||
<string name="continue_reply">Pokračovať</string>
|
||||
<string name="older">Staršie správy</string>
|
||||
<string name="queued">Čaká na odoslanie</string>
|
||||
<string name="fate_unknown">Nie je známe, či sa táto správa dostala do počítača. Odošlite ju znova alebo ju zahoďte.</string>
|
||||
<string name="fate_carried">Počítač túto správu má a prevezme ju pri svojom ďalšom ťahu.</string>
|
||||
<string name="send_now">Poslať teraz</string>
|
||||
<string name="discard_message_confirm">Zahodiť túto správu?</string>
|
||||
<string name="reply_unrecorded">Odpoveď na toto nebola zaznamenaná.</string>
|
||||
<string name="thinking">Premýšľa</string>
|
||||
<string name="thought">Premýšľal</string>
|
||||
<string name="output_cut">Výstup je tu skrátený. Celý nájdete na webovej stránke.</string>
|
||||
@@ -348,6 +353,100 @@
|
||||
<string name="files">Súbory</string>
|
||||
<string name="files_all">Všetky súbory</string>
|
||||
<string name="files_empty">Zatiaľ tu nič nie je. Ani hobitia nora.</string>
|
||||
<string name="files_upload">Nahrať</string>
|
||||
<string name="files_new_file">Nový súbor</string>
|
||||
<string name="files_new_file_ask">Ako sa má súbor volať? Aj s príponou, napríklad notes.md.</string>
|
||||
<string name="files_new_folder_ask">Ako sa má priečinok volať?</string>
|
||||
<string name="files_bad_name">Názov nesmie byť prázdny ani obsahovať lomku.</string>
|
||||
<string name="files_taken">Niečo s názvom %1$s tu už je.</string>
|
||||
<string name="rename">Premenovať</string>
|
||||
<string name="files_new_name">Nový názov</string>
|
||||
<string name="files_move">Presunúť</string>
|
||||
<string name="files_copy_to">Kopírovať do…</string>
|
||||
<string name="files_move_here">Presunúť sem</string>
|
||||
<string name="files_copy_here">Kopírovať sem</string>
|
||||
<string name="files_move_which">Do ktorého priečinka presunúť?</string>
|
||||
<string name="files_copy_which">Do ktorého priečinka kopírovať?</string>
|
||||
<string name="files_choose_folder">Vybrať priečinok</string>
|
||||
<string name="files_save_here">Uložiť sem</string>
|
||||
<string name="files_no_folders">Nie sú tu žiadne priečinky.</string>
|
||||
<string name="files_to_trash">Presunúť do koša</string>
|
||||
<string name="files_trash_one">Presunúť „%1$s“ do koša? Odtiaľ sa dá obnoviť.</string>
|
||||
<string name="files_trash_many">Presunúť vybrané (%1$s) do koša? Odtiaľ sa dajú obnoviť.</string>
|
||||
<string name="files_trashed">Presunuté do koša.</string>
|
||||
<string name="files_selected">Vybrané: %1$s</string>
|
||||
<string name="files_select_all">Vybrať všetko</string>
|
||||
<string name="download">Stiahnuť</string>
|
||||
<string name="files_download_zip">Stiahnuť ako zip</string>
|
||||
<string name="files_downloading">Sťahuje sa…</string>
|
||||
<string name="files_downloaded">Stiahnuté.</string>
|
||||
<string name="files_uploading">Nahráva sa %1$s z %2$s…</string>
|
||||
<string name="files_uploaded">Nahrané.</string>
|
||||
<string name="files_open_with">Otvoriť v…</string>
|
||||
<string name="files_no_app">Žiadna aplikácia v tomto telefóne tento druh súboru neotvorí.</string>
|
||||
<string name="trash">Kôš</string>
|
||||
<string name="trash_is_empty">Kôš je prázdny.</string>
|
||||
<string name="trash_empty">Vyprázdniť kôš</string>
|
||||
<string name="trash_empty_confirm">Natrvalo odstrániť všetko v koši? Nedá sa to vrátiť späť.</string>
|
||||
<string name="trash_remove">Odstrániť natrvalo</string>
|
||||
<string name="trash_remove_confirm">Natrvalo odstrániť „%1$s“? Nedá sa to vrátiť späť.</string>
|
||||
<string name="restore">Obnoviť</string>
|
||||
<string name="versions">Verzie</string>
|
||||
<string name="version_restore">Obnoviť túto verziu</string>
|
||||
<string name="version_restore_confirm">Urobiť z tejto verzie aktuálnu? Súčasná zostane v zozname.</string>
|
||||
<string name="version_current">Aktuálna</string>
|
||||
<string name="files_type">Typ</string>
|
||||
<string name="files_size">Veľkosť</string>
|
||||
<string name="files_no_viewer">Pre tento druh súboru nie je prehliadač.</string>
|
||||
<string name="files_not_shown">Tento súbor sa tu nepodarilo zobraziť. Stále sa dá stiahnuť.</string>
|
||||
<string name="files_svg_source">Toto je zdroj obrázka. Ak chcete vidieť obrázok, otvorte ho v inej aplikácii.</string>
|
||||
<string name="archive_note">Obsah tohto druhu archívu sa tu nedá vypísať.</string>
|
||||
<string name="archive_entries">Položiek: %1$s. Nič sa tu nerozbaľuje.</string>
|
||||
<string name="archive_cut">Vypísaných je len prvých %1$s položiek.</string>
|
||||
<string name="archive_unreadable">Tento archív sa nepodarilo prečítať.</string>
|
||||
<string name="files_waiting">Čaká sa, kým bude aplikácia otvorená a telefón odomknutý.</string>
|
||||
<string name="share_refused">Niečo zo zdieľaného sa odtiaľto nedá odoslať a bolo vynechané.</string>
|
||||
<string name="media_in_trash">Tento súbor je v koši.</string>
|
||||
<string name="table_cut">Do tabuľky sú rozložené len prvé riadky a stĺpce. Text obsahuje všetko.</string>
|
||||
<string name="table_as_text">Zobraziť ako text</string>
|
||||
<string name="table_as_table">Zobraziť ako tabuľku</string>
|
||||
<string name="media_open_in_files">Otvoriť v Súboroch</string>
|
||||
<string name="media_image">Obrázok</string>
|
||||
<string name="media_video">Video</string>
|
||||
<string name="media_music">Hudba</string>
|
||||
<string name="media_model">3D model</string>
|
||||
<string name="media_gone">Tento súbor už neexistuje.</string>
|
||||
<string name="job_queued">Vo fronte</string>
|
||||
<string name="job_running">Beží</string>
|
||||
<string name="job_done">Hotovo</string>
|
||||
<string name="job_failed">Zlyhalo</string>
|
||||
<string name="job_cancelled">Zrušené</string>
|
||||
<string name="job_expired">Vypršalo</string>
|
||||
<string name="mcp_title">Servery MCP</string>
|
||||
<string name="mcp_intro">Servery, ktorých nástroje môžu byť ponúknuté vo vašich chatoch. Niektoré sa používajú s vaším vlastným účtom u nich: ich nástroje sú ponúkané, kým ste prihlásení.</string>
|
||||
<string name="mcp_none">Na tejto inštancii vám nie sú ponúkané žiadne servery MCP.</string>
|
||||
<string name="mcp_ready">Pripravené</string>
|
||||
<string name="mcp_signed_in">Prihlásené</string>
|
||||
<string name="mcp_signed_out">Neprihlásené</string>
|
||||
<string name="mcp_needs_signin">Je potrebné nové prihlásenie</string>
|
||||
<string name="mcp_tools">Nástroje: %1$s</string>
|
||||
<string name="mcp_account">Prihlásené ako %1$s</string>
|
||||
<string name="mcp_until">Prihlásené do %1$s</string>
|
||||
<string name="mcp_shared_note">Tento server má jedno spoločné prihlásenie, ktoré robí správca.</string>
|
||||
<string name="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.</string>
|
||||
<string name="mcp_sign_in">Prihlásiť sa</string>
|
||||
<string name="notebook_empty">Tento zápisník nemá žiadne bunky.</string>
|
||||
<string name="notebook_more">Ďalších %1$s buniek sa nezobrazuje.</string>
|
||||
<string name="notebook_cell_cut">Táto bunka je dlhšia, než sa tu zobrazuje.</string>
|
||||
<string name="viewer_page">Strana %1$s z %2$s</string>
|
||||
<string name="play">Prehrať</string>
|
||||
<string name="pause">Pozastaviť</string>
|
||||
<string name="files_conflict">Súbor sa od otvorenia zmenil. Načítajte ho znova alebo ho napriek tomu uložte.</string>
|
||||
<string name="files_save_anyway">Napriek tomu uložiť</string>
|
||||
<string name="reload">Znova načítať</string>
|
||||
<string name="discard">Zahodiť</string>
|
||||
<string name="files_unsaved">Zahodiť zmeny v tomto súbore?</string>
|
||||
<string name="share_to_files">Uložiť do Súborov</string>
|
||||
<string name="settings">Nastavenia</string>
|
||||
<string name="settings_instances">Inštancie</string>
|
||||
<string name="sign_out">Odhlásiť sa</string>
|
||||
|
||||
@@ -52,6 +52,11 @@
|
||||
<string name="continue_reply">Continue</string>
|
||||
<string name="older">Earlier messages</string>
|
||||
<string name="queued">Waiting to be sent</string>
|
||||
<string name="fate_unknown">It is not known whether this reached the computer. Send it again, or discard it.</string>
|
||||
<string name="fate_carried">The computer has this message and takes it in with its next turn.</string>
|
||||
<string name="send_now">Send now</string>
|
||||
<string name="discard_message_confirm">Discard this message?</string>
|
||||
<string name="reply_unrecorded">The reply to this was not recorded.</string>
|
||||
<string name="thinking">Thinking</string>
|
||||
<string name="thought">Thought</string>
|
||||
<string name="output_cut">Output shortened here. The whole of it is on the web page.</string>
|
||||
@@ -350,6 +355,100 @@
|
||||
<string name="files">Files</string>
|
||||
<string name="files_all">All files</string>
|
||||
<string name="files_empty">Nothing here yet. Not even a hobbit hole.</string>
|
||||
<string name="files_upload">Upload</string>
|
||||
<string name="files_new_file">New file</string>
|
||||
<string name="files_new_file_ask">What should the file be called? With its extension, such as notes.md.</string>
|
||||
<string name="files_new_folder_ask">What should the folder be called?</string>
|
||||
<string name="files_bad_name">A name cannot be empty or hold a slash.</string>
|
||||
<string name="files_taken">There is already something called %1$s here.</string>
|
||||
<string name="rename">Rename</string>
|
||||
<string name="files_new_name">New name</string>
|
||||
<string name="files_move">Move</string>
|
||||
<string name="files_copy_to">Copy to…</string>
|
||||
<string name="files_move_here">Move here</string>
|
||||
<string name="files_copy_here">Copy here</string>
|
||||
<string name="files_move_which">Move to which folder?</string>
|
||||
<string name="files_copy_which">Copy to which folder?</string>
|
||||
<string name="files_choose_folder">Choose a folder</string>
|
||||
<string name="files_save_here">Save here</string>
|
||||
<string name="files_no_folders">No directories here.</string>
|
||||
<string name="files_to_trash">Move to the trash</string>
|
||||
<string name="files_trash_one">Move “%1$s” to the trash? It can be restored from there.</string>
|
||||
<string name="files_trash_many">Move the %1$s selected to the trash? They can be restored from there.</string>
|
||||
<string name="files_trashed">Moved to the trash.</string>
|
||||
<string name="files_selected">%1$s selected</string>
|
||||
<string name="files_select_all">Select all</string>
|
||||
<string name="download">Download</string>
|
||||
<string name="files_download_zip">Download as a zip</string>
|
||||
<string name="files_downloading">Downloading…</string>
|
||||
<string name="files_downloaded">Downloaded.</string>
|
||||
<string name="files_uploading">Uploading %1$s of %2$s…</string>
|
||||
<string name="files_uploaded">Uploaded.</string>
|
||||
<string name="files_open_with">Open with…</string>
|
||||
<string name="files_no_app">No app on this phone opens this kind of file.</string>
|
||||
<string name="trash">Trash</string>
|
||||
<string name="trash_is_empty">The trash is empty.</string>
|
||||
<string name="trash_empty">Empty the trash</string>
|
||||
<string name="trash_empty_confirm">Remove everything in the trash for good? This cannot be undone.</string>
|
||||
<string name="trash_remove">Remove for good</string>
|
||||
<string name="trash_remove_confirm">Remove “%1$s” for good? This cannot be undone.</string>
|
||||
<string name="restore">Restore</string>
|
||||
<string name="versions">Versions</string>
|
||||
<string name="version_restore">Restore this version</string>
|
||||
<string name="version_restore_confirm">Make this version the current one? The current one stays in the list.</string>
|
||||
<string name="version_current">Current</string>
|
||||
<string name="files_type">Type</string>
|
||||
<string name="files_size">Size</string>
|
||||
<string name="files_no_viewer">There is no viewer for this kind of file.</string>
|
||||
<string name="files_not_shown">This file could not be shown here. It can still be downloaded.</string>
|
||||
<string name="files_svg_source">This is the picture\'s source. Open it with another app to see the picture.</string>
|
||||
<string name="archive_note">What is inside this kind of archive cannot be listed here.</string>
|
||||
<string name="archive_entries">%1$s entries. Nothing is unpacked here.</string>
|
||||
<string name="archive_cut">Only the first %1$s entries are listed.</string>
|
||||
<string name="archive_unreadable">This archive could not be read.</string>
|
||||
<string name="files_waiting">Waiting until the app is open and the phone is unlocked.</string>
|
||||
<string name="share_refused">Something that was shared cannot be sent from here and was left out.</string>
|
||||
<string name="media_in_trash">That file is in the trash.</string>
|
||||
<string name="table_cut">Only the first rows and columns are laid out. The text has all of it.</string>
|
||||
<string name="table_as_text">Show as text</string>
|
||||
<string name="table_as_table">Show as a table</string>
|
||||
<string name="media_open_in_files">Open in Files</string>
|
||||
<string name="media_image">Image</string>
|
||||
<string name="media_video">Video</string>
|
||||
<string name="media_music">Music</string>
|
||||
<string name="media_model">3D model</string>
|
||||
<string name="media_gone">That file no longer exists.</string>
|
||||
<string name="job_queued">Queued</string>
|
||||
<string name="job_running">Running</string>
|
||||
<string name="job_done">Done</string>
|
||||
<string name="job_failed">Failed</string>
|
||||
<string name="job_cancelled">Cancelled</string>
|
||||
<string name="job_expired">Expired</string>
|
||||
<string name="mcp_title">MCP servers</string>
|
||||
<string name="mcp_intro">The servers whose tools your chats may be offered. Some are used with an account of your own there: their tools are offered while you are signed in.</string>
|
||||
<string name="mcp_none">No MCP servers are offered to you on this instance.</string>
|
||||
<string name="mcp_ready">Ready</string>
|
||||
<string name="mcp_signed_in">Signed in</string>
|
||||
<string name="mcp_signed_out">Not signed in</string>
|
||||
<string name="mcp_needs_signin">Needs a new sign-in</string>
|
||||
<string name="mcp_tools">Tools: %1$s</string>
|
||||
<string name="mcp_account">Signed in as %1$s</string>
|
||||
<string name="mcp_until">Signed in until %1$s</string>
|
||||
<string name="mcp_shared_note">This server has one shared sign-in, which an administrator makes.</string>
|
||||
<string name="mcp_browser_note">Signing in happens in the browser, on the instance itself. If the browser is not signed in to the instance, it asks for that first. Come back here afterwards.</string>
|
||||
<string name="mcp_sign_in">Sign in</string>
|
||||
<string name="notebook_empty">This notebook has no cells.</string>
|
||||
<string name="notebook_more">%1$s more cells are not shown.</string>
|
||||
<string name="notebook_cell_cut">This cell is longer than is shown here.</string>
|
||||
<string name="viewer_page">Page %1$s of %2$s</string>
|
||||
<string name="play">Play</string>
|
||||
<string name="pause">Pause</string>
|
||||
<string name="files_conflict">This file changed since you opened it. Reload it, or save anyway.</string>
|
||||
<string name="files_save_anyway">Save anyway</string>
|
||||
<string name="reload">Reload</string>
|
||||
<string name="discard">Discard</string>
|
||||
<string name="files_unsaved">Discard your changes to this file?</string>
|
||||
<string name="share_to_files">Save to Files</string>
|
||||
<string name="settings">Settings</string>
|
||||
<string name="settings_instances">Instances</string>
|
||||
<string name="sign_out">Sign out</string>
|
||||
|
||||
@@ -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.15 (shire). Do not edit. -->
|
||||
<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.18 (shire). Do not edit. -->
|
||||
<resources>
|
||||
<color name="token_bg">#FFF1EAD6</color>
|
||||
<color name="token_surface">#FFF8F3E5</color>
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- The one folder the app shares with another app: the cache folder a photo for the composer
|
||||
is taken into. The camera app may write the one file it was given, and nothing else. -->
|
||||
<!-- The two folders of the private cache another app may be handed one file of, and nothing
|
||||
else: `camera/`, the one file a photo for the composer is taken into (the camera app may
|
||||
write it); `shared/`, the copy of one of the account's files that Open with or Share hands
|
||||
over, read-only, for that one grant (ui/files/Transfers.kt deletes them). -->
|
||||
<paths>
|
||||
<cache-path name="camera" path="camera/" />
|
||||
<cache-path name="shared" path="shared/" />
|
||||
</paths>
|
||||
@@ -137,13 +137,14 @@ class ClientTest {
|
||||
val api = client()
|
||||
val declared = "\"client\":[\"phone_actions\"]"
|
||||
val answer = """{"chat":{"id":"c1"}}"""
|
||||
repeat(6) { server.enqueue(MockResponse().setResponseCode(201).setBody(answer)) }
|
||||
repeat(7) { server.enqueue(MockResponse().setResponseCode(201).setBody(answer)) }
|
||||
api.createChat("Hello")
|
||||
api.sendMessage("c1", "And then?")
|
||||
api.edit("c1", "m1", "Hello again")
|
||||
api.regenerate("c1", "m2")
|
||||
api.continueChat("c1")
|
||||
api.executePlan("c1")
|
||||
api.sendWaiting("c1", "m3")
|
||||
val paths = listOf(
|
||||
"/api/v2/chats",
|
||||
"/api/v2/chats/c1/messages",
|
||||
@@ -151,6 +152,7 @@ class ClientTest {
|
||||
"/api/v2/chats/c1/messages/m2/regenerate",
|
||||
"/api/v2/chats/c1/continue",
|
||||
"/api/v2/chats/c1/plan/execute",
|
||||
"/api/v2/chats/c1/messages/m3/send",
|
||||
)
|
||||
for (path in paths) {
|
||||
val request = server.takeRequest()
|
||||
|
||||
@@ -139,7 +139,7 @@ class ContractTest {
|
||||
val listing = read("files_listing", FileListing.serializer())
|
||||
assertEquals("/home/frodo", listing.path)
|
||||
assertEquals("/home", listing.parent)
|
||||
assertEquals(listOf("recipes", "lembas.md"), listing.entries.map { it.name })
|
||||
assertEquals(listOf("recipes", "lembas.md", "map.png"), listing.entries.map { it.name })
|
||||
assertTrue(listing.entries[0].isFolder)
|
||||
val file = listing.entries[1]
|
||||
assertFalse(file.isFolder)
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import eu.llembas.android.api.BatchAnswer
|
||||
import eu.llembas.android.api.FileContent
|
||||
import eu.llembas.android.api.FileEntry
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.FileListing
|
||||
import eu.llembas.android.api.FileVersions
|
||||
import eu.llembas.android.api.FileView
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.TrashList
|
||||
import eu.llembas.android.api.parseNotebook
|
||||
import eu.llembas.android.api.parseTable
|
||||
import eu.llembas.android.api.sampleFor
|
||||
import eu.llembas.android.api.tableDelimiter
|
||||
import eu.llembas.android.share.sharedNoteName
|
||||
import eu.llembas.android.ui.files.FilesState
|
||||
import eu.llembas.android.ui.files.TransferViewModel
|
||||
import eu.llembas.android.ui.files.asZip
|
||||
import eu.llembas.android.ui.files.outcome
|
||||
import eu.llembas.android.ui.viewer.clampPan
|
||||
import eu.llembas.android.ui.viewer.playTime
|
||||
import kotlinx.serialization.KSerializer
|
||||
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
|
||||
import java.time.LocalDateTime
|
||||
|
||||
/** What the file manager decides without a phone: the viewer for a kind, a table, a notebook, what is chosen, what a batch said. */
|
||||
class FileLogicTest {
|
||||
private fun <T> read(name: String, serializer: KSerializer<T>): T = LembasJson.decodeFromString(
|
||||
serializer,
|
||||
requireNotNull(javaClass.classLoader!!.getResource("$name.json")) {
|
||||
"contract/$name.json is missing"
|
||||
}.readText(),
|
||||
)
|
||||
|
||||
@Test
|
||||
fun thePinnedFilesContract() {
|
||||
val listing = read("files_listing", FileListing.serializer())
|
||||
assertEquals(listOf(null, "markdown", "image"), listing.entries.map { it.fileKind })
|
||||
assertNull(listing.copied)
|
||||
val copied = read("files_copied", FileListing.serializer())
|
||||
assertEquals("lembas (2).md", copied.copied!!.name)
|
||||
assertEquals("/home/frodo/lembas (2).md", copied.copied!!.path)
|
||||
|
||||
val file = read("file_content", FileContent.serializer())
|
||||
assertEquals("markdown", file.fileKind)
|
||||
assertEquals(true, file.writable)
|
||||
assertEquals("ab".repeat(32), file.sha)
|
||||
val picture = read("file_content_withheld", FileContent.serializer())
|
||||
assertEquals("image", picture.fileKind)
|
||||
assertEquals(false, picture.writable)
|
||||
|
||||
val trash = read("files_trash", TrashList.serializer())
|
||||
assertEquals("node5", trash.items.single().id)
|
||||
assertEquals("/home/frodo/old.md", trash.items.single().path)
|
||||
assertEquals(12L, trash.items.single().size)
|
||||
assertEquals("/home/frodo/old.md", read("files_restored", TrashList.serializer()).restored)
|
||||
assertEquals(1, read("files_trash_emptied", TrashList.serializer()).removed)
|
||||
|
||||
val versions = read("file_versions", FileVersions.serializer())
|
||||
assertEquals(listOf("ver2", "ver1"), versions.versions.map { it.id })
|
||||
assertTrue(versions.versions[0].current)
|
||||
assertFalse(versions.versions[1].current)
|
||||
assertEquals("Frodo", versions.versions[1].by)
|
||||
assertNull(versions.versions[1].chatId)
|
||||
|
||||
// A batch is answered path by path: one moved, one refused in the server's own sentence.
|
||||
val batch = read("files_batch", BatchAnswer.serializer())
|
||||
assertEquals(1, batch.done)
|
||||
assertEquals(1, batch.failed)
|
||||
assertEquals("/home/frodo/recipes/lembas.md", batch.results[0].to)
|
||||
val said = outcome(batch)
|
||||
assertEquals(1, said.done)
|
||||
assertEquals("Read-only: /home/frodo/map.png can be read in this session but not changed.", said.said)
|
||||
assertNull(outcome(batch.copy(failed = 0)).said)
|
||||
// Without a sentence, at least which one.
|
||||
assertEquals("map.png", outcome(batch.copy(results = batch.results.map { it.copy(error = null) })).said)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aKindChoosesItsViewer() {
|
||||
for (kind in listOf("markdown", "code", "text", "html", "svg")) assertEquals(kind, FileView.Text, FileKinds.viewer(kind))
|
||||
assertEquals(FileView.Image, FileKinds.viewer("image"))
|
||||
assertEquals(FileView.Pdf, FileKinds.viewer("pdf"))
|
||||
assertEquals(FileView.Audio, FileKinds.viewer("audio"))
|
||||
assertEquals(FileView.Video, FileKinds.viewer("video"))
|
||||
assertEquals(FileView.Table, FileKinds.viewer("table"))
|
||||
assertEquals(FileView.Notebook, FileKinds.viewer("notebook"))
|
||||
for (kind in listOf("archive", "model3d", "binary", "something-new")) assertEquals(kind, FileView.Details, FileKinds.viewer(kind))
|
||||
// A server that does not say the kind is read as before: as text.
|
||||
assertEquals(FileView.Text, FileKinds.viewer(null))
|
||||
|
||||
// Editing: a text kind (a table too) the person may change, and nothing withheld or unsaid.
|
||||
assertTrue(FileKinds.editable("markdown", writable = true, withheld = false))
|
||||
assertTrue(FileKinds.editable("svg", writable = true, withheld = false))
|
||||
assertTrue(FileKinds.editable("table", writable = true, withheld = false))
|
||||
assertFalse(FileKinds.editable("markdown", writable = false, withheld = false))
|
||||
assertFalse(FileKinds.editable("markdown", writable = null, withheld = false))
|
||||
assertFalse(FileKinds.editable("markdown", writable = true, withheld = true))
|
||||
assertFalse(FileKinds.editable("notebook", writable = true, withheld = false))
|
||||
assertFalse(FileKinds.editable("image", writable = true, withheld = false))
|
||||
assertFalse(FileKinds.editable(null, writable = true, withheld = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun namesAndPaths() {
|
||||
assertTrue(FileKinds.badName(""))
|
||||
assertTrue(FileKinds.badName(" "))
|
||||
assertTrue(FileKinds.badName("a/b"))
|
||||
assertTrue(FileKinds.badName(".."))
|
||||
assertFalse(FileKinds.badName("notes.md"))
|
||||
assertEquals("/home/frodo/notes.md", FileKinds.child("/home/frodo/", " notes.md "))
|
||||
assertEquals("/notes.md", FileKinds.child("/", "notes.md"))
|
||||
assertEquals("/home/frodo", FileKinds.parent("/home/frodo/notes.md"))
|
||||
assertEquals("/", FileKinds.parent("/home"))
|
||||
assertEquals("notes.md", FileKinds.name("/home/frodo/notes.md"))
|
||||
assertEquals("recipes", FileKinds.name("/home/frodo/recipes/"))
|
||||
// What another app is told a file is called holds no way out of its folder.
|
||||
assertEquals("_.._etc_passwd", FileKinds.safeName("../../etc/passwd"))
|
||||
assertEquals("file", FileKinds.safeName(".."))
|
||||
assertEquals("file", FileKinds.safeName(" "))
|
||||
assertEquals("a_b", FileKinds.safeName("a\\b"))
|
||||
assertEquals("map.png", FileKinds.safeName("map.png"))
|
||||
|
||||
assertFalse(asZip(listOf(FileEntry(name = "a.md", path = "/h/a.md"))))
|
||||
assertTrue(asZip(listOf(FileEntry(name = "r", path = "/h/r", kind = "dir"))))
|
||||
assertTrue(asZip(listOf(FileEntry(name = "a.md", path = "/h/a.md"), FileEntry(name = "b.md", path = "/h/b.md"))))
|
||||
assertEquals("recipes.zip", TransferViewModel.zipName(listOf("/home/frodo/recipes")))
|
||||
assertEquals("frodo.zip", TransferViewModel.zipName(listOf("/home/frodo/a.md", "/home/frodo/b.md")))
|
||||
assertEquals("files.zip", TransferViewModel.zipName(emptyList()))
|
||||
assertEquals("shared-20260102-030405.txt", sharedNoteName(LocalDateTime.of(2026, 1, 2, 3, 4, 5)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whatIsChosenInADirectory() {
|
||||
val listing = read("files_listing", FileListing.serializer())
|
||||
var state = FilesState(path = "/home/frodo").listed(listing)
|
||||
assertFalse(state.selecting)
|
||||
state = state.toggled("/home/frodo/lembas.md").toggled("/home/frodo/map.png")
|
||||
assertTrue(state.selecting)
|
||||
assertEquals(listOf("lembas.md", "map.png"), state.chosen.map { it.name })
|
||||
assertEquals(listOf("map.png"), state.toggled("/home/frodo/lembas.md").chosen.map { it.name })
|
||||
assertEquals(3, state.allSelected().selected.size)
|
||||
// The same directory read again keeps what is still there; another directory keeps nothing.
|
||||
val without = listing.copy(entries = listing.entries.filter { it.name != "map.png" })
|
||||
assertEquals(setOf("/home/frodo/lembas.md"), state.listed(without).selected)
|
||||
assertTrue(state.listed(listing.copy(path = "/home/frodo/recipes")).selected.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aTableIsCutIntoCells() {
|
||||
val table = parseTable("name,what\r\n\"Baggins, Frodo\",\"says \"\"hello\"\"\"\nSam,\"two\nlines\"\n\nlast,row", ',')
|
||||
assertEquals(
|
||||
listOf(listOf("name", "what"), listOf("Baggins, Frodo", "says \"hello\""), listOf("Sam", "two\nlines"), listOf("last", "row")),
|
||||
table.rows,
|
||||
)
|
||||
assertEquals(2, table.columns)
|
||||
assertFalse(table.cut)
|
||||
// Tabs, a ragged row, and a quote inside a bare cell left as it is.
|
||||
val tabs = parseTable("a\tb\tc\n1\t2\n5\" pipe\tx\ty\n", '\t')
|
||||
assertEquals(listOf(listOf("a", "b", "c"), listOf("1", "2"), listOf("5\" pipe", "x", "y")), tabs.rows)
|
||||
assertEquals(3, tabs.columns)
|
||||
// Caps: rows, columns and a cell's length; what was left out is said.
|
||||
val many = parseTable((1..10).joinToString("\n") { "$it,x,y,z" }, ',', maxRows = 3, maxColumns = 2, maxCell = 1)
|
||||
assertEquals(listOf(listOf("1", "x"), listOf("2", "x"), listOf("3", "x")), many.rows)
|
||||
assertTrue(many.cut)
|
||||
assertEquals("a", parseTable("abcdef,2", ',', maxCell = 1).rows[0][0])
|
||||
// Only the beginning of a long file: its last, half line is not shown as a row.
|
||||
val head = parseTable("a,b\n1,2\n3,", ',', partial = true)
|
||||
assertEquals(listOf(listOf("a", "b"), listOf("1", "2")), head.rows)
|
||||
assertTrue(head.cut)
|
||||
assertTrue(parseTable("", ',').rows.isEmpty())
|
||||
|
||||
assertEquals('\t', tableDelimiter("list.tsv", "a,b"))
|
||||
assertEquals('\t', tableDelimiter("list.csv", "a\tb\n1\t2"))
|
||||
assertEquals(';', tableDelimiter("list.csv", "a;b\n1;2"))
|
||||
assertEquals(',', tableDelimiter("list.csv", "a,b;c"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aNotebookIsItsCellsAsText() {
|
||||
val text = """
|
||||
{"metadata": {"kernelspec": {"language": "python"}}, "cells": [
|
||||
{"cell_type": "markdown", "source": ["# Waybread\n", "Notes."]},
|
||||
{"cell_type": "code", "execution_count": 3, "source": "print('hi')",
|
||||
"outputs": [
|
||||
{"output_type": "stream", "text": ["hi\n"]},
|
||||
{"output_type": "execute_result", "data": {"text/plain": "42", "text/html": "<b onclick=x>42</b>", "image/png": "AAAA"}},
|
||||
{"output_type": "error", "ename": "ValueError", "evalue": "no"}
|
||||
]},
|
||||
{"cell_type": "code", "execution_count": null, "source": []}
|
||||
]}
|
||||
""".trimIndent()
|
||||
val notebook = parseNotebook(text)
|
||||
assertNotNull(notebook)
|
||||
assertEquals("python", notebook!!.language)
|
||||
assertEquals(listOf("markdown", "code", "code"), notebook.cells.map { it.kind })
|
||||
assertEquals("# Waybread\nNotes.", notebook.cells[0].source)
|
||||
assertEquals(3, notebook.cells[1].count)
|
||||
// Only what is plain text of an output is kept: no HTML, no picture.
|
||||
assertEquals("hi\n42\nValueError: no", notebook.cells[1].output)
|
||||
assertFalse(notebook.cells[1].output.contains("onclick"))
|
||||
assertNull(notebook.cells[2].count)
|
||||
assertEquals("", notebook.cells[2].source)
|
||||
assertEquals(0, notebook.more)
|
||||
|
||||
val long = parseNotebook(text, maxCells = 1, maxChars = 4)!!
|
||||
assertEquals(2, long.more)
|
||||
assertEquals("# Wa", long.cells.single().source)
|
||||
assertTrue(long.cells.single().cut)
|
||||
// Not a notebook: nothing to draw as one.
|
||||
assertNull(parseNotebook("[1, 2]"))
|
||||
assertNull(parseNotebook("{\"cells\": 3}"))
|
||||
assertNull(parseNotebook("not json"))
|
||||
assertTrue(parseNotebook("{\"cells\": []}")!!.cells.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPictureIsDecodedSmallWhateverItClaims() {
|
||||
assertEquals(1, sampleFor(1920, 1080))
|
||||
assertEquals(2, sampleFor(4000, 3000))
|
||||
// 30 000 px square: at most a few megapixels are ever decoded.
|
||||
val sample = sampleFor(30_000, 30_000)
|
||||
assertTrue((30_000L / sample) * (30_000L / sample) <= 8_000_000)
|
||||
assertTrue(30_000 / sample <= 2560)
|
||||
// A ribbon: its long edge decides.
|
||||
assertTrue(100_000 / sampleFor(100_000, 10) <= 2560)
|
||||
assertEquals(1, sampleFor(0, 0))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aZoomedPictureStaysInItsFrameAndAPlayerSaysItsTime() {
|
||||
val size = IntSize(1000, 500)
|
||||
// Not zoomed: it does not move. Zoomed twice: half its size either way, and no further.
|
||||
val still = clampPan(Offset(300f, -80f), 1f, size)
|
||||
assertEquals(0f, still.x, 0f)
|
||||
assertEquals(0f, still.y, 0f)
|
||||
val right = clampPan(Offset(900f, -80f), 2f, size)
|
||||
assertEquals(500f, right.x, 0f)
|
||||
assertEquals(-80f, right.y, 0f)
|
||||
val corner = clampPan(Offset(-900f, 400f), 2f, size)
|
||||
assertEquals(-500f, corner.x, 0f)
|
||||
assertEquals(250f, corner.y, 0f)
|
||||
|
||||
assertEquals("0:00", playTime(0))
|
||||
assertEquals("0:00", playTime(-5))
|
||||
assertEquals("1:05", playTime(65_400))
|
||||
assertEquals("1:00:07", playTime(3_607_000))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.RangeReader
|
||||
import eu.llembas.android.api.SaveConflict
|
||||
import eu.llembas.android.ui.files.StreamBody
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import okio.Buffer
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
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.ByteArrayInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
/** The file manager's calls, against a server that answers as the pinned contract says. */
|
||||
class FilesClientTest {
|
||||
private lateinit var server: MockWebServer
|
||||
|
||||
@Before
|
||||
fun up() {
|
||||
server = MockWebServer().apply { start() }
|
||||
}
|
||||
|
||||
@After
|
||||
fun down() = server.shutdown()
|
||||
|
||||
private fun client() = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test")
|
||||
|
||||
private fun contract(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) {
|
||||
"contract/$name.json is missing"
|
||||
}.readText()
|
||||
|
||||
@Test
|
||||
fun anUploadIsStreamedIntoItsFolderAndSaysHowFarItIs() = runTest {
|
||||
server.enqueue(MockResponse().setResponseCode(201).setBody(contract("files_listing")))
|
||||
val bytes = ByteArray(300_000) { (it % 251).toByte() }
|
||||
val heard = mutableListOf<Long>()
|
||||
val body = StreamBody("application/octet-stream".toMediaType(), bytes.size.toLong(), { heard += it }) { ByteArrayInputStream(bytes) }
|
||||
val listing = client().uploadFile("/home/frodo", "big.bin", body)
|
||||
assertEquals("/home/frodo", listing.path)
|
||||
val request = server.takeRequest()
|
||||
assertEquals("POST", request.method)
|
||||
assertEquals("/api/v2/files/upload?path=%2Fhome%2Ffrodo", request.path)
|
||||
assertEquals("Bearer lmb_test", request.getHeader("Authorization"))
|
||||
val sent = request.body.readByteArray()
|
||||
val head = String(sent, 0, 400, Charsets.ISO_8859_1)
|
||||
assertTrue(head, head.contains("name=\"files\"; filename=\"big.bin\""))
|
||||
// Every byte went, in pieces, and the last word on progress is the whole file.
|
||||
assertTrue(sent.size > bytes.size)
|
||||
assertTrue(heard.size > 1)
|
||||
assertEquals(bytes.size.toLong(), heard.last())
|
||||
assertTrue(body.isOneShot())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFileOverTheLimitIsRefusedInTheServersSentence() = runTest {
|
||||
val sentence = "big.bin is larger than 50 MB, the most that can be uploaded here."
|
||||
server.enqueue(MockResponse().setResponseCode(413).setBody("""{"detail":"$sentence"}"""))
|
||||
try {
|
||||
client().uploadFile("/home/frodo", "big.bin", StreamBody(null, 3, {}) { ByteArrayInputStream(byteArrayOf(1, 2, 3)) })
|
||||
fail("a 413 is a refusal")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals(413, e.status)
|
||||
assertEquals(sentence, e.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aSaveSaysWhatItOpenedAndAConflictWritesNothing() = runTest {
|
||||
val api = client()
|
||||
server.enqueue(MockResponse().setBody(contract("file_content")))
|
||||
val saved = api.saveFile("/home/frodo/lembas.md", "# Lembas\n", base = "abab")
|
||||
assertEquals("markdown", saved.fileKind)
|
||||
assertEquals(true, saved.writable)
|
||||
val first = server.takeRequest()
|
||||
assertEquals("PUT", first.method)
|
||||
assertEquals("/api/v2/files/content", first.path)
|
||||
val said = first.body.readUtf8()
|
||||
assertTrue(said, said.contains("\"base\":\"abab\""))
|
||||
assertTrue(said, said.contains("\"path\":\"/home/frodo/lembas.md\""))
|
||||
assertFalse(said, said.contains("force"))
|
||||
|
||||
// The file changed meanwhile: the server's sentence and what the file holds now.
|
||||
server.enqueue(MockResponse().setResponseCode(409).setBody(contract("file_save_conflict")))
|
||||
try {
|
||||
api.saveFile("/home/frodo/lembas.md", "mine", base = "abab")
|
||||
fail("a conflict is not a save")
|
||||
} catch (e: SaveConflict) {
|
||||
assertEquals("This file changed since you opened it. Reload it, or save anyway.", e.message)
|
||||
assertEquals("ab".repeat(32), e.sha)
|
||||
}
|
||||
server.takeRequest()
|
||||
|
||||
// Save anyway says so; a new file says no base at all.
|
||||
server.enqueue(MockResponse().setBody(contract("file_content")))
|
||||
api.saveFile("/home/frodo/lembas.md", "mine", base = "abab", force = true)
|
||||
assertTrue(server.takeRequest().body.readUtf8().contains("\"force\":true"))
|
||||
server.enqueue(MockResponse().setBody(contract("file_content")))
|
||||
api.saveFile("/home/frodo/new.md", "")
|
||||
assertFalse(server.takeRequest().body.readUtf8().contains("base"))
|
||||
|
||||
// Any other 409 is a refusal like any other.
|
||||
server.enqueue(MockResponse().setResponseCode(409).setBody("""{"detail":"Not now."}"""))
|
||||
try {
|
||||
api.saveFile("/home/frodo/lembas.md", "mine", base = "abab")
|
||||
fail("a refusal")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals("Not now.", e.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aDownloadIsCopiedAsItComesWithTheTokenInItsHeaderOnly() = runTest {
|
||||
val api = client()
|
||||
server.enqueue(MockResponse().setBody("hello world"))
|
||||
val out = ByteArrayOutputStream()
|
||||
var last = 0L to 0L
|
||||
val done = api.download(api.rawFile("/home/frodo/map of the road.png"), out) { now, total -> last = now to total }
|
||||
assertEquals(11L, done)
|
||||
assertEquals("hello world", out.toString("UTF-8"))
|
||||
assertEquals(11L to 11L, last)
|
||||
val request = server.takeRequest()
|
||||
assertEquals("/api/v2/files/raw?path=%2Fhome%2Ffrodo%2Fmap%20of%20the%20road.png", request.path)
|
||||
assertEquals("Bearer lmb_test", request.getHeader("Authorization"))
|
||||
assertFalse(request.requestUrl.toString().contains("lmb_test"))
|
||||
assertNull(request.getHeader("Range"))
|
||||
|
||||
// More than the caller will take is refused before it is copied.
|
||||
server.enqueue(MockResponse().setBody("hello world"))
|
||||
try {
|
||||
api.download(api.rawFile("/home/frodo/map.png"), ByteArrayOutputStream(), most = 4)
|
||||
fail("too much")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals(413, e.status)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPieceOfAFileIsARangeRequest() {
|
||||
val api = client()
|
||||
server.enqueue(MockResponse().setResponseCode(206).setHeader("Content-Range", "bytes 4-7/11").setBody("o wo"))
|
||||
assertEquals("o wo", api.rawBytes("/home/frodo/song.mp3", 4, 7).toString(Charsets.UTF_8))
|
||||
val request = server.takeRequest()
|
||||
assertEquals("bytes=4-7", request.getHeader("Range"))
|
||||
assertEquals("Bearer lmb_test", request.getHeader("Authorization"))
|
||||
assertFalse(request.requestUrl.toString().contains("lmb_test"))
|
||||
|
||||
// A server that ignores the range would hand the wrong bytes: refused, not played.
|
||||
server.enqueue(MockResponse().setBody("hello world"))
|
||||
try {
|
||||
api.rawBytes("/home/frodo/song.mp3", 4, 7)
|
||||
fail("the whole file is not the piece asked for")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals(416, e.status)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPlayerReadsBlockByBlockAndABlockIsFetchedOnce() {
|
||||
val file = ByteArray(10) { it.toByte() }
|
||||
val asked = mutableListOf<Pair<Long, Long>>()
|
||||
val reader = RangeReader(file.size.toLong(), block = 4, keep = 2) { from, to ->
|
||||
asked += from to to
|
||||
file.copyOfRange(from.toInt(), to.toInt() + 1)
|
||||
}
|
||||
val buffer = ByteArray(8)
|
||||
// A read ends at its block's end; the player asks again for the rest.
|
||||
assertEquals(4, reader.read(0, buffer, 0, 8))
|
||||
assertArrayEquals(byteArrayOf(0, 1, 2, 3), buffer.copyOf(4))
|
||||
assertEquals(2, reader.read(2, buffer, 0, 8))
|
||||
assertEquals(listOf(0L to 3L), asked)
|
||||
// The last block is short, and the end is the end.
|
||||
assertEquals(2, reader.read(8, buffer, 3, 5))
|
||||
assertArrayEquals(byteArrayOf(8, 9), buffer.copyOfRange(3, 5))
|
||||
assertEquals(listOf(0L to 3L, 8L to 9L), asked)
|
||||
assertEquals(-1, reader.read(10, buffer, 0, 8))
|
||||
assertEquals(-1, reader.read(-1, buffer, 0, 8))
|
||||
assertEquals(0, reader.read(1, buffer, 0, 0))
|
||||
// A seek back to a block still kept asks nothing; one that fell out is asked for again.
|
||||
assertEquals(1, reader.read(3, buffer, 0, 8))
|
||||
assertEquals(2, asked.size)
|
||||
assertEquals(4, reader.read(4, buffer, 0, 8))
|
||||
assertEquals(4, reader.read(0, buffer, 0, 8))
|
||||
assertEquals(listOf(0L to 3L, 8L to 9L, 4L to 7L), asked)
|
||||
assertEquals(2, reader.read(8, buffer, 0, 8))
|
||||
assertEquals(listOf(0L to 3L, 8L to 9L, 4L to 7L, 8L to 9L), asked)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aBatchTheTrashAndTheVersions() = runTest {
|
||||
val api = client()
|
||||
server.enqueue(MockResponse().setBody(contract("files_batch")))
|
||||
val answer = api.batchFiles("move", listOf("/home/frodo/lembas.md", "/home/frodo/map.png"), "/home/frodo/recipes")
|
||||
assertEquals(1, answer.done)
|
||||
assertEquals(1, answer.failed)
|
||||
val batch = server.takeRequest()
|
||||
assertEquals("/api/v2/files/batch", batch.path)
|
||||
val body = batch.body.readUtf8()
|
||||
assertTrue(body, body.contains("\"op\":\"move\""))
|
||||
assertTrue(body, body.contains("\"paths\":[\"/home/frodo/lembas.md\",\"/home/frodo/map.png\"]"))
|
||||
assertTrue(body, body.contains("\"to\":\"/home/frodo/recipes\""))
|
||||
|
||||
server.enqueue(MockResponse().setBody(contract("files_trash_emptied")))
|
||||
assertEquals(1, api.removeTrashed().removed)
|
||||
val emptied = server.takeRequest()
|
||||
assertEquals("DELETE", emptied.method)
|
||||
assertEquals("/api/v2/files/trash", emptied.path)
|
||||
server.enqueue(MockResponse().setBody(contract("files_trash_emptied")))
|
||||
api.removeTrashed("node5")
|
||||
assertEquals("/api/v2/files/trash?id=node5", server.takeRequest().path)
|
||||
|
||||
server.enqueue(MockResponse().setBody(contract("file_versions")))
|
||||
api.restoreVersion("/home/frodo/lembas.md", "ver1")
|
||||
val restored = server.takeRequest()
|
||||
assertEquals("/api/v2/files/versions/restore", restored.path)
|
||||
assertTrue(restored.body.readUtf8().contains("\"version\":\"ver1\""))
|
||||
|
||||
// A zip is asked for by its paths, in the body: nothing of the account is in the address.
|
||||
val zip = api.zipFiles(listOf("/home/frodo/recipes"))
|
||||
assertEquals("POST", zip.method)
|
||||
assertTrue(zip.url.toString().endsWith("/api/v2/files/zip"))
|
||||
val asked = Buffer().also { zip.body!!.writeTo(it) }.readUtf8()
|
||||
assertEquals("""{"paths":["/home/frodo/recipes"]}""", asked)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileExists
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.McpServerList
|
||||
import eu.llembas.android.api.MediaJob
|
||||
import eu.llembas.android.api.MediaJobList
|
||||
import eu.llembas.android.api.MediaView
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.ModelList
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.api.ToolCall
|
||||
import eu.llembas.android.api.forChat
|
||||
import eu.llembas.android.api.signInAddress
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
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.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Generated media, its jobs, a new file that must be new, what a model is for and the MCP
|
||||
* servers, as the pinned contract has them and as the client asks for them.
|
||||
*/
|
||||
class MediaContractTest {
|
||||
private lateinit var server: MockWebServer
|
||||
|
||||
@Before
|
||||
fun up() {
|
||||
server = MockWebServer().apply { start() }
|
||||
}
|
||||
|
||||
@After
|
||||
fun down() = server.shutdown()
|
||||
|
||||
private fun client() = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test")
|
||||
|
||||
private fun contract(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) {
|
||||
"contract/$name.json is missing"
|
||||
}.readText()
|
||||
|
||||
@Test
|
||||
fun aCallCarriesItsFileOrItsJob() {
|
||||
val calls = LembasJson.parseToJsonElement(contract("tool_media")).jsonObject.getValue("calls")
|
||||
val (picture, video) = LembasJson.decodeFromJsonElement(ListSerializer(ToolCall.serializer()), calls)
|
||||
// A picture is an attachment as before, and a file of the tree as well.
|
||||
assertEquals("att1", picture.image!!.id)
|
||||
val media = picture.media!!
|
||||
assertEquals(MediaView.Picture, media.view)
|
||||
assertEquals("node8", media.nodeId)
|
||||
assertEquals("/home/frodo/Generated/image-20260102-030405.png", media.path)
|
||||
assertEquals("image-20260102-030405.png", media.title)
|
||||
assertEquals(180_000L, media.size)
|
||||
assertEquals(1024, media.width)
|
||||
assertEquals(0.0, media.seconds, 0.0)
|
||||
assertNull(picture.mediaJob)
|
||||
// A video is a job: the call says which, and that it was running when it returned.
|
||||
assertNull(video.media)
|
||||
assertNull(video.image)
|
||||
val job = MediaJob.of(video.mediaJob!!)
|
||||
assertEquals("mjob1", job.id)
|
||||
assertEquals("video", job.kind)
|
||||
assertTrue(job.underWay)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theCardIsChosenByWhatWasAskedFor() {
|
||||
fun view(kind: String) = LembasJson.decodeFromString(eu.llembas.android.api.GeneratedMedia.serializer(), """{"kind":"$kind"}""").view
|
||||
assertEquals(MediaView.Picture, view("image"))
|
||||
assertEquals(MediaView.Picture, view("image_edit"))
|
||||
assertEquals(MediaView.Video, view("video"))
|
||||
assertEquals(MediaView.Sound, view("music"))
|
||||
assertEquals(MediaView.Details, view("model3d"))
|
||||
// A kind this app does not know is a file with details, never something played or drawn.
|
||||
assertEquals(MediaView.Details, view("hologram"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aJobUnderWayDoneAndFailed() {
|
||||
val running = LembasJson.decodeFromString(MediaJob.serializer(), contract("media_job"))
|
||||
assertTrue(running.underWay)
|
||||
assertFalse(running.unsuccessful)
|
||||
assertEquals(42.0, running.seconds, 0.0)
|
||||
assertNull(running.result)
|
||||
assertFalse(running.told)
|
||||
|
||||
val done = LembasJson.decodeFromString(MediaJob.serializer(), contract("media_job_done"))
|
||||
assertFalse(done.underWay)
|
||||
assertFalse(done.unsuccessful)
|
||||
assertEquals(MediaView.Video, done.result!!.view)
|
||||
assertEquals("node7", done.result!!.nodeId)
|
||||
assertEquals(5.0, done.result!!.seconds, 0.0)
|
||||
assertEquals(0.1, done.cost!!.amount, 1e-9)
|
||||
assertTrue(done.told)
|
||||
|
||||
val failed = LembasJson.decodeFromString(MediaJob.serializer(), contract("media_job_failed"))
|
||||
assertTrue(failed.unsuccessful)
|
||||
assertEquals("ComfyUI ran out of video memory in KSampler.", failed.error)
|
||||
|
||||
assertEquals(listOf("running", "done", "failed"), LembasJson.decodeFromString(MediaJobList.serializer(), contract("media_jobs")).jobs.map { it.state })
|
||||
// A state this app does not know ends the following unless the server says it is still active.
|
||||
assertFalse(MediaJob(id = "j", state = "paused").underWay)
|
||||
assertTrue(MediaJob(id = "j", state = "paused", active = true).underWay)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theJobsAreAskedForReadAndCancelled() = runTest {
|
||||
val api = client()
|
||||
server.enqueue(MockResponse().setBody(contract("media_jobs")))
|
||||
assertEquals(3, api.mediaJobs("chat1").size)
|
||||
assertEquals("/api/v2/media/jobs?chat_id=chat1", server.takeRequest().path)
|
||||
server.enqueue(MockResponse().setBody(contract("media_jobs")))
|
||||
api.mediaJobs("chat1", active = true)
|
||||
assertEquals("/api/v2/media/jobs?chat_id=chat1&active=true", server.takeRequest().path)
|
||||
|
||||
server.enqueue(MockResponse().setBody(contract("media_job")))
|
||||
assertEquals("mjob1", api.mediaJob("mjob1").id)
|
||||
val read = server.takeRequest()
|
||||
assertEquals("GET", read.method)
|
||||
assertEquals("/api/v2/media/jobs/mjob1", read.path)
|
||||
assertEquals("Bearer lmb_test", read.getHeader("Authorization"))
|
||||
|
||||
server.enqueue(MockResponse().setBody(contract("media_job_failed")))
|
||||
assertEquals("failed", api.cancelMediaJob("mjob3").state)
|
||||
val cancel = server.takeRequest()
|
||||
assertEquals("DELETE", cancel.method)
|
||||
assertEquals("/api/v2/media/jobs/mjob3", cancel.path)
|
||||
|
||||
// Somebody else's job, or one that is gone: the server's sentence.
|
||||
server.enqueue(MockResponse().setResponseCode(404).setBody("""{"detail":"That job no longer exists."}"""))
|
||||
try {
|
||||
api.mediaJob("mjob9")
|
||||
fail("a 404 is no job")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals("That job no longer exists.", e.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun bytesAreAskedForByPathByVersionByNodeAndByAttachment() {
|
||||
val api = client()
|
||||
fun path(what: Raw, inline: Boolean = false) = api.raw(what, inline = inline).url.let { it.encodedPath + "?" + it.encodedQuery }
|
||||
assertEquals("/api/v2/files/raw?path=%2Fhome%2Ffrodo%2Fa.mp4", path(Raw.Path("/home/frodo/a.mp4")))
|
||||
assertEquals("/api/v2/files/raw?path=%2Fhome%2Ffrodo%2Fa.md&version=ver3", path(Raw.Path("/home/frodo/a.md", "ver3")))
|
||||
assertEquals("/api/v2/files/raw?node=node7&inline=1", path(Raw.Node("node7"), inline = true))
|
||||
assertEquals("/api/v2/attachments/att1", api.raw(Raw.Attached("att1")).url.encodedPath)
|
||||
// The token is in the header of each, and in the address of none.
|
||||
for (what in listOf(Raw.Path("/a"), Raw.Node("node7"), Raw.Attached("att1"))) {
|
||||
val request = api.raw(what, range = 0L..9L)
|
||||
assertEquals("Bearer lmb_test", request.header("Authorization"))
|
||||
assertEquals("bytes=0-9", request.header("Range"))
|
||||
assertFalse(request.url.toString().contains("lmb_test"))
|
||||
}
|
||||
// A piece of a file by its id is the same Range request a piece by its path is.
|
||||
server.enqueue(MockResponse().setResponseCode(206).setBody("0123456789"))
|
||||
assertEquals("0123456789", api.rawBytes(Raw.Node("node7"), 10, 19).toString(Charsets.UTF_8))
|
||||
val piece = server.takeRequest()
|
||||
assertEquals("/api/v2/files/raw?node=node7", piece.path)
|
||||
assertEquals("bytes=10-19", piece.getHeader("Range"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aNewFileIsNeverWrittenOverAnother() = runTest {
|
||||
val api = client()
|
||||
server.enqueue(MockResponse().setResponseCode(201).setBody(contract("file_content")))
|
||||
api.saveFile("/home/frodo/new.md", "", create = true)
|
||||
val said = server.takeRequest().body.readUtf8()
|
||||
assertTrue(said, said.contains("\"create\":true"))
|
||||
assertFalse(said, said.contains("base"))
|
||||
|
||||
server.enqueue(MockResponse().setResponseCode(409).setBody(contract("file_create_exists")))
|
||||
try {
|
||||
api.saveFile("/home/frodo/lembas.md", "", create = true)
|
||||
fail("a name that is taken makes no file")
|
||||
} catch (e: FileExists) {
|
||||
assertEquals("There is already something called lembas.md here.", e.message)
|
||||
}
|
||||
server.takeRequest()
|
||||
// A save that is not a new file does not say `create`.
|
||||
server.enqueue(MockResponse().setBody(contract("file_content")))
|
||||
api.saveFile("/home/frodo/lembas.md", "x", base = "abab")
|
||||
assertFalse(server.takeRequest().body.readUtf8().contains("create"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onlyAModelToChatWithIsOffered() = runTest {
|
||||
// The pinned lists say `chat` for every model; a list that named another kind loses it here.
|
||||
assertTrue(LembasJson.decodeFromString(ModelList.serializer(), contract("models")).models.all { it.capability == "chat" && it.forChat })
|
||||
val mixed = """{"models": [
|
||||
{"id": "qwen", "capability": "chat"},
|
||||
{"id": "embedder", "capability": "embedding"},
|
||||
{"id": "painter", "capability": "image"},
|
||||
{"id": "old"},
|
||||
{"id": "novel", "capability": "something-new"}], "subagents_cap": 4}"""
|
||||
val list = LembasJson.decodeFromString(ModelList.serializer(), mixed)
|
||||
assertEquals(listOf("qwen", "old"), list.models.forChat().map { it.id })
|
||||
assertEquals(listOf("qwen", "old"), list.forChat().models.map { it.id })
|
||||
assertEquals(4, list.forChat().subagentsCap)
|
||||
// What the pickers and the assistant's setting are filled from is already narrowed.
|
||||
val api = client()
|
||||
server.enqueue(MockResponse().setBody(mixed))
|
||||
assertEquals(listOf("qwen", "old"), api.models().map(ModelInfo::id))
|
||||
server.enqueue(MockResponse().setBody(mixed))
|
||||
assertEquals(listOf("qwen", "old"), api.agentModelList("dev1").models.map(ModelInfo::id))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theMcpServersAndWhoHasToSignIn() = runTest {
|
||||
val servers = LembasJson.decodeFromString(McpServerList.serializer(), contract("mcp_servers")).servers
|
||||
assertEquals(listOf("Tracker", "Mail", "Notes", "Wiki"), servers.map { it.label })
|
||||
assertEquals(listOf("ready", "signed_in", "signed_out", "needs_signin"), servers.map { it.auth.state })
|
||||
assertEquals(listOf(false, false, true, true), servers.map { it.auth.needsSignIn })
|
||||
assertEquals("frodo@example.org", servers[1].auth.account)
|
||||
assertTrue(servers[1].auth.renews)
|
||||
// One's own sign-in has a page; a shared one has none for a person who is no administrator.
|
||||
assertEquals("https://lembas.example.org/settings/mcp/mcp3/sign-in", servers[2].auth.signinUrl)
|
||||
assertTrue(servers[3].auth.shared)
|
||||
assertNull(servers[3].auth.signinUrl)
|
||||
|
||||
server.enqueue(MockResponse().setBody(contract("mcp_servers")))
|
||||
assertEquals(4, client().mcpServers().size)
|
||||
assertEquals("/api/v2/mcp", server.takeRequest().path)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aSignInOpensAPageOfTheInstanceAndNothingElse() {
|
||||
val base = "https://lembas.example.org"
|
||||
val page = "/settings/mcp/mcp3/sign-in"
|
||||
assertEquals(base + page, signInAddress(base, base + page))
|
||||
assertEquals(base + page, signInAddress(base, page))
|
||||
assertEquals(base + page, signInAddress("$base/", page))
|
||||
// The instance named itself otherwise (another name, another port): the same page, on the instance the app knows.
|
||||
assertEquals(base + page, signInAddress(base, "https://other.example.net$page"))
|
||||
assertEquals("$base$page?x=1", signInAddress(base, "http://lembas.example.org:8080$page?x=1"))
|
||||
assertEquals("http://lembas.example.org:8080$page", signInAddress("http://lembas.example.org:8080", "http://lembas.example.org:8080$page"))
|
||||
// Nothing that is not a page, and never a host hidden in a path or before an @.
|
||||
assertNull(signInAddress(base, null))
|
||||
assertNull(signInAddress(base, " "))
|
||||
assertNull(signInAddress(base, "javascript:alert(1)"))
|
||||
assertNull(signInAddress(base, "intent://settings#Intent;end"))
|
||||
assertEquals("$base/settings", signInAddress(base, "//other.example.net/settings"))
|
||||
assertEquals("$base/settings", signInAddress(base, "https://lembas.example.org@other.example.net/settings"))
|
||||
// The app's token is in none of them: there is no place for one.
|
||||
assertFalse(signInAddress(base, base + page)!!.contains("token"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.MediaJob
|
||||
import eu.llembas.android.api.MediaJobList
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.ToolCall
|
||||
import eu.llembas.android.ui.chat.ChatMedia
|
||||
import eu.llembas.android.ui.chat.ChatState
|
||||
import eu.llembas.android.ui.chat.JobSeen
|
||||
import eu.llembas.android.ui.chat.MediaActions
|
||||
import eu.llembas.android.ui.chat.awaitsTelling
|
||||
import eu.llembas.android.ui.chat.job
|
||||
import eu.llembas.android.ui.chat.jobRefs
|
||||
import eu.llembas.android.ui.chat.jobRefsOf
|
||||
import eu.llembas.android.ui.chat.jobsToRead
|
||||
import eu.llembas.android.ui.chat.withJobs
|
||||
import eu.llembas.android.ui.chat.woke
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/** How a chat follows its long generations: which jobs it reads again, and when a job has woken it. */
|
||||
class MediaJobsTest {
|
||||
private fun contract(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) {
|
||||
"contract/$name.json is missing"
|
||||
}.readText()
|
||||
|
||||
private fun job(name: String) = LembasJson.decodeFromString(MediaJob.serializer(), contract(name))
|
||||
|
||||
/** A reply whose one round of tools is the pinned picture call and the pinned video call. */
|
||||
private val reply: Message
|
||||
get() {
|
||||
val calls = LembasJson.parseToJsonElement(contract("tool_media")).jsonObject.getValue("calls")
|
||||
val read = LembasJson.decodeFromJsonElement(ListSerializer(ToolCall.serializer()), calls)
|
||||
return Message(id = "msg2", role = "assistant", steps = listOf(Step(index = 0, kind = "tools", calls = read)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theJobsACallStartedAreFoundOnceWhereverTheCallIs() {
|
||||
assertEquals(listOf("mjob1"), jobRefsOf(listOf(reply)).map { it.id })
|
||||
// In the reply being written too, a call under another call, and never the same job twice.
|
||||
val nested = ToolCall(name = "agent", children = reply.steps[0].calls)
|
||||
val live = listOf(Step(index = 0, kind = "tools", calls = listOf(nested)))
|
||||
assertEquals(listOf("mjob1"), jobRefsOf(listOf(reply), live).map { it.id })
|
||||
assertEquals(listOf("mjob1"), jobRefsOf(emptyList(), live).map { it.id })
|
||||
assertEquals(listOf("mjob1"), ChatState(live = LiveReply("msg3", steps = live)).jobRefs.map { it.id })
|
||||
assertTrue(jobRefsOf(listOf(Message(id = "m", role = "user", text = "hello"))).isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aJobIsReadAgainUntilItHasEnded() {
|
||||
val state = ChatState(messages = listOf(reply))
|
||||
// Named by a call and never read: the call's own word is from the moment it returned.
|
||||
assertEquals(listOf("mjob1"), state.jobsToRead())
|
||||
val running = state.withJobs(listOf(job("media_job")), at = 1000)
|
||||
assertEquals(listOf("mjob1"), running.jobsToRead())
|
||||
// Ended: left alone, whatever the call still says.
|
||||
val done = running.withJobs(listOf(job("media_job_done").copy(id = "mjob1")), at = 4000)
|
||||
assertTrue(done.jobsToRead().isEmpty())
|
||||
assertEquals("done", done.mediaJobs.getValue("mjob1").job.state)
|
||||
assertEquals(4000L, done.mediaJobs.getValue("mjob1").at)
|
||||
// A job the chat's list has that no call on this page names is followed while it is under way.
|
||||
val listed = ChatState().withJobs(LembasJson.decodeFromString(MediaJobList.serializer(), contract("media_jobs")).jobs, at = 1000)
|
||||
assertEquals(listOf("mjob1"), listed.jobsToRead())
|
||||
assertEquals(setOf("mjob1", "mjob2", "mjob3"), listed.mediaJobs.keys)
|
||||
assertEquals(ChatState(), ChatState().withJobs(emptyList(), at = 1))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aJobThatToldTheChatHasWokenIt() {
|
||||
val running = job("media_job")
|
||||
val ended = job("media_job_done").copy(told = false)
|
||||
val told = job("media_job_done")
|
||||
// The end and the telling may be two reads apart: only the telling says there is a reply to read.
|
||||
assertFalse(woke(running, ended))
|
||||
assertTrue(awaitsTelling(ended))
|
||||
assertTrue(woke(ended, told))
|
||||
assertTrue(woke(running, told))
|
||||
assertFalse(awaitsTelling(told))
|
||||
// Told already at the last read, or first heard of as told: the transcript in hand has it.
|
||||
assertFalse(woke(told, told))
|
||||
assertFalse(woke(null, told))
|
||||
// A failure wakes the chat too; a job the person stopped wakes nobody and is not waited for.
|
||||
assertTrue(woke(running, job("media_job_failed")))
|
||||
assertFalse(awaitsTelling(running))
|
||||
assertFalse(awaitsTelling(MediaJob(id = "j", state = "cancelled")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theClockOnTheCardRunsOnFromTheRead() {
|
||||
val seen = JobSeen(job("media_job"), at = 10_000)
|
||||
assertEquals(42L, seen.elapsed(10_000))
|
||||
assertEquals(47L, seen.elapsed(15_999))
|
||||
// A clock that went back, or a job never read, says what the server said.
|
||||
assertEquals(42L, seen.elapsed(5_000))
|
||||
assertEquals(42L, JobSeen(job("media_job")).elapsed(99_000))
|
||||
// An ended job took what it took.
|
||||
assertEquals(95L, JobSeen(job("media_job_done"), at = 10_000).elapsed(500_000))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aCardIsDrawnFromWhatWasReadElseFromTheCall() {
|
||||
val ref = jobRefsOf(listOf(reply)).single()
|
||||
val unread = ChatMedia(emptyMap(), object : MediaActions {})
|
||||
assertEquals("running", unread.job(ref).job.state)
|
||||
assertTrue(unread.job(ref).job.underWay)
|
||||
assertEquals(0L, unread.job(ref).at)
|
||||
val read = ChatMedia(mapOf("mjob1" to JobSeen(job("media_job_failed").copy(id = "mjob1"), at = 5)), object : MediaActions {})
|
||||
assertEquals("failed", read.job(ref).job.state)
|
||||
assertEquals("ComfyUI ran out of video memory in KSampler.", read.job(ref).job.error)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aGeneratedFileIsAskedForByItsId() {
|
||||
val done = job("media_job_done").result!!
|
||||
assertEquals(Raw.Node("node7"), done.raw)
|
||||
assertEquals("/home/frodo/Generated", done.folder)
|
||||
assertEquals("video-20260102-030405.mp4", done.title)
|
||||
// A result without an id is asked for by where it was written.
|
||||
assertEquals(Raw.Path("/home/frodo/Generated/a.glb"), done.copy(nodeId = "", path = "/home/frodo/Generated/a.glb").raw)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.ChatPage
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Metrics
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.RunResult
|
||||
import eu.llembas.android.api.Schedule
|
||||
import eu.llembas.android.api.ScheduleEnvelope
|
||||
import eu.llembas.android.api.SchedulingModel
|
||||
import eu.llembas.android.api.modelKey
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.api.replyModel
|
||||
import eu.llembas.android.api.saidWithConnection
|
||||
import eu.llembas.android.api.serving
|
||||
import eu.llembas.android.ui.chat.ChatState
|
||||
import eu.llembas.android.ui.chat.footLine
|
||||
import eu.llembas.android.ui.chat.modelId
|
||||
import eu.llembas.android.ui.chat.modelInfo
|
||||
import eu.llembas.android.ui.chat.modelWord
|
||||
import eu.llembas.android.ui.scheduled.EditState
|
||||
import eu.llembas.android.ui.scheduled.modelToSend
|
||||
import eu.llembas.android.ui.scheduled.read
|
||||
import kotlinx.serialization.KSerializer
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Two connections serve one model id, and a chat, a reply and a schedule are on the second:
|
||||
* each says which connection (`model_ref`), and the app shows that one, not the first with the id.
|
||||
*/
|
||||
class ModelRefTest {
|
||||
private val home = ModelInfo(id = "qwen", name = "Qwen", ref = "local/qwen", provider = "local", connection = "Local", default = true)
|
||||
private val cloud = ModelInfo(id = "qwen", name = "Qwen", ref = "studio/qwen", provider = "studio", connection = "Model Studio")
|
||||
private val other = ModelInfo(id = "gpt-oss", name = "gpt-oss", ref = "local/gpt-oss", provider = "local", connection = "Local")
|
||||
private val models = listOf(home, cloud, other)
|
||||
|
||||
private fun <T> read(name: String, serializer: KSerializer<T>): T = LembasJson.decodeFromString(
|
||||
serializer,
|
||||
requireNotNull(javaClass.classLoader!!.getResource("$name.json")) {
|
||||
"contract/$name.json is missing"
|
||||
}.readText(),
|
||||
)
|
||||
|
||||
@Test
|
||||
fun aChatOnTheSecondConnectionShowsTheSecond() {
|
||||
val chat = Chat(id = "c", model = "qwen", modelRef = "studio/qwen")
|
||||
val open = ChatState(models = models, chat = chat)
|
||||
assertEquals("studio/qwen", chat.modelKey)
|
||||
// The header, the composer's facts and the picker's tick all read these two.
|
||||
assertEquals("studio/qwen", open.modelId)
|
||||
assertEquals(cloud, open.modelInfo)
|
||||
assertEquals(cloud.key, models.named(open.modelId)?.key)
|
||||
// What was picked here earlier does not outrank what the chat itself says.
|
||||
assertEquals(cloud, open.copy(picked = "local/qwen").modelInfo)
|
||||
// The bare id alone still names the first, as before and as on the server.
|
||||
assertEquals(home, ChatState(models = models, chat = Chat(id = "c", model = "qwen")).modelInfo)
|
||||
assertEquals(home, ChatState(models = models, chat = Chat(id = "c", model = "qwen", modelRef = "")).modelInfo)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRefTheListDoesNotHaveIsNoModelRatherThanTheFirstWithThatId() {
|
||||
val open = ChatState(models = models, chat = Chat(id = "c", model = "qwen", modelRef = "gone/qwen"))
|
||||
assertNull(open.modelInfo)
|
||||
// The title then says the chat's own id for it, not a ref nobody chose by.
|
||||
assertEquals("qwen", open.modelWord)
|
||||
assertNull(models.serving("gone/qwen", "qwen"))
|
||||
assertEquals(home, models.serving(null, "qwen"))
|
||||
assertEquals(cloud, models.serving("studio/qwen", "anything"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whatAThingIsKeptAndSentBy() {
|
||||
assertEquals("studio/qwen", modelKey("studio/qwen", "qwen"))
|
||||
assertEquals("qwen", modelKey(null, "qwen"))
|
||||
assertEquals("qwen", modelKey("", "qwen"))
|
||||
assertNull(modelKey(null, ""))
|
||||
assertNull(modelKey(null, null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theLineUnderAReplyNamesTheConnectionOfATwin() {
|
||||
assertEquals("qwen · Model Studio", models.replyModel("studio/qwen", "qwen"))
|
||||
assertEquals("qwen · Local", models.replyModel("local/qwen", "qwen"))
|
||||
// A model alone with its id says nothing more, and neither does a reply with no ref.
|
||||
assertEquals("gpt-oss", models.replyModel("local/gpt-oss", "gpt-oss"))
|
||||
assertEquals("qwen", models.replyModel(null, "qwen"))
|
||||
assertEquals("qwen", models.replyModel("gone/qwen", "qwen"))
|
||||
assertNull(models.replyModel("studio/qwen", null))
|
||||
val reply = Message(id = "m", role = "assistant", model = "qwen", modelRef = "studio/qwen", metrics = Metrics(completionTokens = 12))
|
||||
assertEquals("qwen · Model Studio · 12 tok", footLine(reply, models))
|
||||
assertEquals("qwen · 12 tok", footLine(reply))
|
||||
assertEquals("qwen · Model Studio", footLine(reply.copy(metrics = null), models))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aScheduleAndItsRunNameTheConnection() {
|
||||
val offered = listOf(
|
||||
SchedulingModel(id = "qwen", name = "Qwen", ref = "local/qwen", connection = "Local"),
|
||||
SchedulingModel(id = "qwen", name = "Qwen", ref = "studio/qwen", connection = "Model Studio"),
|
||||
SchedulingModel(id = "gpt-oss", name = "gpt-oss", ref = "local/gpt-oss", connection = "Local"),
|
||||
)
|
||||
assertEquals("qwen · Model Studio", offered.saidWithConnection("studio/qwen", "qwen"))
|
||||
assertEquals("gpt-oss", offered.saidWithConnection("local/gpt-oss", "gpt-oss"))
|
||||
assertEquals("qwen", offered.saidWithConnection(null, "qwen"))
|
||||
assertEquals("qwen", emptyList<SchedulingModel>().saidWithConnection("studio/qwen", "qwen"))
|
||||
assertNull(offered.saidWithConnection("studio/qwen", ""))
|
||||
|
||||
// The form starts from the schedule's own connection, ticks that one, and a save that
|
||||
// changed nothing says no model.
|
||||
val schedule = Schedule(id = "s", model = "qwen", modelRef = "studio/qwen")
|
||||
assertEquals("studio/qwen", schedule.modelKey)
|
||||
val form = EditState(models = offered, loaded = true).read(schedule).copy(agentic = true)
|
||||
assertEquals("studio/qwen", form.model)
|
||||
assertEquals(offered[1], offered.named(form.model))
|
||||
assertNull(modelToSend(form, editing = true))
|
||||
assertEquals("local/qwen", modelToSend(form.copy(model = "local/qwen"), editing = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun thePinnedContractSaysTheRefs() {
|
||||
assertEquals("local/qwen", read("chat", Chat.serializer()).modelRef)
|
||||
assertEquals("local/qwen", read("chats_listed", ChatPage.serializer()).chats.first().modelRef)
|
||||
assertEquals("local/qwen", read("message_assistant", Message.serializer()).modelRef)
|
||||
assertEquals("local/qwen", read("schedule", ScheduleEnvelope.serializer()).schedule.modelRef)
|
||||
assertEquals("local/gpt-oss", read("schedule_run", RunResult.serializer()).run.model.ref)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.ChatDetail
|
||||
import eu.llembas.android.api.ChatPage
|
||||
import eu.llembas.android.api.Drawn
|
||||
import eu.llembas.android.api.EventsHub
|
||||
import eu.llembas.android.api.Frame
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.MessageEnd
|
||||
import eu.llembas.android.api.ReplyFrame
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.drawn
|
||||
import eu.llembas.android.api.replyUnrecorded
|
||||
import eu.llembas.android.api.unrecordedReplies
|
||||
import eu.llembas.android.ui.chat.ChatState
|
||||
import eu.llembas.android.ui.chat.TranscriptChange
|
||||
import eu.llembas.android.ui.chat.asksFor
|
||||
import eu.llembas.android.ui.chat.movesToEnd
|
||||
import eu.llembas.android.ui.chat.pictureRatio
|
||||
import eu.llembas.android.ui.chat.restFollows
|
||||
import eu.llembas.android.ui.chat.transcriptChange
|
||||
import eu.llembas.android.ui.chat.wentBack
|
||||
import eu.llembas.android.ui.chat.withNewest
|
||||
import eu.llembas.android.ui.home.ChatsState
|
||||
import eu.llembas.android.ui.home.withNewest
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.flow.receiveAsFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* A reply this app did not start (the events route's `reply` frame, `contract/event_reply.json`):
|
||||
* which frames are news to an open chat, what reading the chat again keeps, how a turn nobody
|
||||
* typed and its reply are drawn -- and where the transcript stands through all of it.
|
||||
*/
|
||||
class ReplyEventTest {
|
||||
private fun text(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) { "contract/$name.json is missing" }.readText()
|
||||
|
||||
private fun person(id: String) = Message(id = id, role = "user", text = "How many cakes are left?")
|
||||
|
||||
private fun reply(id: String, complete: Boolean = true) = Message(
|
||||
id = id,
|
||||
role = "assistant",
|
||||
complete = complete,
|
||||
steps = if (complete) listOf(Step(index = 0, kind = "text", markdown = "Seven.")) else emptyList(),
|
||||
)
|
||||
|
||||
private fun note(id: String, origin: String = "") = Message(id = id, role = "user", machine = true, origin = origin, text = "The baker has finished.")
|
||||
|
||||
private val chat = Chat(id = "chat1")
|
||||
|
||||
private fun frame(message: String, chatId: String = "chat1", live: Boolean = true) = ReplyFrame(chatId = chatId, messageId = message, live = live)
|
||||
|
||||
@Test
|
||||
fun theFrameIsReadAsTheServerWritesIt() {
|
||||
val said = LembasJson.decodeFromString(ReplyFrame.serializer(), text("event_reply"))
|
||||
assertEquals(ReplyFrame(chatId = "chat1", messageId = "msg2", live = true), said)
|
||||
// A frame with more in it than this app knows is still read; one with less says nothing is live.
|
||||
assertEquals(frame("m9", live = false), LembasJson.decodeFromString(ReplyFrame.serializer(), """{"chat_id":"chat1","message_id":"m9","kind":"wake"}"""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onlyAReplyThisScreenDoesNotHoldIsNews() {
|
||||
val open = ChatState(chat = chat, messages = listOf(person("q1"), reply("a1")))
|
||||
// A reply nobody asked for from here: news.
|
||||
assertTrue(open.asksFor(frame("a2")))
|
||||
// Said as already ended: the chat is still read, the row is not there yet.
|
||||
assertTrue(open.asksFor(frame("a2", live = false)))
|
||||
// Another chat's, or a frame that names no reply: not this screen's.
|
||||
assertFalse(open.asksFor(frame("a2", chatId = "chat2")))
|
||||
assertFalse(open.asksFor(frame("")))
|
||||
// A chat not made yet has no replies to hear of.
|
||||
assertFalse(ChatState().asksFor(frame("a2")))
|
||||
// The reply being followed -- this app's own, said back by the server: not news.
|
||||
val writing = open.copy(messages = open.messages + person("q2") + reply("a2", complete = false), live = LiveReply("a2"))
|
||||
assertFalse(writing.asksFor(frame("a2")))
|
||||
// One drawn as finished: not news either, however late its frame is heard.
|
||||
assertFalse(open.asksFor(frame("a1")))
|
||||
// A row that is there but was never finished and is followed by nobody (its stream was lost): news.
|
||||
val lost = open.copy(messages = open.messages + person("q2") + reply("a2", complete = false))
|
||||
assertTrue(lost.asksFor(frame("a2")))
|
||||
// While another reply is followed, the frame for the next one is still news -- it is taken up after.
|
||||
assertTrue(writing.asksFor(frame("a3")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun readingTheChatAgainKeepsTheOlderPagesAPersonLoaded() {
|
||||
val rows = listOf(person("q1"), reply("a1"), person("q2"), reply("a2"), person("q3"), reply("a3"))
|
||||
// Two older pages were loaded: the transcript goes back to the chat's first message.
|
||||
val shown = ChatState(chat = chat, messages = rows, more = false)
|
||||
// The newest page as the server has it now: a turn nobody typed and its reply are new.
|
||||
val page = listOf(person("q3"), reply("a3"), note("n1", "harness"), reply("a4", complete = false))
|
||||
val read = shown.withNewest(ChatDetail(chat = chat.copy(title = "Waybread"), messages = page, more = true, live = "a4"))
|
||||
assertEquals(listOf("q1", "a1", "q2", "a2", "q3", "a3", "n1", "a4"), read.messages.map { it.id })
|
||||
// What is above is what this screen loaded, not what the page says of itself.
|
||||
assertFalse(read.more)
|
||||
assertEquals("Waybread", read.chat?.title)
|
||||
// The rows a reader looks at are the same rows, so the list keeps them where they are.
|
||||
assertEquals(TranscriptChange.Appended, transcriptChange(shown.messages, read.messages))
|
||||
|
||||
// The page is the whole chat (nothing above it), or joins nothing shown: it replaces the transcript.
|
||||
val whole = shown.withNewest(ChatDetail(chat = chat, messages = page, more = false))
|
||||
assertEquals(page.map { it.id }, whole.messages.map { it.id })
|
||||
val elsewhere = listOf(person("x1"), reply("y1"))
|
||||
assertEquals(elsewhere, shown.withNewest(ChatDetail(chat = chat, messages = elsewhere, more = true)).messages)
|
||||
// Only the newest page was shown: it is replaced, with the server's word on what is above.
|
||||
val one = ChatState(chat = chat, messages = listOf(person("q3"), reply("a3")), more = true)
|
||||
assertEquals(ChatState(chat = chat, messages = page, more = true), one.withNewest(ChatDetail(chat = chat, messages = page, more = true)))
|
||||
// A rewind: the rows after the edited turn are gone on the server, and go here.
|
||||
val rewound = shown.withNewest(ChatDetail(chat = chat, messages = listOf(reply("a1"), person("q2"), reply("a5")), more = true))
|
||||
assertEquals(listOf("q1", "a1", "q2", "a5"), rewound.messages.map { it.id })
|
||||
// No row twice, whatever the page repeats of the rows above it.
|
||||
val repeating = shown.withNewest(ChatDetail(chat = chat, messages = listOf(person("q2"), reply("a2"), person("q1")), more = true))
|
||||
assertEquals(repeating.messages.map { it.id }.distinct(), repeating.messages.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aReplyNobodyAskedForFollowsOnlyForAPersonAtTheEnd() {
|
||||
val before = listOf(person("q1"), reply("a1"))
|
||||
val after = before + note("n1", "harness") + reply("a2", complete = false)
|
||||
val change = transcriptChange(before, after, sent = "q1")
|
||||
assertEquals(TranscriptChange.Appended, change)
|
||||
assertTrue(movesToEnd(change, following = true))
|
||||
assertFalse(movesToEnd(change, following = false))
|
||||
// The stored reply in place of the one being written is the same row under the same key.
|
||||
val stored = before + note("n1", "harness") + reply("a2")
|
||||
assertEquals(after.map { it.id }, stored.map { it.id })
|
||||
assertEquals(TranscriptChange.Changed, transcriptChange(after, stored))
|
||||
assertFalse(movesToEnd(TranscriptChange.Changed, following = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aReplyFrameIsNotToldAgainToAWatcherThatJoinsLater() = runTest {
|
||||
// The one connection, as a line whose frames wait for whoever reads it.
|
||||
val route = Channel<Frame>(Channel.UNLIMITED)
|
||||
val hub = EventsHub(backgroundScope)
|
||||
val open = { route.receiveAsFlow() }
|
||||
val drawer = Channel<Frame>(Channel.UNLIMITED)
|
||||
val screen = Channel<Frame>(Channel.UNLIMITED)
|
||||
val first = launch { hub.frames("instance", open).collect { drawer.send(it) } }
|
||||
val reports = Frame("reports", """{"unread":1}""")
|
||||
val started = Frame("reply", text("event_reply"))
|
||||
route.send(reports)
|
||||
route.send(started)
|
||||
assertEquals(reports, drawer.receive())
|
||||
assertEquals(started, drawer.receive())
|
||||
// A chat opened later hears the state it missed, and not the reply that started before it listened.
|
||||
val second = launch { hub.frames("instance", open).collect { screen.send(it) } }
|
||||
assertEquals(reports, screen.receive())
|
||||
val next = Frame("reply", """{"chat_id":"chat1","message_id":"msg3","live":true}""")
|
||||
route.send(next)
|
||||
assertEquals(next, screen.receive())
|
||||
assertEquals(next, drawer.receive())
|
||||
first.cancel()
|
||||
second.cancel()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theListReadAgainMovesTheChatUpAndKeepsWhatWasLoadedBelow() {
|
||||
fun row(id: String, running: Boolean = false, unread: Boolean = false) = Chat(id = id, title = id, running = running, unread = unread)
|
||||
val shown = ChatsState(chats = listOf(row("c1"), row("c2"), row("c3"), row("c4"), row("c5")), more = true)
|
||||
// The first page is three rows; c4 and c5 were loaded with "more".
|
||||
val page = ChatPage(chats = listOf(row("c3", running = true), row("c1"), row("c2")), more = true)
|
||||
val read = shown.withNewest(page)
|
||||
assertEquals(listOf("c3", "c1", "c2", "c4", "c5"), read.chats.map { it.id })
|
||||
assertTrue(read.chats.first().running)
|
||||
assertTrue(read.more)
|
||||
// A new chat pushed the page's last row off it: that row is kept below, once.
|
||||
val pushed = shown.withNewest(ChatPage(chats = listOf(row("c0", unread = true), row("c1"), row("c2")), more = true))
|
||||
assertEquals(listOf("c0", "c1", "c2", "c3", "c4", "c5"), pushed.chats.map { it.id })
|
||||
// Only the page was shown, or nothing shown is on it: the page is the list.
|
||||
val short = ChatsState(chats = listOf(row("c1"), row("c2")), more = false)
|
||||
assertEquals(ChatsState(chats = page.chats, more = true), short.withNewest(page))
|
||||
val other = ChatPage(chats = listOf(row("x1")), more = false)
|
||||
assertEquals(ChatsState(chats = other.chats, more = false), shown.withNewest(other))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aTurnTheComputersHarnessStartedIsNeverThePersonsBubble() {
|
||||
val harness = note("n1", "harness")
|
||||
assertEquals(Drawn.Note, drawn(harness, first = false, reportChat = false))
|
||||
// By its origin alone, should a server say it without `machine`.
|
||||
assertEquals(Drawn.Note, drawn(harness.copy(machine = false), first = false, reportChat = false))
|
||||
// Typed in the terminal: a person wrote it, and an origin this app does not know is nobody's mark.
|
||||
assertEquals(Drawn.Person, drawn(person("q1").copy(origin = "terminal"), first = false, reportChat = false))
|
||||
assertEquals(Drawn.Person, drawn(person("q1").copy(origin = "later"), first = false, reportChat = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anEmptyFinishedReplyToATurnNobodyTypedSaysSoInOneLine() {
|
||||
val empty = Message(id = "a2", role = "assistant")
|
||||
assertTrue(replyUnrecorded(empty, note("n1", "harness")))
|
||||
assertTrue(replyUnrecorded(empty, note("n1")))
|
||||
// To something a person asked, an empty reply is just that.
|
||||
assertFalse(replyUnrecorded(empty, person("q1")))
|
||||
assertFalse(replyUnrecorded(empty, null))
|
||||
assertFalse(replyUnrecorded(empty, reply("a1")))
|
||||
// Still being written, stopped, failed, or holding anything at all: drawn as a reply.
|
||||
assertFalse(replyUnrecorded(empty.copy(complete = false), note("n1")))
|
||||
assertFalse(replyUnrecorded(empty.copy(stopped = true), note("n1")))
|
||||
assertFalse(replyUnrecorded(empty.copy(error = "The device did not answer."), note("n1")))
|
||||
assertFalse(replyUnrecorded(empty.copy(end = MessageEnd(phase = "stopped")), note("n1")))
|
||||
assertFalse(replyUnrecorded(empty.copy(text = "Seven."), note("n1")))
|
||||
assertFalse(replyUnrecorded(reply("a2"), note("n1")))
|
||||
// In a transcript: by the row before each reply.
|
||||
val rows = listOf(person("q1"), reply("a1"), note("n1", "harness"), empty, note("n2", "harness"), reply("a3"), person("q2"), empty.copy(id = "a4"))
|
||||
assertEquals(setOf("a2"), unrecordedReplies(rows))
|
||||
assertEquals(emptySet<String>(), unrecordedReplies(listOf(empty)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onlyThePersonsOwnScrollEndsTheFollowing() {
|
||||
// This app's scroll to the end, left short of it by a card that arrived meanwhile: still following.
|
||||
assertTrue(restFollows(following = true, byPerson = false, distance = 600, slack = 96))
|
||||
// The same rest after a finger: the person is reading above, and is left there.
|
||||
assertFalse(restFollows(following = true, byPerson = true, distance = 600, slack = 96))
|
||||
// Back at the end, however it got there: the following is taken up.
|
||||
assertTrue(restFollows(following = false, byPerson = true, distance = 40, slack = 96))
|
||||
assertTrue(restFollows(following = false, byPerson = false, distance = 0, slack = 96))
|
||||
// Not following and resting away from the end: nothing takes it up.
|
||||
assertFalse(restFollows(following = false, byPerson = false, distance = 600, slack = 96))
|
||||
// A list gone back towards its start was moved by a person (a wheel, a key, a reader's gesture).
|
||||
assertTrue(wentBack(fromIndex = 8, fromOffset = 0, toIndex = 6, toOffset = 120))
|
||||
assertTrue(wentBack(fromIndex = 8, fromOffset = 300, toIndex = 8, toOffset = 40))
|
||||
// Further down, or where it was: this app's own keeping to the end.
|
||||
assertFalse(wentBack(fromIndex = 8, fromOffset = 300, toIndex = 8, toOffset = 300))
|
||||
assertFalse(wentBack(fromIndex = 8, fromOffset = 300, toIndex = 9, toOffset = 0))
|
||||
assertFalse(wentBack(fromIndex = 8, fromOffset = 300, toIndex = 8, toOffset = 900))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPicturesPlaceHasItsShapeBeforeItsBytes() {
|
||||
assertEquals(1.6f, pictureRatio(1024, 640), 0.001f)
|
||||
assertEquals(0.75f, pictureRatio(768, 1024), 0.001f)
|
||||
// A size the server did not say: a square, not nothing.
|
||||
assertEquals(1f, pictureRatio(0, 0), 0f)
|
||||
assertEquals(1f, pictureRatio(1024, 0), 0f)
|
||||
// A strip is kept within what a phone can show.
|
||||
assertEquals(4f, pictureRatio(4000, 100), 0f)
|
||||
assertEquals(0.25f, pictureRatio(100, 4000), 0f)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,411 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ArchiveListing
|
||||
import eu.llembas.android.api.FileContent
|
||||
import eu.llembas.android.api.FileExists
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.FileNode
|
||||
import eu.llembas.android.api.FileView
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.SchedulingModel
|
||||
import eu.llembas.android.api.Whereabouts
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.api.whereabouts
|
||||
import eu.llembas.android.assist.AssistUiState
|
||||
import eu.llembas.android.share.Kept
|
||||
import eu.llembas.android.share.SharedSource
|
||||
import eu.llembas.android.ui.files.FileCache
|
||||
import eu.llembas.android.ui.scheduled.EditState
|
||||
import eu.llembas.android.ui.scheduled.modelInfo
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.cancelAndJoin
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.test.advanceTimeBy
|
||||
import kotlinx.coroutines.test.runCurrent
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
|
||||
/**
|
||||
* What a review of the file manager found, each as the rule it became: nothing new is sent
|
||||
* from behind a lock, a share's addresses are not believed, a new file empties nothing, a kept
|
||||
* copy outlives a restart, a name fits a file system, a ref is never read as an id, a second
|
||||
* try goes on where the first stopped, and a transfer given up ends at once.
|
||||
*/
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class ReviewFixesTest {
|
||||
@get:Rule
|
||||
val folder = TemporaryFolder()
|
||||
|
||||
// --- The gate ----------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun theRequestUnderWayFinishesAndTheNextWaitsForTheUnlock() = runTest {
|
||||
var locked = false
|
||||
val gate = InstanceGate { locked }
|
||||
gate.activityStarted()
|
||||
val started = mutableListOf<Int>()
|
||||
val waits = mutableListOf<Boolean>()
|
||||
val first = CompletableDeferred<Unit>()
|
||||
val queue = launch {
|
||||
sendFrom(listOf(1, 2, 3), 0, { gate.pass { waits += it } }, {}) { n ->
|
||||
started += n
|
||||
if (n == 1) first.await()
|
||||
}
|
||||
}
|
||||
runCurrent()
|
||||
assertEquals(listOf(1), started)
|
||||
|
||||
// The phone locks while the first is on its way: it goes through, the second does not start.
|
||||
locked = true
|
||||
gate.look()
|
||||
first.complete(Unit)
|
||||
runCurrent()
|
||||
assertEquals(listOf(1), started)
|
||||
assertEquals(listOf(true), waits)
|
||||
advanceTimeBy(60_000)
|
||||
runCurrent()
|
||||
assertEquals(listOf(1), started)
|
||||
|
||||
// Unlocked, and nobody said so: the gate looks again by itself and the queue goes on.
|
||||
locked = false
|
||||
advanceTimeBy(InstanceGate.AGAIN_MS + 1)
|
||||
runCurrent()
|
||||
assertEquals(listOf(1, 2, 3), started)
|
||||
assertEquals(listOf(true, false), waits)
|
||||
queue.join()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun nothingStartsWhileTheAppIsNotInFront() = runTest {
|
||||
val gate = InstanceGate { false }
|
||||
val started = mutableListOf<String>()
|
||||
// No activity of the app is started: shut, although the phone is unlocked.
|
||||
assertFalse(gate.look())
|
||||
val waiting = launch {
|
||||
gate.pass()
|
||||
started += "sent"
|
||||
}
|
||||
runCurrent()
|
||||
assertTrue(started.isEmpty())
|
||||
gate.activityStarted()
|
||||
runCurrent()
|
||||
assertEquals(listOf("sent"), started)
|
||||
waiting.join()
|
||||
|
||||
// In front but locked (a sheet over the lock screen) is shut too; stopped again is shut.
|
||||
var locked = true
|
||||
val over = InstanceGate { locked }
|
||||
over.activityStarted()
|
||||
assertFalse(over.open.value)
|
||||
locked = false
|
||||
assertTrue(over.look())
|
||||
over.activityStopped()
|
||||
assertFalse(over.open.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aWaitGivenUpSaysItIsOver() = runTest {
|
||||
val gate = InstanceGate { true }
|
||||
gate.activityStarted()
|
||||
val waits = mutableListOf<Boolean>()
|
||||
val job = launch { gate.pass { waits += it } }
|
||||
runCurrent()
|
||||
assertEquals(listOf(true), waits)
|
||||
job.cancelAndJoin()
|
||||
assertEquals(listOf(true, false), waits)
|
||||
}
|
||||
|
||||
// --- A second try ------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun aSecondTryGoesOnFromTheOneThatFailed() = runTest {
|
||||
val files = listOf("a.txt", "b.txt", "c.txt", "d.txt")
|
||||
val sent = mutableListOf<String>()
|
||||
var kept = Kept().into("/home/frodo")
|
||||
var refuse = true
|
||||
val send: suspend (String) -> Unit = { name ->
|
||||
if (name == "c.txt" && refuse) throw IOException("too large")
|
||||
sent += name
|
||||
}
|
||||
try {
|
||||
sendFrom(files, kept.done, {}, { kept = kept.copy(done = it) }, send)
|
||||
fail("the third is refused")
|
||||
} catch (e: IOException) {
|
||||
assertEquals(2, kept.done)
|
||||
}
|
||||
// Save again, into the same folder: the first two are not sent twice.
|
||||
refuse = false
|
||||
kept = kept.into("/home/frodo")
|
||||
sendFrom(files, kept.done, {}, { kept = kept.copy(done = it) }, send)
|
||||
assertEquals(listOf("a.txt", "b.txt", "c.txt", "d.txt"), sent)
|
||||
assertEquals(4, kept.done)
|
||||
// Another folder has none of them: from the first.
|
||||
assertEquals(0, kept.into("/home/frodo/recipes").done)
|
||||
}
|
||||
|
||||
// --- A share's addresses -----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun aShareMayNotNameThisAppsOwnFiles() {
|
||||
val own = setOf("eu.llembas.android.files", "eu.llembas.android.androidx-startup")
|
||||
// Another app's provider is what a share is.
|
||||
assertFalse(SharedSource.refused("content", "com.example.gallery.provider", own))
|
||||
assertFalse(SharedSource.refused("content", "media", own))
|
||||
// A path is read with this app's own rights; so is anything that is not a provider's address.
|
||||
assertTrue(SharedSource.refused("file", "", own))
|
||||
assertTrue(SharedSource.refused("file", null, own))
|
||||
assertTrue(SharedSource.refused("http", "example.org", own))
|
||||
assertTrue(SharedSource.refused(null, null, own))
|
||||
assertTrue(SharedSource.refused("content", "", own))
|
||||
// This app's own provider, however it is spelled: with a user before it, in capitals.
|
||||
assertTrue(SharedSource.refused("content", "eu.llembas.android.files", own))
|
||||
assertTrue(SharedSource.refused("content", "10@eu.llembas.android.files", own))
|
||||
assertTrue(SharedSource.refused("CONTENT", "EU.LLEMBAS.ANDROID.FILES", own))
|
||||
assertTrue(SharedSource.refused("content", "eu.llembas.android.androidx-startup", own))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whatAnAddressOpensOntoMayNotBeInsideThisAppsData() {
|
||||
val roots = listOf("/data/user/0/eu.llembas.android", "/data/data/eu.llembas.android", "/storage/emulated/0/Android/data/eu.llembas.android/")
|
||||
assertTrue(SharedSource.inside("/data/user/0/eu.llembas.android/files/datastore/prefs.preferences_pb", roots))
|
||||
assertTrue(SharedSource.inside("/data/data/eu.llembas.android/cache/shared/x/notes.md", roots))
|
||||
assertTrue(SharedSource.inside("/storage/emulated/0/Android/data/eu.llembas.android/cache/a", roots))
|
||||
assertTrue(SharedSource.inside("/data/user/0/eu.llembas.android", roots))
|
||||
// Another app whose name begins as this one's does, a picture of the phone, a pipe.
|
||||
assertFalse(SharedSource.inside("/data/user/0/eu.llembas.android.debug/files/a", roots))
|
||||
assertFalse(SharedSource.inside("/storage/emulated/0/DCIM/map.jpg", roots))
|
||||
assertFalse(SharedSource.inside("pipe:[4711]", roots))
|
||||
assertFalse(SharedSource.inside("", roots))
|
||||
assertFalse(SharedSource.inside("/anything", listOf("")))
|
||||
}
|
||||
|
||||
// --- A new file --------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun aNewFileIsNotAskedForWhereTheDirectoryHoldsTheName() = runBlocking {
|
||||
val server = MockWebServer().apply { start() }
|
||||
try {
|
||||
val api = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test")
|
||||
val listing = requireNotNull(javaClass.classLoader!!.getResource("files_listing.json")).readText()
|
||||
val content = requireNotNull(javaClass.classLoader!!.getResource("file_content.json")).readText()
|
||||
|
||||
// An instance from before `create` would write over lembas.md: it is never asked to.
|
||||
server.enqueue(MockResponse().setBody(listing))
|
||||
try {
|
||||
api.newFile("/home/frodo", "lembas.md")
|
||||
fail("the name is taken")
|
||||
} catch (e: FileExists) {
|
||||
assertEquals(1, server.requestCount)
|
||||
assertEquals("GET", server.takeRequest().method)
|
||||
}
|
||||
|
||||
// A free name: the directory is read, then the file is made with `create`.
|
||||
server.enqueue(MockResponse().setBody(listing))
|
||||
server.enqueue(MockResponse().setBody(content))
|
||||
assertEquals("/home/frodo/second-breakfast.md", api.newFile("/home/frodo", " second-breakfast.md "))
|
||||
assertEquals("GET", server.takeRequest().method)
|
||||
val put = server.takeRequest()
|
||||
assertEquals("PUT", put.method)
|
||||
val said = put.body.readUtf8()
|
||||
assertTrue(said, said.contains("\"create\":true"))
|
||||
assertTrue(said, said.contains("\"path\":\"/home/frodo/second-breakfast.md\""))
|
||||
} finally {
|
||||
server.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
// --- Copies and names --------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun aCopyAnotherAppWasHandedGoesByItsAgeAlone() {
|
||||
val shared = folder.newFolder("shared")
|
||||
val now = 10_000_000_000L
|
||||
val hour = FileCache.SHARED_KEPT_MS
|
||||
|
||||
fun copy(name: String, folderAge: Long, fileAge: Long): File {
|
||||
val dir = File(shared, name).apply { mkdirs() }
|
||||
val file = File(dir, "report.pdf").apply { writeText("x") }
|
||||
file.setLastModified(now - fileAge)
|
||||
dir.setLastModified(now - folderAge)
|
||||
return dir
|
||||
}
|
||||
val fresh = copy("fresh", folderAge = 60_000, fileAge = 60_000)
|
||||
val old = copy("old", folderAge = hour + 60_000, fileAge = hour + 60_000)
|
||||
// A long download: its folder was made long ago, the file was written just now.
|
||||
val long = copy("long", folderAge = hour + 60_000, fileAge = 1_000)
|
||||
|
||||
// What the start of the process and the closing of a screen do: the fresh copy is still there for the app that has it.
|
||||
FileCache.sweep(shared, now, hour)
|
||||
assertTrue(fresh.exists())
|
||||
assertTrue(File(fresh, "report.pdf").exists())
|
||||
assertFalse(old.exists())
|
||||
assertTrue(long.exists())
|
||||
// A folder that is not there is nothing to sweep.
|
||||
FileCache.sweep(File(shared, "none"), now, hour)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aNameFitsAFileSystemInBytesAndKeepsItsExtension() {
|
||||
fun bytes(text: String) = text.toByteArray(Charsets.UTF_8).size
|
||||
|
||||
// 120 letters of three bytes each were let through as 360 bytes: more than a file system takes.
|
||||
val long = "指".repeat(120) + ".pdf"
|
||||
val safe = FileKinds.safeName(long)
|
||||
assertTrue(bytes(safe).toString(), bytes(safe) <= FileKinds.NAME_MAX_BYTES)
|
||||
assertTrue(safe, safe.endsWith(".pdf"))
|
||||
assertTrue(safe, safe.startsWith("指"))
|
||||
assertEquals("指".repeat(65) + ".pdf", safe)
|
||||
|
||||
// Half of a pair is not a character: a name of four-byte signs is cut between them.
|
||||
val signs = FileKinds.safeName("🗺".repeat(80) + ".png")
|
||||
assertTrue(bytes(signs) <= FileKinds.NAME_MAX_BYTES)
|
||||
assertEquals("🗺".repeat(49) + ".png", signs)
|
||||
|
||||
// A last dot far from the end is not an extension: the name is cut as a whole.
|
||||
val sentence = FileKinds.safeName("a".repeat(100) + "." + "b".repeat(300))
|
||||
assertEquals(FileKinds.NAME_MAX_BYTES, bytes(sentence))
|
||||
// A smaller cap, for a name that gets a prefix of its own.
|
||||
assertTrue(bytes(FileKinds.safeName("ž".repeat(200) + ".md", 80)) <= 80)
|
||||
// A short name is left alone, as before.
|
||||
assertEquals("map.png", FileKinds.safeName("map.png"))
|
||||
assertEquals("a".repeat(196) + ".txt", FileKinds.safeName("a".repeat(196) + ".txt"))
|
||||
}
|
||||
|
||||
// --- A ref is not an id ------------------------------------------------------------------
|
||||
|
||||
// An aggregator serves a model whose id is spelled like another connection's ref.
|
||||
private val routed = ModelInfo(id = "studio/qwen", name = "Qwen", ref = "router/studio/qwen", provider = "router", connection = "Router")
|
||||
private val direct = ModelInfo(id = "qwen", name = "Qwen", ref = "studio/qwen", provider = "studio", connection = "Model Studio")
|
||||
|
||||
@Test
|
||||
fun aRefWhoseModelIsGoneIsNotAnotherConnectionsModelOfThatId() {
|
||||
// Both there: the ref names the direct one.
|
||||
assertEquals(direct, listOf(routed, direct).named("studio/qwen", isRef = true))
|
||||
// The direct connection is gone: the ref names nothing here, not the aggregator's model called that.
|
||||
assertNull(listOf(routed).named("studio/qwen", isRef = true))
|
||||
assertNull(listOf(routed).named("", isRef = true))
|
||||
assertNull(listOf(routed).named(null, isRef = true))
|
||||
// A name of unknown kind (a setting from before refs) is still an id where no ref matches.
|
||||
assertEquals(routed, listOf(routed).named("studio/qwen", isRef = false))
|
||||
assertEquals(routed, listOf(routed).named("studio/qwen"))
|
||||
|
||||
// The assistant's sheet on a continued chat that says its connection.
|
||||
val sheet = AssistUiState(models = listOf(routed), modelId = "studio/qwen", modelIsRef = true)
|
||||
assertNull(sheet.modelInfo)
|
||||
assertEquals(routed, sheet.copy(modelIsRef = false).modelInfo)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aSchedulesOwnRefTicksItsRowOrNone() {
|
||||
val routedPlan = SchedulingModel(id = "studio/qwen", name = "Qwen", ref = "router/studio/qwen", connection = "Router")
|
||||
val directPlan = SchedulingModel(id = "qwen", name = "Qwen", ref = "studio/qwen", connection = "Model Studio")
|
||||
val read = EditState(models = listOf(routedPlan), model = "studio/qwen", modelIsRef = true)
|
||||
assertNull(read.modelInfo)
|
||||
assertEquals(directPlan, read.copy(models = listOf(routedPlan, directPlan)).modelInfo)
|
||||
// A row picked from the list is found as before.
|
||||
assertEquals(routedPlan, read.copy(model = routedPlan.key, modelIsRef = false).modelInfo)
|
||||
assertNull(listOf(routedPlan).named("studio/qwen", isRef = true))
|
||||
assertEquals(routedPlan, listOf(routedPlan).named("studio/qwen", isRef = false))
|
||||
}
|
||||
|
||||
// --- Where a file is now, and what an archive holds ----------------------------------------
|
||||
|
||||
private fun contract(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) {
|
||||
"contract/$name.json is missing"
|
||||
}.readText()
|
||||
|
||||
@Test
|
||||
fun openInFilesGoesWhereTheFileIsNow() = runBlocking {
|
||||
val node = LembasJson.decodeFromString(FileNode.serializer(), contract("file_node"))
|
||||
assertEquals("node6", node.id)
|
||||
assertEquals("video", node.fileKind)
|
||||
assertFalse(node.trashed)
|
||||
// Written to Generated/, moved to Clips since: Files opens at Clips.
|
||||
assertEquals(Whereabouts.Folder("/home/frodo/Clips"), whereabouts(node, "/home/frodo/Generated/video.mp4"))
|
||||
assertEquals(Whereabouts.Trashed, whereabouts(node.copy(trashed = true), "/home/frodo/Generated/video.mp4"))
|
||||
// An instance that cannot say where a node is: the folder it was written to, as before.
|
||||
assertEquals(Whereabouts.Folder("/home/frodo/Generated"), whereabouts(null, "/home/frodo/Generated/video.mp4"))
|
||||
assertEquals(Whereabouts.Folder("/home/frodo/Clips"), whereabouts(node.copy(parent = ""), "/home/frodo/Generated/video.mp4"))
|
||||
|
||||
val server = MockWebServer().apply { start() }
|
||||
try {
|
||||
server.enqueue(MockResponse().setBody(contract("file_node")))
|
||||
val api = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test")
|
||||
assertEquals("/home/frodo/Clips", api.fileNode("node6").parent)
|
||||
val asked = server.takeRequest()
|
||||
assertEquals("GET", asked.method)
|
||||
assertEquals("/api/v2/files/node?id=node6", asked.path)
|
||||
assertEquals("Bearer lmb_test", asked.getHeader("Authorization"))
|
||||
} finally {
|
||||
server.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anArchiveSaysWhatIsInsideIt() {
|
||||
val file = LembasJson.decodeFromString(FileContent.serializer(), contract("file_content_archive"))
|
||||
assertEquals("archive", file.fileKind)
|
||||
// Still nothing to draw as text: the listing is beside the refusal, not instead of it.
|
||||
assertEquals(FileView.Details, FileKinds.viewer(file.fileKind))
|
||||
val archive = requireNotNull(file.archive)
|
||||
assertNull(archive.problem)
|
||||
assertFalse(archive.truncated)
|
||||
assertEquals(2, archive.total)
|
||||
assertEquals(listOf("maps/", "maps/shire.png"), archive.entries.map { it.name })
|
||||
assertEquals(listOf(true, false), archive.entries.map { it.dir })
|
||||
assertEquals(listOf(null, 2048L), archive.entries.map { it.size })
|
||||
// Every other kind, and an instance from before the listing, says nothing of one.
|
||||
assertNull(LembasJson.decodeFromString(FileContent.serializer(), contract("file_content")).archive)
|
||||
// No listing, and why: the instance's sentence is what is shown.
|
||||
val busy = LembasJson.decodeFromString(
|
||||
ArchiveListing.serializer(),
|
||||
"""{"entries": [], "total": null, "truncated": false, "problem": "busy", "message": "Open it again shortly."}""",
|
||||
)
|
||||
assertEquals("busy", busy.problem)
|
||||
assertEquals("Open it again shortly.", busy.message)
|
||||
}
|
||||
|
||||
// --- A transfer given up -----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun aDownloadGivenUpDoesNotWaitForTheServer() = runBlocking {
|
||||
val server = MockWebServer().apply { start() }
|
||||
try {
|
||||
// The server says more is coming and sends no more: the read waits.
|
||||
server.enqueue(MockResponse().setBody("0123456789").setHeader("Content-Length", "100000"))
|
||||
val api = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test")
|
||||
val began = CompletableDeferred<Unit>()
|
||||
val transfer = launch(Dispatchers.Default) {
|
||||
api.download(api.rawFile("/home/frodo/map.png"), ByteArrayOutputStream(), progress = { _, _ -> began.complete(Unit) })
|
||||
}
|
||||
withTimeout(10_000) { began.await() }
|
||||
val ended = withTimeoutOrNull(5_000) {
|
||||
transfer.cancelAndJoin()
|
||||
true
|
||||
}
|
||||
assertEquals("Cancel must end the read, not wait for its timeout", true, ended)
|
||||
assertTrue(transfer.isCancelled)
|
||||
} finally {
|
||||
server.shutdown()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,7 +93,7 @@ class ScheduleContractTest {
|
||||
assertWaybread(read("schedules", ScheduleList.serializer()).schedules.single())
|
||||
assertWaybread(read("schedule", ScheduleEnvelope.serializer()).schedule)
|
||||
val frame = read("event_schedules", SchedulesFrame.serializer())
|
||||
assertEquals("31f4ad7e7995d215", frame.version)
|
||||
assertEquals("3968a502db186b62", frame.version)
|
||||
assertWaybread(frame.schedules.single())
|
||||
}
|
||||
|
||||
|
||||
@@ -118,7 +118,7 @@ class ScheduleTypesTest {
|
||||
|
||||
@Test
|
||||
fun aChatSchedulesModelIsShownWhenItIsMadeAgentic() {
|
||||
val chat = read("schedule", ScheduleEnvelope.serializer()).schedule.copy(model = "gpt-oss")
|
||||
val chat = read("schedule", ScheduleEnvelope.serializer()).schedule.copy(model = "gpt-oss", modelRef = null)
|
||||
val form = EditState().read(chat).copy(loaded = true, agentic = true, device = "tok1", cwd = "/home/user/project")
|
||||
// Its own model is the one the form shows, and it is kept: nothing is said of it.
|
||||
assertEquals("gpt-oss", form.model)
|
||||
|
||||
@@ -0,0 +1,616 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.ChatDetail
|
||||
import eu.llembas.android.api.ChatPage
|
||||
import eu.llembas.android.api.Drawn
|
||||
import eu.llembas.android.api.Frame
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Outcome
|
||||
import eu.llembas.android.api.ReplyFrame
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.drawn
|
||||
import eu.llembas.android.api.fateUnknown
|
||||
import eu.llembas.android.api.reopened
|
||||
import eu.llembas.android.api.replyUnrecorded
|
||||
import eu.llembas.android.api.unrecordedReplies
|
||||
import eu.llembas.android.ui.chat.ChatState
|
||||
import eu.llembas.android.ui.chat.KEPT_MOST
|
||||
import eu.llembas.android.ui.chat.KEPT_ROWS
|
||||
import eu.llembas.android.ui.chat.Reads
|
||||
import eu.llembas.android.ui.chat.TranscriptChange
|
||||
import eu.llembas.android.ui.chat.asksFor
|
||||
import eu.llembas.android.ui.chat.capped
|
||||
import eu.llembas.android.ui.chat.movesToEnd
|
||||
import eu.llembas.android.ui.chat.ownScroll
|
||||
import eu.llembas.android.ui.chat.personScrolls
|
||||
import eu.llembas.android.ui.chat.restFollows
|
||||
import eu.llembas.android.ui.chat.scrollWasPersons
|
||||
import eu.llembas.android.ui.chat.transcriptChange
|
||||
import eu.llembas.android.ui.chat.withNewest
|
||||
import eu.llembas.android.ui.home.ChatsState
|
||||
import eu.llembas.android.ui.home.ReplyEnds
|
||||
import eu.llembas.android.ui.home.Soon
|
||||
import eu.llembas.android.ui.home.ended
|
||||
import eu.llembas.android.ui.home.readsFor
|
||||
import eu.llembas.android.ui.home.runningPause
|
||||
import eu.llembas.android.ui.home.withNewest
|
||||
import eu.llembas.android.ui.scheduled.listens
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.cancelAndJoin
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.flow.toList
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.test.advanceTimeBy
|
||||
import kotlinx.coroutines.test.advanceUntilIdle
|
||||
import kotlinx.coroutines.test.runCurrent
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.ZoneOffset
|
||||
|
||||
/**
|
||||
* What a second review found, each as the rule it became: the list of chats is merged by id, a
|
||||
* reply nobody asked for is not followed behind a lock, a long transcript is held to a size, a
|
||||
* list the person is scrolling is theirs, the list of chats is read when it is seen and no
|
||||
* oftener than needed, a reply's end is marked without a read, and several pieces of one news
|
||||
* are one read.
|
||||
*/
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class SecondReviewTest {
|
||||
// --- The list of chats, read again -----------------------------------------------------------
|
||||
|
||||
private val noon = OffsetDateTime.of(2026, 1, 2, 12, 0, 0, 0, ZoneOffset.UTC)
|
||||
|
||||
/** The chat [n]: the higher its number, the longer ago it changed -- the list's own order. */
|
||||
private fun row(n: Int, changed: Int = n, running: Boolean = false, pinned: Boolean = false) =
|
||||
Chat(id = "c$n", title = "Chat $n", running = running, pinned = pinned, updatedAt = noon.minusMinutes(changed.toLong()).toString())
|
||||
|
||||
private fun rows(range: IntRange) = range.map { row(it) }
|
||||
|
||||
@Test
|
||||
fun aChatThatComesUpFromALaterPageTakesNoOtherChatWithIt() {
|
||||
// Three pages loaded; a reply starts in a chat of the last one, which goes to the top.
|
||||
val shown = ChatsState(chats = rows(1..90), more = false)
|
||||
val page = ChatPage(chats = listOf(row(80, changed = 0, running = true)) + rows(1..49), more = true)
|
||||
val read = shown.withNewest(page)
|
||||
assertEquals(listOf("c80") + (1..79).map { "c$it" } + (81..90).map { "c$it" }, read.chats.map { it.id })
|
||||
assertTrue(read.chats.first().running)
|
||||
// "More" still asks for what comes after the oldest chat shown, and there was none.
|
||||
assertEquals("c90", read.chats.last().id)
|
||||
assertFalse(read.more)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPinnedChatFurtherDownStaysAndTheNewestPageSaysWhatItIsNow() {
|
||||
val shown = ChatsState(chats = rows(1..59) + row(60, pinned = true) + rows(61..70), more = true)
|
||||
// Pinned elsewhere meanwhile: the page's own row says so.
|
||||
val page = ChatPage(chats = listOf(row(3, changed = 0, pinned = true)) + rows(1..2) + rows(4..50), more = true)
|
||||
val read = shown.withNewest(page)
|
||||
assertEquals(70, read.chats.size)
|
||||
assertEquals(70, read.chats.map { it.id }.toSet().size)
|
||||
assertTrue(read.chats.first { it.id == "c60" }.pinned)
|
||||
assertTrue(read.chats.first { it.id == "c3" }.pinned)
|
||||
assertEquals("c3", read.chats.first().id)
|
||||
assertTrue(read.more)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aChatDeletedElsewhereGoesFromTheList() {
|
||||
val shown = ChatsState(chats = rows(1..70), more = true)
|
||||
// c7 is gone on the server: the page reaches one chat further down instead.
|
||||
val page = ChatPage(chats = rows(1..6) + rows(8..51), more = true)
|
||||
val read = shown.withNewest(page)
|
||||
assertFalse(read.chats.any { it.id == "c7" })
|
||||
// What lies below the page was not looked at, and stays.
|
||||
assertEquals((1..6).map { "c$it" } + (8..70).map { "c$it" }, read.chats.map { it.id })
|
||||
// A page with nothing after it is the whole list: whatever it does not name is gone.
|
||||
val whole = shown.withNewest(ChatPage(chats = rows(1..3), more = false))
|
||||
assertEquals(listOf("c1", "c2", "c3"), whole.chats.map { it.id })
|
||||
assertFalse(whole.more)
|
||||
// A row with no time the app can read is never taken for gone.
|
||||
val undated = ChatsState(chats = rows(1..50) + Chat(id = "x", updatedAt = "yesterday"), more = true)
|
||||
assertEquals("x", undated.withNewest(ChatPage(chats = rows(1..50), more = true)).chats.last().id)
|
||||
}
|
||||
|
||||
// --- A reply nobody asked for, and the gate ---------------------------------------------------
|
||||
|
||||
private class Door {
|
||||
var locked = false
|
||||
val gate = InstanceGate { locked }.also { it.activityStarted() }
|
||||
|
||||
fun lock() {
|
||||
locked = true
|
||||
gate.look()
|
||||
}
|
||||
|
||||
fun unlock() {
|
||||
locked = false
|
||||
gate.look()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aReplyNobodyAskedForIsLetGoWhenThePhoneLocks() = runTest {
|
||||
val door = Door()
|
||||
var open = false
|
||||
val following = async {
|
||||
door.gate.whileOpen<String> {
|
||||
open = true
|
||||
try {
|
||||
awaitCancellation()
|
||||
} finally {
|
||||
open = false
|
||||
}
|
||||
}
|
||||
}
|
||||
runCurrent()
|
||||
assertTrue(open)
|
||||
door.lock()
|
||||
runCurrent()
|
||||
// Let go: its stream is closed, and the answer says so.
|
||||
assertFalse(open)
|
||||
assertNull(following.await())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aReplyThatEndsInFrontIsFollowedToItsEnd() = runTest {
|
||||
val door = Door()
|
||||
assertEquals("done", door.gate.whileOpen { "done" })
|
||||
// The app leaving the front is the gate closing as well.
|
||||
door.gate.activityStopped()
|
||||
var started = false
|
||||
assertNull(
|
||||
door.gate.whileOpen {
|
||||
started = true
|
||||
"done"
|
||||
},
|
||||
)
|
||||
// Behind the gate nothing nobody asked for is even started.
|
||||
assertFalse(started)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun thePersonsOwnReplyGoesOnBehindTheLock() = runTest {
|
||||
val door = Door()
|
||||
val end = CompletableDeferred<String>()
|
||||
var own = true
|
||||
val following = async { door.gate.whileOpen(stays = { own }) { end.await() } }
|
||||
runCurrent()
|
||||
door.lock()
|
||||
runCurrent()
|
||||
assertTrue(following.isActive)
|
||||
end.complete("done")
|
||||
assertEquals("done", following.await())
|
||||
// One that became the person's while it ran (they asked, the events route was first) stays too;
|
||||
// one that is not theirs goes at the next closing.
|
||||
own = false
|
||||
door.unlock()
|
||||
val other = async { door.gate.whileOpen<String>(stays = { own }) { awaitCancellation() } }
|
||||
runCurrent()
|
||||
door.lock()
|
||||
runCurrent()
|
||||
assertNull(other.await())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFollowThatIsCancelledIsNotTakenForOneLetGo() = runTest {
|
||||
val door = Door()
|
||||
var after = false
|
||||
val following = launch {
|
||||
door.gate.whileOpen<String> { awaitCancellation() }
|
||||
after = true
|
||||
}
|
||||
runCurrent()
|
||||
following.cancelAndJoin()
|
||||
// The caller's own end: nothing of "let go, read again on the return" runs.
|
||||
assertFalse(after)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aBrokenStreamIsOpenedAgainOnlyAtItsTurn() = runTest {
|
||||
val door = Door()
|
||||
var opened = 0
|
||||
val frames = mutableListOf<Frame>()
|
||||
val following = launch {
|
||||
reopened(turn = { door.gate.pass() }) {
|
||||
opened++
|
||||
if (opened == 1) flowOf(Outcome.Event(Frame("tail", "{}")), Outcome.Dropped) else flowOf(Outcome.Event(Frame("close", "{}")))
|
||||
}.toList(frames)
|
||||
}
|
||||
runCurrent()
|
||||
assertEquals(1, opened)
|
||||
// The connection broke and the phone is locked: an hour later nothing has been asked.
|
||||
door.lock()
|
||||
advanceTimeBy(3_600_000)
|
||||
assertEquals(1, opened)
|
||||
door.unlock()
|
||||
advanceUntilIdle()
|
||||
assertEquals(2, opened)
|
||||
assertEquals(listOf("tail", "close"), frames.map { it.event })
|
||||
assertTrue(following.isCompleted)
|
||||
}
|
||||
|
||||
// --- A transcript left open ------------------------------------------------------------------
|
||||
|
||||
private fun person(id: String) = Message(id = id, role = "user", text = "How many cakes are left?")
|
||||
|
||||
private fun reply(id: String, complete: Boolean = true) = Message(
|
||||
id = id,
|
||||
role = "assistant",
|
||||
complete = complete,
|
||||
steps = if (complete) listOf(Step(index = 0, kind = "text", markdown = "Seven.")) else emptyList(),
|
||||
)
|
||||
|
||||
private fun note(id: String) = Message(id = id, role = "user", machine = true, origin = "harness", text = "The baker has finished.")
|
||||
|
||||
private val chat = Chat(id = "chat1")
|
||||
|
||||
private fun talk(range: IntRange) = range.map { if (it % 2 == 1) person("m$it") else reply("m$it") }
|
||||
|
||||
@Test
|
||||
fun aLongTranscriptIsCutBackOnlyUnderAPersonAtItsEnd() {
|
||||
val long = ChatState(chat = chat, messages = talk(1..KEPT_MOST + 2), more = false)
|
||||
val cut = long.capped(atEnd = true)
|
||||
assertEquals(KEPT_ROWS, cut.messages.size)
|
||||
// The newest stay, and "older" reads the rest back.
|
||||
assertEquals("m${KEPT_MOST + 2}", cut.messages.last().id)
|
||||
assertEquals("m${KEPT_MOST + 2 - KEPT_ROWS + 1}", cut.messages.first().id)
|
||||
assertTrue(cut.more)
|
||||
// Somebody reading further up keeps every row.
|
||||
assertSame(long, long.capped(atEnd = false))
|
||||
// Under the limit nothing goes, so it is not cut at every read.
|
||||
val fits = ChatState(chat = chat, messages = talk(1..KEPT_MOST))
|
||||
assertSame(fits, fits.capped(atEnd = true))
|
||||
// The list keeps its rows by their ids: to it this is rows changed in place, and it stays at its end.
|
||||
assertEquals(TranscriptChange.None, transcriptChange(cut.messages, cut.messages))
|
||||
assertEquals(TranscriptChange.Changed, transcriptChange(long.messages, cut.messages))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRewindElsewhereLeavesNoRowTheServerNoLongerHas() {
|
||||
// 120 rows shown, of which the last 50 were the newest page. From another client the
|
||||
// chat is rewound to row 60 and answered again: 61..120 are gone, n1 and n2 are new.
|
||||
val shown = ChatState(chat = chat, messages = talk(1..120), more = true)
|
||||
val after = talk(13..60) + person("n1") + reply("n2")
|
||||
val read = shown.withNewest(ChatDetail(chat = chat, messages = after, more = true))
|
||||
// The page joins at m13: what is above it is older than anything a rewind that left m13 could touch.
|
||||
assertEquals(talk(1..12).map { it.id } + after.map { it.id }, read.messages.map { it.id })
|
||||
// Rewound to above everything the page holds: the page joins nothing here and is the transcript.
|
||||
val far = listOf(person("x1"), reply("x2"))
|
||||
assertEquals(far, shown.withNewest(ChatDetail(chat = chat, messages = far, more = false)).messages)
|
||||
}
|
||||
|
||||
// --- Whose scroll it is ------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun aListThePersonIsScrollingIsNotMovedWhenRowsArrive() {
|
||||
// A wheel, a key or a screen reader moving the list: no finger, so the following has not
|
||||
// ended yet -- and rows that arrive now must not cancel that scroll.
|
||||
val wheel = personScrolls(inProgress = true, ownScrolls = 0)
|
||||
assertTrue(wheel)
|
||||
assertFalse(movesToEnd(TranscriptChange.Appended, following = true, personScrolling = wheel))
|
||||
assertFalse(movesToEnd(TranscriptChange.Changed, following = true, personScrolling = wheel))
|
||||
// A message the person sends, and a chat opened, still show.
|
||||
assertTrue(movesToEnd(TranscriptChange.Sent, following = false, personScrolling = wheel))
|
||||
assertTrue(movesToEnd(TranscriptChange.Opened, following = false, personScrolling = wheel))
|
||||
// The app's own scroll to the end, still under way when more arrives, is not the person's.
|
||||
assertFalse(personScrolls(inProgress = true, ownScrolls = 1))
|
||||
assertTrue(movesToEnd(TranscriptChange.Appended, following = true, personScrolling = false))
|
||||
// A list at rest is nobody's scroll.
|
||||
assertFalse(personScrolls(inProgress = false, ownScrolls = 0))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aScrollTheAppDidNotStartIsThePersonsWhereItRests() {
|
||||
// Not a finger and not (by where it rests) a move back -- but nothing of the app's started it.
|
||||
assertTrue(scrollWasPersons(touched = false, wentBack = false, startedByApp = false))
|
||||
assertFalse(
|
||||
restFollows(following = true, byPerson = scrollWasPersons(touched = false, wentBack = false, startedByApp = false), distance = 900, slack = 48),
|
||||
)
|
||||
// The app's own, left short of the end by a line that arrived: nobody left.
|
||||
assertFalse(scrollWasPersons(touched = false, wentBack = false, startedByApp = true))
|
||||
assertTrue(restFollows(following = true, byPerson = false, distance = 900, slack = 48))
|
||||
// A finger or a move back on a scroll the app started is still the person's.
|
||||
assertTrue(scrollWasPersons(touched = true, wentBack = false, startedByApp = true))
|
||||
assertTrue(scrollWasPersons(touched = false, wentBack = true, startedByApp = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theAppsOwnScrollsAreCountedWhileTheyRun() = runTest {
|
||||
val own = intArrayOf(0)
|
||||
val first = launch { ownScroll(own) { awaitCancellation() } }
|
||||
val second = launch { ownScroll(own) { awaitCancellation() } }
|
||||
runCurrent()
|
||||
assertEquals(2, own[0])
|
||||
// One overtaken by the other: its end does not unmark the one still running.
|
||||
first.cancelAndJoin()
|
||||
assertEquals(1, own[0])
|
||||
assertFalse(personScrolls(inProgress = true, ownScrolls = own[0]))
|
||||
second.cancelAndJoin()
|
||||
assertEquals(0, own[0])
|
||||
}
|
||||
|
||||
// --- The drawer's list and the replies' frames -----------------------------------------------
|
||||
|
||||
private fun said(chatId: String, message: String = "r1", live: Boolean = true) = ReplyFrame(chatId = chatId, messageId = message, live = live)
|
||||
|
||||
@Test
|
||||
fun theListIsReadOnlyWhenItIsSeenAndOnlyForWhatItDoesNotShow() {
|
||||
val list = ChatsState(chats = listOf(row(1, running = true), row(2)), more = false)
|
||||
// The drawer is closed: it reads the list when it opens, and nothing before.
|
||||
assertFalse(list.readsFor(said("c2"), shown = false))
|
||||
// Open: a reply started in a chat not shown as running, or in one not listed yet.
|
||||
assertTrue(list.readsFor(said("c2"), shown = true))
|
||||
assertTrue(list.readsFor(said("c9"), shown = true))
|
||||
// The route says every reply being written again at each reconnection: that row runs already.
|
||||
assertFalse(list.readsFor(said("c1"), shown = true))
|
||||
// An end in a listed chat is marked on its row; one in a chat not listed is read.
|
||||
assertFalse(list.readsFor(said("c1", live = false), shown = true))
|
||||
assertTrue(list.readsFor(said("c9", live = false), shown = true))
|
||||
// A list not read yet is left to its first read.
|
||||
assertFalse(ChatsState().readsFor(said("c1"), shown = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aReplysEndClearsTheRunningMarkAndShowsSomethingNewWithoutARead() {
|
||||
val list = ChatsState(chats = listOf(row(1, running = true), row(2, running = true), row(3)), more = false)
|
||||
val ended = list.ended(said("c1", live = false), open = "c2")
|
||||
assertFalse(ended.chats[0].running)
|
||||
assertTrue(ended.chats[0].unread)
|
||||
// The others are as they were.
|
||||
assertEquals(list.chats.drop(1), ended.chats.drop(1))
|
||||
// The chat on screen: the person watched it end, so nothing is new.
|
||||
val watched = list.ended(said("c2", live = false), open = "c2")
|
||||
assertFalse(watched.chats[1].running)
|
||||
assertFalse(watched.chats[1].unread)
|
||||
// A start is not an end, and a chat not listed changes nothing.
|
||||
assertSame(list, list.ended(said("c1"), open = null))
|
||||
assertSame(list, list.ended(said("c9", live = false), open = null))
|
||||
}
|
||||
|
||||
private fun fixture(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) {
|
||||
"contract/$name.json is missing"
|
||||
}.readText()
|
||||
|
||||
@Test
|
||||
fun theEndFrameIsReadAsTheServerWritesItAndDoesWhatAnEndDoes() {
|
||||
val start = LembasJson.decodeFromString(ReplyFrame.serializer(), fixture("event_reply"))
|
||||
val end = LembasJson.decodeFromString(ReplyFrame.serializer(), fixture("event_reply_end"))
|
||||
// The same reply, said twice: once being written, once over.
|
||||
assertEquals(ReplyFrame(chatId = start.chatId, messageId = start.messageId, live = false), end)
|
||||
assertTrue(start.live)
|
||||
val list = ChatsState(chats = listOf(Chat(id = end.chatId, running = true)), more = false)
|
||||
// No read for it, the mark gone, something new.
|
||||
assertFalse(list.readsFor(end, shown = true))
|
||||
assertEquals(listOf(Chat(id = end.chatId, running = false, unread = true)), list.ended(end, open = null).chats)
|
||||
// The pair is the proof that this instance says the ends.
|
||||
val ends = ReplyEnds()
|
||||
ends.hear(start)
|
||||
ends.hear(end)
|
||||
assertTrue(ends.said)
|
||||
// For the chat on screen that followed the reply, it is no news.
|
||||
val open = ChatState(chat = Chat(id = end.chatId), messages = listOf(reply(end.messageId, complete = false)), live = LiveReply(end.messageId))
|
||||
assertFalse(open.asksFor(end))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aMessageWhoseArrivalIsUnknownSaysSoAndNotThatItWaitsItsTurn() {
|
||||
val unsure = Message(id = "q1", role = "user", text = "And the bread?", queued = true, origin = "unsure")
|
||||
assertTrue(unsure.fateUnknown)
|
||||
// Still the person's own bubble.
|
||||
assertEquals(Drawn.Person, drawn(unsure, first = false, reportChat = false))
|
||||
// Once sent it is a turn like any other; a queued prompt is only queued; a reply is never this.
|
||||
assertFalse(unsure.copy(queued = false, origin = "").fateUnknown)
|
||||
assertFalse(unsure.copy(origin = "").fateUnknown)
|
||||
assertFalse(unsure.copy(role = "assistant").fateUnknown)
|
||||
// An origin this app does not know is drawn as none.
|
||||
assertEquals(Drawn.Person, drawn(unsure.copy(queued = false, origin = "somewhere"), first = false, reportChat = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anInstanceProvesItSaysTheEndsWithOneEndOfAReplyItSaidStarted() {
|
||||
val ends = ReplyEnds()
|
||||
// "Already ended" at the start, which instances before the end frame say too, proves nothing.
|
||||
ends.hear(said("c1", "r0", live = false))
|
||||
assertFalse(ends.said)
|
||||
ends.hear(said("c1", "r1"))
|
||||
assertFalse(ends.said)
|
||||
ends.hear(said("c1", "r1", live = false))
|
||||
assertTrue(ends.said)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRunningRowIsReadAgainAtABoundedRate() {
|
||||
assertEquals(listOf(5_000L, 10_000L, 20_000L, 40_000L, 60_000L, 60_000L), (0..5).map { runningPause(it) })
|
||||
assertEquals(60_000L, runningPause(1_000))
|
||||
assertEquals(5_000L, runningPause(-1))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun framesThatNeverFallQuietStillGetTheirRead() = runTest {
|
||||
var reads = 0
|
||||
val soon = Soon(backgroundScope, pause = 1_500, most = 6_000) { reads++ }
|
||||
// A team: a reply starts every second, for nineteen seconds.
|
||||
repeat(19) {
|
||||
soon.ask()
|
||||
advanceTimeBy(1_000)
|
||||
}
|
||||
runCurrent()
|
||||
// At the latest six seconds after the first asking, and again six after the next: never "not until it is quiet".
|
||||
assertEquals(2, reads)
|
||||
// And once more when it has fallen quiet.
|
||||
advanceTimeBy(1_600)
|
||||
runCurrent()
|
||||
assertEquals(3, reads)
|
||||
// Nothing asked, nothing read.
|
||||
advanceTimeBy(60_000)
|
||||
assertEquals(3, reads)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun askingsCloseTogetherAreOneRead() = runTest {
|
||||
var reads = 0
|
||||
val soon = Soon(backgroundScope, pause = 1_500, most = 6_000) { reads++ }
|
||||
repeat(5) {
|
||||
soon.ask()
|
||||
advanceTimeBy(200)
|
||||
}
|
||||
assertEquals(0, reads)
|
||||
advanceTimeBy(1_500)
|
||||
runCurrent()
|
||||
assertEquals(1, reads)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aReadUnderWayIsNotCutShortByTheNextFrame() = runTest {
|
||||
var began = 0
|
||||
var finished = 0
|
||||
val soon = Soon(backgroundScope, pause = 1_500, most = 6_000) {
|
||||
began++
|
||||
delay(5_000)
|
||||
finished++
|
||||
}
|
||||
soon.ask()
|
||||
advanceTimeBy(1_600)
|
||||
assertEquals(1, began)
|
||||
// Frames while the list is being read: that read finishes, and one more follows it.
|
||||
soon.ask()
|
||||
advanceTimeBy(1_000)
|
||||
soon.ask()
|
||||
advanceTimeBy(4_100)
|
||||
assertEquals(1, finished)
|
||||
advanceTimeBy(1_600)
|
||||
assertEquals(2, began)
|
||||
advanceTimeBy(5_100)
|
||||
assertEquals(2, finished)
|
||||
advanceTimeBy(60_000)
|
||||
assertEquals(2, began)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whatIsAskedWhileAReadWaitsForItsTurnIsThatRead() = runTest {
|
||||
val turn = CompletableDeferred<Unit>()
|
||||
var reads = 0
|
||||
val soon = Soon(backgroundScope, pause = 1_500, most = 6_000, before = { turn.await() }) { reads++ }
|
||||
soon.ask()
|
||||
advanceTimeBy(1_600)
|
||||
// Waiting at the gate (the phone is locked): more is heard meanwhile.
|
||||
soon.ask()
|
||||
soon.ask()
|
||||
turn.complete(Unit)
|
||||
advanceTimeBy(60_000)
|
||||
// One read on the return, not one per frame and not two.
|
||||
assertEquals(1, reads)
|
||||
// The drawer closed before the pause was over: nothing is read for it.
|
||||
soon.ask()
|
||||
soon.forget()
|
||||
advanceTimeBy(60_000)
|
||||
assertEquals(1, reads)
|
||||
}
|
||||
|
||||
// --- A reply's end, and one news read once -----------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun theEndOfAReplyThisScreenFollowsOrHasDrawnAsksForNoRead() {
|
||||
val following = ChatState(chat = chat, messages = listOf(person("q1"), reply("a1", complete = false)), live = LiveReply("a1"))
|
||||
// The stream's own `done` brings the end: the events route's word for it costs nothing.
|
||||
assertFalse(following.asksFor(said("chat1", "a1", live = false)))
|
||||
val drawn = ChatState(chat = chat, messages = listOf(person("q1"), reply("a1")))
|
||||
assertFalse(drawn.asksFor(said("chat1", "a1", live = false)))
|
||||
// The end of a reply this screen never heard of (it was shorter than the news of it) is read once.
|
||||
assertTrue(drawn.asksFor(said("chat1", "a2", live = false)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aBurstOfNewsIsOneRead() = runTest {
|
||||
val reads = Reads()
|
||||
var made = 0
|
||||
val answer = CompletableDeferred<Unit>()
|
||||
// Five frames before anything was read.
|
||||
val asked = List(5) { reads.mark() }.map { mark ->
|
||||
launch {
|
||||
reads.since(mark) {
|
||||
made++
|
||||
answer.await()
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
runCurrent()
|
||||
assertEquals(1, made)
|
||||
// News that arrives while that read is under way is newer than it.
|
||||
val later = reads.mark()
|
||||
answer.complete(Unit)
|
||||
advanceUntilIdle()
|
||||
assertTrue(asked.all { it.isCompleted })
|
||||
assertEquals(1, made)
|
||||
assertTrue(reads.since(later) { true })
|
||||
// And what was learned before a read that has answered is not read again.
|
||||
assertFalse(reads.since(0) { true })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aReadThatFailedStandsForNobodyAndOneNoLongerWantedIsNotMade() = runTest {
|
||||
val reads = Reads()
|
||||
val first = reads.mark()
|
||||
val second = reads.mark()
|
||||
assertTrue(reads.since(first) { false })
|
||||
// The first one's read got no answer: the second still makes its own.
|
||||
var made = false
|
||||
assertTrue(
|
||||
reads.since(second) {
|
||||
made = true
|
||||
true
|
||||
},
|
||||
)
|
||||
assertTrue(made)
|
||||
// Asked again when its turn comes: no longer news, no read.
|
||||
assertFalse(reads.since(reads.mark(), wanted = { false }) { error("not made") })
|
||||
}
|
||||
|
||||
// --- The line that says a reply was not recorded -----------------------------------------------
|
||||
|
||||
@Test
|
||||
fun aReplyThatHoldsOnlyAPlanWasRecorded() {
|
||||
val empty = Message(id = "a1", role = "assistant")
|
||||
assertTrue(replyUnrecorded(empty, note("n1")))
|
||||
val plan = empty.copy(plan = JsonObject(mapOf("title" to JsonPrimitive("Bake more"))))
|
||||
assertFalse(replyUnrecorded(plan, note("n1")))
|
||||
assertEquals(emptySet<String>(), unrecordedReplies(listOf(note("n1"), plan)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theReplyBeingWrittenIsNeverNotRecordedWhateverItsRowSays() {
|
||||
// A row that says nothing of `complete` reads as complete; the screen knows better.
|
||||
val row = Message(id = "a1", role = "assistant")
|
||||
assertFalse(replyUnrecorded(row, note("n1"), live = "a1"))
|
||||
assertEquals(emptySet<String>(), unrecordedReplies(listOf(note("n1"), row), live = "a1"))
|
||||
// Once it has ended, or for another row, the rule is as it was.
|
||||
assertEquals(setOf("a1"), unrecordedReplies(listOf(note("n1"), row), live = "a9"))
|
||||
assertEquals(setOf("a1"), unrecordedReplies(listOf(note("n1"), row)))
|
||||
}
|
||||
|
||||
// --- The Scheduled list ------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun theScheduledListListensOnlyWhileItIsInFront() {
|
||||
assertTrue(listens(inFront = true, listening = false))
|
||||
// A read that comes back after the screen was left opens nothing.
|
||||
assertFalse(listens(inFront = false, listening = false))
|
||||
assertFalse(listens(inFront = true, listening = true))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.ChatDetail
|
||||
import eu.llembas.android.api.Discarded
|
||||
import eu.llembas.android.api.Drawn
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.Turn
|
||||
import eu.llembas.android.api.Waiting
|
||||
import eu.llembas.android.api.drawn
|
||||
import eu.llembas.android.api.editable
|
||||
import eu.llembas.android.api.fateUnknown
|
||||
import eu.llembas.android.api.waiting
|
||||
import eu.llembas.android.ui.chat.ChatState
|
||||
import eu.llembas.android.ui.chat.Followed
|
||||
import eu.llembas.android.ui.chat.WaitingActions
|
||||
import eu.llembas.android.ui.chat.discarded
|
||||
import eu.llembas.android.ui.chat.followedAfterSend
|
||||
import eu.llembas.android.ui.chat.sentNow
|
||||
import eu.llembas.android.ui.chat.staleWaiting
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.test.runCurrent
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Test
|
||||
import java.net.ConnectException
|
||||
|
||||
/**
|
||||
* A message that waits (`queued`: behind a reply, of unknown arrival at a linked computer, or
|
||||
* held by it) and the two things its person does with it: read as the server writes it
|
||||
* (`contract/message_unsure.json`, `message_carried.json`, `message_sent_now.json`,
|
||||
* `message_discarded.json`), sent now and its reply followed, discarded and gone, and refused
|
||||
* in the instance's own words with the chat read again.
|
||||
*/
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class WaitingMessageTest {
|
||||
private fun fixture(name: String): String =
|
||||
requireNotNull(javaClass.classLoader!!.getResource("$name.json")) { "contract/$name.json is missing" }.readText()
|
||||
|
||||
private fun message(name: String) = LembasJson.decodeFromString(Message.serializer(), fixture(name))
|
||||
|
||||
private fun person(id: String, queued: Boolean = false, origin: String = "") =
|
||||
Message(id = id, role = "user", text = "And the bread?", queued = queued, origin = origin)
|
||||
|
||||
private fun reply(id: String, complete: Boolean = true) = Message(
|
||||
id = id,
|
||||
role = "assistant",
|
||||
complete = complete,
|
||||
steps = if (complete) listOf(Step(index = 0, kind = "text", markdown = "Seven.")) else emptyList(),
|
||||
)
|
||||
|
||||
private val chat = Chat(id = "chat1")
|
||||
|
||||
// --- The fixtures -----------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun aWaitingMessageSaysHowItWaitsAsTheServerWritesIt() {
|
||||
val queued = message("message_queued")
|
||||
val unsure = message("message_unsure")
|
||||
val carried = message("message_carried")
|
||||
assertEquals(Waiting.Queued, queued.waiting)
|
||||
assertEquals(Waiting.Unsure, unsure.waiting)
|
||||
assertEquals(Waiting.Carried, carried.waiting)
|
||||
// Each is the person's own bubble, waiting, with its words.
|
||||
for (waits in listOf(queued, unsure, carried)) {
|
||||
assertTrue(waits.isUser && waits.queued)
|
||||
assertEquals("And the leaves?", waits.text)
|
||||
assertEquals(Drawn.Person, drawn(waits, first = false, reportChat = false))
|
||||
}
|
||||
// Only the one whose arrival nobody heard of is drawn as a warning.
|
||||
assertTrue(unsure.fateUnknown)
|
||||
assertFalse(carried.fateUnknown)
|
||||
assertFalse(queued.fateUnknown)
|
||||
// The queue's place is the plain queued one's alone.
|
||||
assertEquals(2, queued.progress?.ahead)
|
||||
assertNull(unsure.progress?.ahead)
|
||||
assertNull(carried.progress?.ahead)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onlyAPersonsQueuedMessageWaits() {
|
||||
// Sent, it is a turn like any other; a reply never waits, whatever its row says.
|
||||
assertNull(person("q1").waiting)
|
||||
assertNull(person("q1", origin = "carried").waiting)
|
||||
assertNull(reply("a1").copy(queued = true).waiting)
|
||||
// An origin this app does not know waits as a plain queued message does.
|
||||
assertEquals(Waiting.Queued, person("q1", queued = true, origin = "somewhere").waiting)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aWaitingMessageIsNeverOfferedEdit() {
|
||||
for (name in listOf("message_queued", "message_unsure", "message_carried")) {
|
||||
assertFalse(name, message(name).editable(writing = false))
|
||||
}
|
||||
// A delivered one is, while nothing is being written; a reply never.
|
||||
assertTrue(person("q1").editable(writing = false))
|
||||
assertFalse(person("q1").editable(writing = true))
|
||||
assertFalse(reply("a1").editable(writing = false))
|
||||
// The message a send-now answers with has stopped waiting.
|
||||
val sent = LembasJson.decodeFromString(Turn.serializer(), fixture("message_sent_now"))
|
||||
assertTrue(requireNotNull(sent.message).editable(writing = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theAnswersToSendNowAndDiscardAreReadAsTheServerWritesThem() {
|
||||
val sent = LembasJson.decodeFromString(Turn.serializer(), fixture("message_sent_now"))
|
||||
val message = requireNotNull(sent.message)
|
||||
val started = requireNotNull(sent.reply)
|
||||
assertEquals("msg1", message.id)
|
||||
assertFalse(message.queued)
|
||||
assertEquals("", message.origin)
|
||||
assertNull(message.waiting)
|
||||
assertNull(message.progress)
|
||||
// The reply started for it: the model's, not finished, nothing written yet.
|
||||
assertEquals("msg4", started.id)
|
||||
assertFalse(started.isUser)
|
||||
assertFalse(started.complete)
|
||||
assertTrue(started.steps.isEmpty())
|
||||
|
||||
assertEquals(Discarded(id = "msg3", discarded = true), LembasJson.decodeFromString(Discarded.serializer(), fixture("message_discarded")))
|
||||
}
|
||||
|
||||
// --- The two requests -------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun sendNowAndDiscardAreTheMessagesOwnRoutes() = runTest {
|
||||
val server = MockWebServer().apply { start() }
|
||||
try {
|
||||
val api = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test")
|
||||
server.enqueue(MockResponse().setBody(fixture("message_sent_now")))
|
||||
server.enqueue(MockResponse().setBody(fixture("message_discarded")))
|
||||
server.enqueue(MockResponse().setResponseCode(409).setBody("""{"detail":"Wait for the current reply to finish, or stop it."}"""))
|
||||
server.enqueue(MockResponse().setResponseCode(404).setBody("""{"detail":"That message is not waiting to be sent."}"""))
|
||||
|
||||
assertEquals("msg4", api.sendWaiting("chat1", "msg1").reply?.id)
|
||||
val send = server.takeRequest()
|
||||
assertEquals("POST", send.method)
|
||||
assertEquals("/api/v2/chats/chat1/messages/msg1/send", send.path)
|
||||
assertEquals("Bearer lmb_test", send.getHeader("Authorization"))
|
||||
// It starts a reply, so it says what this app can do, as a message does.
|
||||
assertTrue(send.body.readUtf8().contains("\"client\":[\"phone_actions\"]"))
|
||||
|
||||
assertTrue(api.discardWaiting("chat1", "msg3").discarded)
|
||||
val discard = server.takeRequest()
|
||||
assertEquals("POST", discard.method)
|
||||
assertEquals("/api/v2/chats/chat1/messages/msg3/discard", discard.path)
|
||||
|
||||
// A refusal is the instance's own sentence, with its status.
|
||||
try {
|
||||
api.sendWaiting("chat1", "msg1")
|
||||
fail("a 409 must throw")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals(409, e.status)
|
||||
assertEquals("Wait for the current reply to finish, or stop it.", e.message)
|
||||
}
|
||||
try {
|
||||
api.discardWaiting("chat1", "msg3")
|
||||
fail("a 404 must throw")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals(404, e.status)
|
||||
assertEquals("That message is not waiting to be sent.", e.message)
|
||||
}
|
||||
} finally {
|
||||
server.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
// --- What the transcript becomes ---------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun aMessageSentNowStopsWaitingWhereItStoodAndItsReplyIsTheLastRow() {
|
||||
val shown = ChatState(
|
||||
chat = chat,
|
||||
messages = listOf(person("q1"), reply("a1"), person("w1", queued = true, origin = "unsure"), person("w2", queued = true)),
|
||||
)
|
||||
val turn = Turn(message = person("w1"), reply = reply("a2", complete = false))
|
||||
val after = shown.sentNow(turn)
|
||||
assertEquals(listOf("q1", "a1", "w1", "w2", "a2"), after.messages.map { it.id })
|
||||
assertNull(after.messages[2].waiting)
|
||||
// The other waiting message still waits.
|
||||
assertEquals(Waiting.Queued, after.messages[3].waiting)
|
||||
assertEquals("w1", after.lastSent)
|
||||
// Told twice (the answer, then the same rows from a read): no row is there twice.
|
||||
assertEquals(after.messages.map { it.id }, after.sentNow(turn).messages.map { it.id })
|
||||
// An answer that names no reply changes the message alone.
|
||||
assertEquals(listOf("q1", "a1", "w1", "w2"), shown.sentNow(Turn(message = person("w1"))).messages.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aDiscardedMessageIsGoneAndNothingElseMoves() {
|
||||
val shown = ChatState(chat = chat, messages = listOf(person("q1"), reply("a1"), person("w1", queued = true), person("w2", queued = true)), more = true)
|
||||
val after = shown.discarded("w1")
|
||||
assertEquals(listOf("q1", "a1", "w2"), after.messages.map { it.id })
|
||||
assertTrue(after.more)
|
||||
// One that is not shown (any more): nothing to take away.
|
||||
assertEquals(after, after.discarded("w1"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theReplyASendStartedIsFollowedAsThePersonsOwnUnlessTheChatNoLongerHoldsIt() {
|
||||
val message = person("w1")
|
||||
val started = reply("a2", complete = false)
|
||||
// The read could not be made: the answer's word stands.
|
||||
assertEquals(Followed("a2", own = true), followedAfterSend("a2", null))
|
||||
// The read says it is being written, by `live` or by its row.
|
||||
assertEquals(Followed("a2", own = true), followedAfterSend("a2", ChatDetail(chat = chat, messages = listOf(message, started), live = "a2")))
|
||||
assertEquals(Followed("a2", own = true), followedAfterSend("a2", ChatDetail(chat = chat, messages = listOf(message, started))))
|
||||
// A linked computer that still knew the message did not run it again: the reply's row is
|
||||
// gone, and there is nothing to follow -- or only what else is being written, as nobody's.
|
||||
assertNull(followedAfterSend("a2", ChatDetail(chat = chat, messages = listOf(person("w1", queued = true, origin = "carried")))))
|
||||
assertEquals(
|
||||
Followed("a9", own = false),
|
||||
followedAfterSend("a2", ChatDetail(chat = chat, messages = listOf(message, reply("a9", complete = false)), live = "a9")),
|
||||
)
|
||||
// Already finished by the time it was read: drawn from the read, not followed.
|
||||
assertNull(followedAfterSend("a2", ChatDetail(chat = chat, messages = listOf(message, reply("a2")))))
|
||||
// An answer without a reply follows whatever the read says is live.
|
||||
assertNull(followedAfterSend(null, null))
|
||||
assertEquals(Followed("a9", own = false), followedAfterSend(null, ChatDetail(chat = chat, live = "a9")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onlyARefusalAboutTheMessageAsksForTheChatAgain() {
|
||||
assertTrue(staleWaiting(ApiException(409, "Wait for the current reply to finish, or stop it.")))
|
||||
assertTrue(staleWaiting(ApiException(409, "That message is not waiting to be sent.")))
|
||||
assertTrue(staleWaiting(ApiException(404, "That message is not waiting to be sent.")))
|
||||
// A server that failed, or one out of reach, says nothing about the message.
|
||||
assertFalse(staleWaiting(ApiException(500, "Something went wrong.")))
|
||||
assertFalse(staleWaiting(ConnectException("refused")))
|
||||
}
|
||||
|
||||
// --- The actions, as the screen does them -------------------------------------------------------
|
||||
|
||||
/** The screen's side of the two actions, recorded: what was read, followed and said. */
|
||||
private class Screen(start: ChatState, private val server: ChatDetail? = null) {
|
||||
val state = MutableStateFlow(start)
|
||||
val followed = mutableListOf<Followed>()
|
||||
val said = mutableListOf<String>()
|
||||
var reads = 0
|
||||
var catchUps = 0
|
||||
|
||||
/** What the buttons were when the chat was read again after a refusal. */
|
||||
var actingAtCatchUp: String? = "never"
|
||||
|
||||
val actions = WaitingActions(
|
||||
state = state,
|
||||
read = {
|
||||
reads++
|
||||
server
|
||||
},
|
||||
follow = { followed += it },
|
||||
say = { said += it.message.orEmpty() },
|
||||
catchUp = {
|
||||
catchUps++
|
||||
actingAtCatchUp = state.value.acting
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private val waitingChat = ChatState(chat = chat, messages = listOf(person("q1"), reply("a1"), person("w1", queued = true, origin = "unsure")))
|
||||
|
||||
@Test
|
||||
fun sendNowStartsAReplyThatIsFollowedAsOneThePersonAskedFor() = runTest {
|
||||
val turn = Turn(message = person("w1"), reply = reply("a2", complete = false))
|
||||
val screen =
|
||||
Screen(
|
||||
waitingChat,
|
||||
server = ChatDetail(chat = chat, messages = listOf(person("q1"), reply("a1"), person("w1"), reply("a2", complete = false)), live = "a2"),
|
||||
)
|
||||
screen.actions.sendNow(waitingChat.messages.last()) { turn }
|
||||
// The row no longer waits, the reply is there, and it is followed as the person's own.
|
||||
assertEquals(listOf("q1", "a1", "w1", "a2"), screen.state.value.messages.map { it.id })
|
||||
assertNull(screen.state.value.messages[2].waiting)
|
||||
assertEquals(listOf(Followed("a2", own = true)), screen.followed)
|
||||
// The chat was read once (a linked computer's chat sorts the message to where it was sent).
|
||||
assertEquals(1, screen.reads)
|
||||
assertTrue(screen.said.isEmpty())
|
||||
assertEquals(0, screen.catchUps)
|
||||
assertNull(screen.state.value.acting)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theButtonsRestWhileTheInstanceIsAskedAndASecondTapIsNoSecondRequest() = runTest {
|
||||
val screen = Screen(waitingChat)
|
||||
val answer = CompletableDeferred<Turn>()
|
||||
var asked = 0
|
||||
val first = launch {
|
||||
screen.actions.sendNow(waitingChat.messages.last()) {
|
||||
asked++
|
||||
answer.await()
|
||||
}
|
||||
}
|
||||
runCurrent()
|
||||
assertEquals("w1", screen.state.value.acting)
|
||||
// A second tap, on either button, while the first is under way: nothing is asked.
|
||||
screen.actions.sendNow(waitingChat.messages.last()) {
|
||||
asked++
|
||||
Turn()
|
||||
}
|
||||
screen.actions.discard(waitingChat.messages.last()) { asked++ }
|
||||
assertEquals(1, asked)
|
||||
assertEquals(3, screen.state.value.messages.size)
|
||||
answer.complete(Turn(message = person("w1"), reply = reply("a2", complete = false)))
|
||||
first.join()
|
||||
assertNull(screen.state.value.acting)
|
||||
assertEquals(listOf(Followed("a2", own = true)), screen.followed)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun discardTakesTheRowAwayAndAsksNothingElse() = runTest {
|
||||
val screen = Screen(waitingChat)
|
||||
var asked = 0
|
||||
screen.actions.discard(waitingChat.messages.last()) { asked++ }
|
||||
assertEquals(1, asked)
|
||||
assertEquals(listOf("q1", "a1"), screen.state.value.messages.map { it.id })
|
||||
assertEquals(0, screen.reads)
|
||||
assertEquals(0, screen.catchUps)
|
||||
assertTrue(screen.followed.isEmpty())
|
||||
assertTrue(screen.said.isEmpty())
|
||||
assertNull(screen.state.value.acting)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRefusalIsSaidInTheInstancesWordsAndTheChatIsReadAgain() = runTest {
|
||||
// Send now while a reply is being written; send now and discard for a message that waits no more; discard for one that is gone.
|
||||
val refusals = listOf(
|
||||
ApiException(409, "Wait for the current reply to finish, or stop it."),
|
||||
ApiException(409, "That message is not waiting to be sent."),
|
||||
ApiException(404, "That message is not waiting to be sent."),
|
||||
)
|
||||
for (refusal in refusals) {
|
||||
for (send in listOf(true, false)) {
|
||||
val screen = Screen(waitingChat)
|
||||
val waits = waitingChat.messages.last()
|
||||
if (send) screen.actions.sendNow(waits) { throw refusal } else screen.actions.discard(waits) { throw refusal }
|
||||
assertEquals(listOf(refusal.message), screen.said)
|
||||
assertEquals(1, screen.catchUps)
|
||||
// The buttons were free again before the read: it may wait for a reply to end.
|
||||
assertNull(screen.actingAtCatchUp)
|
||||
// Nothing was changed on a guess, and nothing followed: the read says what is true.
|
||||
assertEquals(waitingChat.messages, screen.state.value.messages)
|
||||
assertTrue(screen.followed.isEmpty())
|
||||
assertNull(screen.state.value.acting)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFailureThatSaysNothingOfTheMessageLeavesItWaitingAndReadsNothing() = runTest {
|
||||
for (failure in listOf(ConnectException("refused"), ApiException(500, "Something went wrong."))) {
|
||||
val screen = Screen(waitingChat)
|
||||
screen.actions.sendNow(waitingChat.messages.last()) { throw failure }
|
||||
assertEquals(1, screen.said.size)
|
||||
assertEquals(0, screen.catchUps)
|
||||
assertEquals(Waiting.Unsure, screen.state.value.messages.last().waiting)
|
||||
assertNull(screen.state.value.acting)
|
||||
// The person can try again.
|
||||
screen.actions.discard(waitingChat.messages.last()) { }
|
||||
assertEquals(listOf("q1", "a1"), screen.state.value.messages.map { it.id })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -182,6 +182,22 @@ object Fakes {
|
||||
summary = ActivitySummary(working = 2, queued = 1, done = 4, finished = 4, active = 3, total = 7),
|
||||
)
|
||||
|
||||
/**
|
||||
* Three messages that wait, each its own way: queued behind a reply, handed to the linked
|
||||
* computer with its arrival unknown, and held by the computer for its next turn.
|
||||
*/
|
||||
val waiting = ChatState(
|
||||
chat = chat,
|
||||
messages = listOf(
|
||||
question,
|
||||
answer,
|
||||
Message(id = "w1", role = "user", text = "And how long does it keep?", queued = true, progress = Progress(phase = "queued", ahead = 1)),
|
||||
Message(id = "w2", role = "user", text = "Then run the tests once more.", queued = true, origin = "unsure"),
|
||||
Message(id = "w3", role = "user", text = "And tidy the notes when that is done.", queued = true, origin = "carried"),
|
||||
),
|
||||
models = models,
|
||||
)
|
||||
|
||||
private val fixture = LembasJson.decodeFromString(ActivityEnvelope.serializer(), text("activity")).activity
|
||||
|
||||
private fun job(id: String, type: String, role: String, brief: String, state: String, seconds: Int, stoppable: Boolean = true) = ActivityAgent(
|
||||
@@ -528,7 +544,7 @@ object Fakes {
|
||||
)
|
||||
|
||||
val shareFiles = ShareState(
|
||||
files = listOf(SharedFile("map-of-the-road.jpg", image = true), SharedFile("provisions.pdf", image = false)),
|
||||
files = listOf(SharedFile("map-of-the-road.jpg", image = true, size = 2_400_000), SharedFile("provisions.pdf", image = false, size = 184_000)),
|
||||
last = LastAssist("c1", "Packing for the road", 0),
|
||||
error = "Home cannot be reached.",
|
||||
)
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
package eu.llembas.android.shots
|
||||
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.ui.Modifier
|
||||
import eu.llembas.android.api.FileEntry
|
||||
import eu.llembas.android.api.FileVersion
|
||||
import eu.llembas.android.api.Notebook
|
||||
import eu.llembas.android.api.NotebookCell
|
||||
import eu.llembas.android.api.TrashItem
|
||||
import eu.llembas.android.api.parseTable
|
||||
import eu.llembas.android.ui.files.FilesActions
|
||||
import eu.llembas.android.ui.files.FilesContent
|
||||
import eu.llembas.android.ui.files.FilesState
|
||||
import eu.llembas.android.ui.files.FolderPickContent
|
||||
import eu.llembas.android.ui.files.FolderPickState
|
||||
import eu.llembas.android.ui.files.TrashActions
|
||||
import eu.llembas.android.ui.files.TrashContent
|
||||
import eu.llembas.android.ui.files.TrashState
|
||||
import eu.llembas.android.ui.files.VersionsContent
|
||||
import eu.llembas.android.ui.files.VersionsState
|
||||
import eu.llembas.android.ui.viewer.DetailsBody
|
||||
import eu.llembas.android.ui.viewer.EditorBody
|
||||
import eu.llembas.android.ui.viewer.FileActions
|
||||
import eu.llembas.android.ui.viewer.NotebookBody
|
||||
import eu.llembas.android.ui.viewer.PlayerControls
|
||||
import eu.llembas.android.ui.viewer.PlayerUi
|
||||
import eu.llembas.android.ui.viewer.TableBody
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
|
||||
/** The file manager's pages and the viewers' bodies, each drawn from made-up state. */
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(sdk = [35], qualifiers = "xhdpi")
|
||||
class FileShots {
|
||||
private val home = "/home/frodo"
|
||||
|
||||
private fun file(name: String, kind: String, mime: String, size: Long) =
|
||||
FileEntry(name = name, path = "$home/$name", kind = "file", fileKind = kind, size = size, mime = mime)
|
||||
|
||||
private val entries = listOf(
|
||||
FileEntry(name = "recipes", path = "$home/recipes", kind = "dir"),
|
||||
FileEntry(name = "The Fellowship's shared provisions", path = "$home/shared", kind = "mount"),
|
||||
file("lembas.md", "markdown", "text/markdown", 2_048),
|
||||
file("map-of-the-road.png", "image", "image/png", 3_400_000),
|
||||
file("provisions-for-a-very-long-journey-there-and-back-again.pdf", "pdf", "application/pdf", 780_000),
|
||||
file("walking-song.mp3", "audio", "audio/mpeg", 4_100_000),
|
||||
file("the-gates.mp4", "video", "video/mp4", 91_000_000),
|
||||
file("stores.csv", "table", "text/csv", 5_120),
|
||||
file("bake.ipynb", "notebook", "application/x-ipynb+json", 18_000),
|
||||
file("backup.zip", "archive", "application/zip", 12_000_000),
|
||||
)
|
||||
|
||||
private val listed = FilesState(path = home, parent = "/home", entries = entries)
|
||||
|
||||
@Test
|
||||
fun files() {
|
||||
shoot("50-files") { FilesContent(listed, object : FilesActions {}) }
|
||||
shoot("50-files", Phone.Small, fontScale = 1.5f) { FilesContent(listed, object : FilesActions {}) }
|
||||
val chosen = listed.copy(selected = setOf("$home/lembas.md", "$home/map-of-the-road.png"))
|
||||
shoot("50-files-selecting") { FilesContent(chosen, object : FilesActions {}) }
|
||||
shoot("50-files-selecting", Phone.Small, fontScale = 1.5f) { FilesContent(chosen, object : FilesActions {}) }
|
||||
shoot("50-files-empty") { FilesContent(FilesState(path = home, parent = "/home"), object : FilesActions {}) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun folderPicker() {
|
||||
val state = FolderPickState(path = home, parent = "/home", folders = entries.filter { it.isFolder }, loading = false)
|
||||
shoot("51-folder-picker") { FolderPickContent("Move to which folder?", "Move here", state, onNewFolder = {}) }
|
||||
shoot("51-folder-picker", Phone.Small, fontScale = 1.5f) { FolderPickContent("Move to which folder?", "Move here", state, onNewFolder = {}) }
|
||||
shoot("51-folder-picker-empty") { FolderPickContent("Copy to which folder?", "Copy here", state.copy(folders = emptyList())) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun trashAndVersions() {
|
||||
val trash = TrashState(
|
||||
items = listOf(
|
||||
TrashItem(id = "n1", name = "old-notes-from-the-first-attempt-at-the-recipe.md", path = "$home/recipes/old-notes.md", size = 1_200),
|
||||
TrashItem(id = "n2", name = "drafts", path = "$home/drafts", kind = "dir"),
|
||||
),
|
||||
loading = false,
|
||||
)
|
||||
shoot("52-trash") { TrashContent(trash, object : TrashActions {}) }
|
||||
shoot("52-trash", Phone.Small, fontScale = 1.5f) { TrashContent(trash, object : TrashActions {}) }
|
||||
shoot("52-trash-empty") { TrashContent(TrashState(loading = false), object : TrashActions {}) }
|
||||
val versions = VersionsState(
|
||||
versions = listOf(
|
||||
FileVersion(id = "v3", size = 2_048, at = "2026-03-10T08:00:00+00:00", by = "Frodo", current = true),
|
||||
FileVersion(id = "v2", size = 1_900, at = "2026-03-09T17:30:00+00:00", by = "Samwise Gamgee of Bagshot Row"),
|
||||
FileVersion(id = "v1", size = 20, at = "2026-03-01T06:15:00+00:00"),
|
||||
),
|
||||
loading = false,
|
||||
)
|
||||
shoot("53-versions") { VersionsContent("lembas.md", versions, onDownload = {}) }
|
||||
shoot("53-versions", Phone.Small, fontScale = 1.5f) { VersionsContent("lembas.md", versions, onDownload = {}) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun viewers() {
|
||||
val csv = "what,how many,where it is kept\nlembas,12,\"the leaf wrappings, top shelf\"\nwater skins,3,by the door\nrope,1\n" +
|
||||
(1..30).joinToString("\n") { "item $it,$it,shelf ${it % 4}" }
|
||||
shoot("54-viewer-table") { TableBody(parseTable(csv, ',')) }
|
||||
shoot("54-viewer-table-cut", Phone.Small) { TableBody(parseTable(csv, ',', maxRows = 6)) }
|
||||
val notebook = Notebook(
|
||||
cells = listOf(
|
||||
NotebookCell("markdown", "# Baking\nHow many cakes for the road."),
|
||||
NotebookCell("code", "cakes = days * walkers\nprint(cakes)", output = "36", count = 1),
|
||||
NotebookCell("code", "plot(cakes)", count = 2, cut = true),
|
||||
),
|
||||
more = 4,
|
||||
language = "python",
|
||||
)
|
||||
shoot("55-viewer-notebook") { NotebookBody(notebook) }
|
||||
shoot("55-viewer-notebook", Phone.Small, fontScale = 1.5f) { NotebookBody(notebook) }
|
||||
val details: @androidx.compose.runtime.Composable () -> Unit = {
|
||||
DetailsBody(
|
||||
"backup.zip",
|
||||
"archive · application/zip",
|
||||
12_000_000,
|
||||
"What is inside this kind of archive cannot be listed here.",
|
||||
object : FileActions {},
|
||||
)
|
||||
}
|
||||
shoot("56-viewer-details", content = details)
|
||||
shoot("56-viewer-details", Phone.Small, fontScale = 1.5f, content = details)
|
||||
shoot("57-viewer-player") {
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
PlayerControls(PlayerUi(ready = true, playing = true, positionMs = 65_000, durationMs = 214_000), onToggle = {}, onSeek = {})
|
||||
PlayerControls(PlayerUi(), onToggle = {}, onSeek = {})
|
||||
}
|
||||
}
|
||||
shoot("58-viewer-editor") { EditorBody("# Lembas\n\nWrap it in a leaf.\nKeep it dry.\n", onChange = {}) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package eu.llembas.android.shots
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.api.GeneratedMedia
|
||||
import eu.llembas.android.api.McpAuth
|
||||
import eu.llembas.android.api.McpServer
|
||||
import eu.llembas.android.api.MediaJob
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.ToolBlock
|
||||
import eu.llembas.android.api.ToolCall
|
||||
import eu.llembas.android.ui.chat.ChatActions
|
||||
import eu.llembas.android.ui.chat.ChatContent
|
||||
import eu.llembas.android.ui.chat.JobCard
|
||||
import eu.llembas.android.ui.chat.JobSeen
|
||||
import eu.llembas.android.ui.chat.MediaActions
|
||||
import eu.llembas.android.ui.chat.MediaCard
|
||||
import eu.llembas.android.ui.settings.McpContent
|
||||
import eu.llembas.android.ui.settings.McpState
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
|
||||
/** Generated media's cards, a chat that holds them, and Settings › MCP servers, each from made-up state. */
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(sdk = [35], qualifiers = "xhdpi")
|
||||
class MediaShots {
|
||||
private val actions = object : MediaActions {}
|
||||
private val made = "/home/frodo/Generated"
|
||||
|
||||
private val video = GeneratedMedia(
|
||||
kind = "video",
|
||||
path = "$made/video-20260102-030405.mp4",
|
||||
nodeId = "node7",
|
||||
name = "video-20260102-030405.mp4",
|
||||
mime = "video/mp4",
|
||||
size = 2_400_000,
|
||||
width = 832,
|
||||
height = 480,
|
||||
seconds = 5.0,
|
||||
)
|
||||
private val music = GeneratedMedia(
|
||||
kind = "music",
|
||||
path = "$made/a-walking-song-for-the-long-road-east-in-the-evening-20260102-030405.mp3",
|
||||
nodeId = "node9",
|
||||
name = "a-walking-song-for-the-long-road-east-in-the-evening-20260102-030405.mp3",
|
||||
mime = "audio/mpeg",
|
||||
size = 4_100_000,
|
||||
seconds = 187.0,
|
||||
)
|
||||
private val model = GeneratedMedia(kind = "model3d", path = "$made/ring-20260102.glb", nodeId = "node10", name = "ring-20260102.glb", size = 880_000)
|
||||
private val picture =
|
||||
GeneratedMedia(kind = "image", path = "$made/kite.png", nodeId = "node8", name = "kite.png", mime = "image/png", width = 1024, height = 576)
|
||||
|
||||
private val running = MediaJob(id = "mjob1", kind = "video", state = "running", active = true, source = "Studio · Text to video", seconds = 95.0)
|
||||
private val queued = MediaJob(id = "mjob4", kind = "music", state = "queued", active = true)
|
||||
private val failed = running.copy(
|
||||
id = "mjob3",
|
||||
state = "failed",
|
||||
active = false,
|
||||
error = "The workflow ran out of video memory while sampling. Nothing was made.",
|
||||
)
|
||||
private val cancelled = running.copy(id = "mjob5", kind = "model3d", state = "cancelled", active = false, error = "The far side was told to stop.")
|
||||
|
||||
@Test
|
||||
fun cards() {
|
||||
val drawn: @Composable () -> Unit = {
|
||||
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
MediaCard(video, null, actions)
|
||||
MediaCard(music, null, actions)
|
||||
MediaCard(model, null, actions)
|
||||
JobCard(JobSeen(running, at = 1), actions)
|
||||
JobCard(JobSeen(queued, at = 1), actions)
|
||||
JobCard(JobSeen(failed, at = 1), actions)
|
||||
JobCard(JobSeen(cancelled, at = 1), actions)
|
||||
}
|
||||
}
|
||||
shoot("60-media-cards", Phone.Scroll, content = drawn)
|
||||
shoot("60-media-cards", Phone.SmallScroll, fontScale = 1.5f, content = drawn)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aChatWithGeneratedMedia() {
|
||||
fun call(id: String, media: GeneratedMedia? = null, job: MediaJob? = null) = ToolCall(
|
||||
id = id,
|
||||
name = "video_generate",
|
||||
kind = "image",
|
||||
status = "ok",
|
||||
media = media,
|
||||
mediaJob = job?.let { eu.llembas.android.api.MediaJobRef(it.id, it.kind, "running") },
|
||||
block = ToolBlock(kind = "tool", title = "a kite over the dunes", state = "done", label = "Video"),
|
||||
)
|
||||
val reply = Message(
|
||||
id = "m9",
|
||||
role = "assistant",
|
||||
steps = listOf(
|
||||
Step(index = 0, kind = "tools", calls = listOf(call("c1", media = picture))),
|
||||
Step(index = 1, kind = "tools", calls = listOf(call("c2", job = running))),
|
||||
Step(index = 2, kind = "text", markdown = "The picture is here. The video is being made; it takes a few minutes."),
|
||||
),
|
||||
)
|
||||
val state = Fakes.transcript.copy(
|
||||
messages = listOf(Message(id = "m8", role = "user", text = "A kite over the dunes, as a picture and as a video."), reply),
|
||||
mediaJobs = mapOf("mjob1" to JobSeen(running, at = 1)),
|
||||
summary = null,
|
||||
)
|
||||
shoot("61-chat-media") { ChatContent(state, object : ChatActions {}, agent = false, media = actions) }
|
||||
shoot("61-chat-media", Phone.Small, fontScale = 1.5f) { ChatContent(state, object : ChatActions {}, agent = false, media = actions) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mcpServers() {
|
||||
val servers = listOf(
|
||||
McpServer(id = "mcp1", name = "Tracker", tools = 4, auth = McpAuth(kind = "secret", state = "ready")),
|
||||
McpServer(id = "mcp2", name = "Mail", tools = 7, auth = McpAuth(kind = "oauth", state = "signed_in", account = "frodo@example.org", renews = true)),
|
||||
McpServer(
|
||||
id = "mcp3",
|
||||
name = "Notes of the long expedition",
|
||||
tools = 3,
|
||||
auth = McpAuth(kind = "oauth", state = "signed_out", signinUrl = "https://lembas.example.org/settings/mcp/mcp3/sign-in"),
|
||||
),
|
||||
McpServer(id = "mcp4", name = "Wiki", tools = 2, auth = McpAuth(kind = "oauth", state = "needs_signin", shared = true)),
|
||||
McpServer(
|
||||
id = "mcp5",
|
||||
name = "Calendar",
|
||||
tools = 5,
|
||||
auth = McpAuth(kind = "oauth", state = "signed_in", account = "frodo", expiresAt = "2026-03-10T08:00:00+00:00"),
|
||||
),
|
||||
)
|
||||
shoot("62-mcp", Phone.Scroll) { McpContent(McpState(servers, loading = false)) }
|
||||
shoot("62-mcp", Phone.SmallScroll, fontScale = 1.5f) { McpContent(McpState(servers, loading = false)) }
|
||||
shoot("62-mcp-none") { McpContent(McpState(loading = false)) }
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,7 @@ import eu.llembas.android.ui.chat.PhoneCardContent
|
||||
import eu.llembas.android.ui.chat.PhoneCardState
|
||||
import eu.llembas.android.ui.chat.TuneContent
|
||||
import eu.llembas.android.ui.chat.modelId
|
||||
import eu.llembas.android.ui.chat.modelInfo
|
||||
import eu.llembas.android.ui.home.ArchivedActions
|
||||
import eu.llembas.android.ui.home.ArchivedContent
|
||||
import eu.llembas.android.ui.home.ChatsState
|
||||
@@ -132,6 +133,14 @@ class ScreenShots {
|
||||
shoot("03-transcript", Phone.Small, fontScale = 1.5f) { ChatContent(Fakes.transcript, NoChatActions, agent = false) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun waitingMessages() {
|
||||
// How each waits, in words, and Send now / Discard under it; the rows must hold at a small phone's width and large type.
|
||||
shoot("03-waiting") { ChatContent(Fakes.waiting, NoChatActions, agent = false) }
|
||||
shoot("03-waiting", Phone.Small) { ChatContent(Fakes.waiting, NoChatActions, agent = false) }
|
||||
shoot("03-waiting", Phone.Small, fontScale = 1.5f) { ChatContent(Fakes.waiting, NoChatActions, agent = false) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun writing() {
|
||||
// The 3.4.0 progress line under the reply: `{{text}} · {{elapsed}}`, the clock still.
|
||||
@@ -179,7 +188,7 @@ class ScreenShots {
|
||||
|
||||
@Test
|
||||
fun modelPicker() = shoot("06-model-picker") {
|
||||
SheetOver { ModelPickerContent(Fakes.models, Fakes.transcript.modelId, onPick = {}) }
|
||||
SheetOver { ModelPickerContent(Fakes.models, Fakes.transcript.modelInfo?.key, onPick = {}) }
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"kind": "chat",
|
||||
"title": "Waybread",
|
||||
"model": "qwen",
|
||||
"model_ref": "local/qwen",
|
||||
"folder_id": null,
|
||||
"pinned": false,
|
||||
"archived": false,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"kind": "agent",
|
||||
"title": "Waybread",
|
||||
"model": "qwen",
|
||||
"model_ref": "local/qwen",
|
||||
"folder_id": null,
|
||||
"pinned": false,
|
||||
"archived": false,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"kind": "report",
|
||||
"title": "Two cakes are unwrapped",
|
||||
"model": "qwen",
|
||||
"model_ref": "local/qwen",
|
||||
"folder_id": null,
|
||||
"pinned": false,
|
||||
"archived": false,
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
"kind": "chat",
|
||||
"title": "Waybread",
|
||||
"model": "qwen",
|
||||
"model_ref": "local/qwen",
|
||||
"folder_id": null,
|
||||
"pinned": false,
|
||||
"archived": false,
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
"machine": false,
|
||||
"origin": "",
|
||||
"model": "qwen",
|
||||
"model_ref": "local/qwen",
|
||||
"attachments": [],
|
||||
"end": null,
|
||||
"steps": [
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
"machine": false,
|
||||
"origin": "",
|
||||
"model": "qwen",
|
||||
"model_ref": "local/qwen",
|
||||
"attachments": [],
|
||||
"end": null,
|
||||
"steps": [
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"chat_id": "chat1",
|
||||
"message_id": "msg2",
|
||||
"live": true
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"chat_id": "chat1",
|
||||
"message_id": "msg2",
|
||||
"live": false
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "31f4ad7e7995d215",
|
||||
"version": "3968a502db186b62",
|
||||
"schedules": [
|
||||
{
|
||||
"id": "sched1",
|
||||
@@ -39,6 +39,7 @@
|
||||
"catch_up": "one",
|
||||
"grace_minutes": null,
|
||||
"model": "qwen",
|
||||
"model_ref": "local/qwen",
|
||||
"effort": "high",
|
||||
"agents": null,
|
||||
"tools": [
|
||||
@@ -72,6 +73,7 @@
|
||||
"attempts": 1,
|
||||
"model": {
|
||||
"id": "gpt-oss",
|
||||
"ref": "local/gpt-oss",
|
||||
"name": "GPT-OSS",
|
||||
"reason": "switched",
|
||||
"switched_from": "Qwen"
|
||||
|
||||
@@ -4,7 +4,10 @@
|
||||
"size": 27,
|
||||
"mime": "text/markdown",
|
||||
"kind": "markdown",
|
||||
"language": "markdown",
|
||||
"file_kind": "markdown",
|
||||
"level": "commit",
|
||||
"writable": true,
|
||||
"language": "",
|
||||
"sha": "abababababababababababababababababababababababababababababababab",
|
||||
"text": "# Lembas\n\nWrap it in a leaf.\n"
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"path": "/home/frodo/maps.zip",
|
||||
"name": "maps.zip",
|
||||
"size": 4096,
|
||||
"mime": "application/zip",
|
||||
"kind": "archive",
|
||||
"file_kind": "archive",
|
||||
"level": "commit",
|
||||
"writable": true,
|
||||
"language": "",
|
||||
"sha": "abababababababababababababababababababababababababababababababab",
|
||||
"text": "",
|
||||
"withheld": {
|
||||
"reason": "not_text",
|
||||
"message": "This is not a text file, so it is not shown here."
|
||||
},
|
||||
"archive": {
|
||||
"entries": [
|
||||
{
|
||||
"name": "maps/",
|
||||
"size": null,
|
||||
"dir": true
|
||||
},
|
||||
{
|
||||
"name": "maps/shire.png",
|
||||
"size": 2048,
|
||||
"dir": false
|
||||
}
|
||||
],
|
||||
"total": 2,
|
||||
"truncated": false,
|
||||
"problem": null,
|
||||
"message": ""
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,9 @@
|
||||
"size": 2048,
|
||||
"mime": "image/png",
|
||||
"kind": "image",
|
||||
"file_kind": "image",
|
||||
"level": "ro",
|
||||
"writable": false,
|
||||
"language": "",
|
||||
"sha": "abababababababababababababababababababababababababababababababab",
|
||||
"text": "",
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"detail": "There is already something called lembas.md here.",
|
||||
"exists": true,
|
||||
"path": "/home/frodo/lembas.md"
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"id": "node6",
|
||||
"path": "/home/frodo/Clips/video-20261119-101500.mp4",
|
||||
"name": "video-20261119-101500.mp4",
|
||||
"parent": "/home/frodo/Clips",
|
||||
"kind": "file",
|
||||
"file_kind": "video",
|
||||
"trashed": false
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"detail": "This file changed since you opened it. Reload it, or save anyway.",
|
||||
"conflict": true,
|
||||
"sha": "abababababababababababababababababababababababababababababababab",
|
||||
"version": "ver2"
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"path": "/home/frodo/lembas.md",
|
||||
"sha": "abababababababababababababababababababababababababababababababab",
|
||||
"versions": [
|
||||
{
|
||||
"id": "ver2",
|
||||
"sha": "abababababababababababababababababababababababababababababababab",
|
||||
"size": 27,
|
||||
"at": "2026-01-02T03:04:05+00:00",
|
||||
"by": "Frodo",
|
||||
"chat_id": "chat1",
|
||||
"current": true
|
||||
},
|
||||
{
|
||||
"id": "ver1",
|
||||
"sha": "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd",
|
||||
"size": 20,
|
||||
"at": "2026-01-02T03:04:05+00:00",
|
||||
"by": "Frodo",
|
||||
"chat_id": null,
|
||||
"current": false
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"op": "move",
|
||||
"to": "/home/frodo/recipes",
|
||||
"atomic": false,
|
||||
"results": [
|
||||
{
|
||||
"path": "/home/frodo/lembas.md",
|
||||
"ok": true,
|
||||
"to": "/home/frodo/recipes/lembas.md"
|
||||
},
|
||||
{
|
||||
"path": "/home/frodo/map.png",
|
||||
"ok": false,
|
||||
"error": "Read-only: /home/frodo/map.png can be read in this session but not changed."
|
||||
}
|
||||
],
|
||||
"done": 1,
|
||||
"failed": 1
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"path": "/home/frodo",
|
||||
"parent": "/home",
|
||||
"entries": [
|
||||
{
|
||||
"name": "recipes",
|
||||
"path": "/home/frodo/recipes",
|
||||
"kind": "dir",
|
||||
"file_kind": null,
|
||||
"size": 0,
|
||||
"mime": "",
|
||||
"updated_at": "2026-01-02T03:04:05+00:00"
|
||||
},
|
||||
{
|
||||
"name": "lembas.md",
|
||||
"path": "/home/frodo/lembas.md",
|
||||
"kind": "file",
|
||||
"file_kind": "markdown",
|
||||
"size": 27,
|
||||
"mime": "text/markdown",
|
||||
"updated_at": "2026-01-02T03:04:05+00:00"
|
||||
},
|
||||
{
|
||||
"name": "map.png",
|
||||
"path": "/home/frodo/map.png",
|
||||
"kind": "file",
|
||||
"file_kind": "image",
|
||||
"size": 2048,
|
||||
"mime": "image/png",
|
||||
"updated_at": "2026-01-02T03:04:05+00:00"
|
||||
},
|
||||
{
|
||||
"name": "lembas (2).md",
|
||||
"path": "/home/frodo/lembas (2).md",
|
||||
"kind": "file",
|
||||
"file_kind": "markdown",
|
||||
"size": 27,
|
||||
"mime": "text/markdown",
|
||||
"updated_at": "2026-01-02T03:04:05+00:00"
|
||||
}
|
||||
],
|
||||
"copied": {
|
||||
"name": "lembas (2).md",
|
||||
"path": "/home/frodo/lembas (2).md",
|
||||
"kind": "file",
|
||||
"file_kind": "markdown",
|
||||
"size": 27,
|
||||
"mime": "text/markdown",
|
||||
"updated_at": "2026-01-02T03:04:05+00:00"
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
"name": "recipes",
|
||||
"path": "/home/frodo/recipes",
|
||||
"kind": "dir",
|
||||
"file_kind": null,
|
||||
"size": 0,
|
||||
"mime": "",
|
||||
"updated_at": "2026-01-02T03:04:05+00:00"
|
||||
@@ -14,9 +15,19 @@
|
||||
"name": "lembas.md",
|
||||
"path": "/home/frodo/lembas.md",
|
||||
"kind": "file",
|
||||
"file_kind": "markdown",
|
||||
"size": 27,
|
||||
"mime": "text/markdown",
|
||||
"updated_at": "2026-01-02T03:04:05+00:00"
|
||||
},
|
||||
{
|
||||
"name": "map.png",
|
||||
"path": "/home/frodo/map.png",
|
||||
"kind": "file",
|
||||
"file_kind": "image",
|
||||
"size": 2048,
|
||||
"mime": "image/png",
|
||||
"updated_at": "2026-01-02T03:04:05+00:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"restored": "/home/frodo/old.md",
|
||||
"items": []
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": "node5",
|
||||
"name": "old.md",
|
||||
"path": "/home/frodo/old.md",
|
||||
"kind": "file",
|
||||
"size": 12,
|
||||
"trashed_at": "2026-01-02T03:04:05+00:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"removed": 1,
|
||||
"items": []
|
||||
}
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"ref": "v2.0.0-beta.15",
|
||||
"commit": "e38cec75b3685d09ba8ff28c859bd25e5b3a294c",
|
||||
"sha256": "208111001ffd502f13d7f6fbc24a232e5ddc0d63c6789afe1636e34f1c737834"
|
||||
"ref": "v2.0.0-beta.18",
|
||||
"commit": "4c0573f1e68b068b1382ae00c918babb37c91293",
|
||||
"sha256": "ac22d0333a131982ff2906be7d25bedb1ff730cd8d86e68b71b6e907de634220"
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
{
|
||||
"servers": [
|
||||
{
|
||||
"id": "mcp1",
|
||||
"slug": "tracker",
|
||||
"name": "Tracker",
|
||||
"tools": 4,
|
||||
"auth": {
|
||||
"kind": "secret",
|
||||
"state": "ready",
|
||||
"shared": false,
|
||||
"account": "",
|
||||
"expires_at": null,
|
||||
"renews": false,
|
||||
"signin_url": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "mcp2",
|
||||
"slug": "mail",
|
||||
"name": "Mail",
|
||||
"tools": 7,
|
||||
"auth": {
|
||||
"kind": "oauth",
|
||||
"state": "signed_in",
|
||||
"shared": false,
|
||||
"account": "frodo@example.org",
|
||||
"expires_at": null,
|
||||
"renews": true,
|
||||
"signin_url": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "mcp3",
|
||||
"slug": "notes",
|
||||
"name": "Notes",
|
||||
"tools": 3,
|
||||
"auth": {
|
||||
"kind": "oauth",
|
||||
"state": "signed_out",
|
||||
"shared": false,
|
||||
"account": "",
|
||||
"expires_at": null,
|
||||
"renews": false,
|
||||
"signin_url": "https://lembas.example.org/settings/mcp/mcp3/sign-in"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "mcp4",
|
||||
"slug": "wiki",
|
||||
"name": "Wiki",
|
||||
"tools": 2,
|
||||
"auth": {
|
||||
"kind": "oauth",
|
||||
"state": "needs_signin",
|
||||
"shared": true,
|
||||
"account": "",
|
||||
"expires_at": null,
|
||||
"renews": false,
|
||||
"signin_url": null
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"id": "mjob1",
|
||||
"kind": "video",
|
||||
"state": "running",
|
||||
"active": true,
|
||||
"chat_id": "chat1",
|
||||
"message_id": "msg2",
|
||||
"source": "Studio · Text to video",
|
||||
"prompt": "a kite over dunes",
|
||||
"started": "2026-01-02T03:04:05+00:00",
|
||||
"ended": null,
|
||||
"deadline": "2026-01-02T03:34:05+00:00",
|
||||
"seconds": 42,
|
||||
"error": "",
|
||||
"result": null,
|
||||
"cost": null,
|
||||
"told": false
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"id": "mjob2",
|
||||
"kind": "video",
|
||||
"state": "done",
|
||||
"active": false,
|
||||
"chat_id": "chat1",
|
||||
"message_id": "msg2",
|
||||
"source": "Studio · Text to video",
|
||||
"prompt": "a kite over dunes",
|
||||
"started": "2026-01-02T03:04:05+00:00",
|
||||
"ended": "2026-01-02T03:05:40+00:00",
|
||||
"deadline": "2026-01-02T03:34:05+00:00",
|
||||
"seconds": 95,
|
||||
"error": "",
|
||||
"result": {
|
||||
"kind": "video",
|
||||
"path": "/home/frodo/Generated/video-20260102-030405.mp4",
|
||||
"node_id": "node7",
|
||||
"version_id": "ver7",
|
||||
"name": "video-20260102-030405.mp4",
|
||||
"mime": "video/mp4",
|
||||
"size": 2400000,
|
||||
"width": 832,
|
||||
"height": 480,
|
||||
"seconds": 5
|
||||
},
|
||||
"cost": {
|
||||
"amount": 0.1,
|
||||
"currency": ""
|
||||
},
|
||||
"told": true
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"id": "mjob3",
|
||||
"kind": "video",
|
||||
"state": "failed",
|
||||
"active": false,
|
||||
"chat_id": "chat1",
|
||||
"message_id": "msg2",
|
||||
"source": "Studio · Text to video",
|
||||
"prompt": "a kite over dunes",
|
||||
"started": "2026-01-02T03:04:05+00:00",
|
||||
"ended": "2026-01-02T03:05:40+00:00",
|
||||
"deadline": "2026-01-02T03:34:05+00:00",
|
||||
"seconds": 95,
|
||||
"error": "ComfyUI ran out of video memory in KSampler.",
|
||||
"result": null,
|
||||
"cost": null,
|
||||
"told": true
|
||||
}
|
||||
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user