Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
79cd9f3804
|
||
|
|
08a720465e
|
||
|
|
bac89b5e68
|
||
|
|
5e5e63353a
|
||
|
|
660ff90b3a
|
||
|
|
9610a8a9d8
|
||
|
|
1f596af56d
|
||
|
|
635982a4f8
|
||
|
|
5d9e367992
|
||
|
|
72657ba157
|
||
|
|
37574292cd
|
||
|
|
a9bdfcc18a
|
||
|
|
5256959a11
|
||
|
|
c4813831f5
|
||
|
|
6e08795a5c
|
No files matched your search
@@ -3,6 +3,100 @@
|
||||
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`.
|
||||
|
||||
## [1.0.0-beta.15] — 2026-11-24
|
||||
|
||||
What is said here of shown files and of an edit's diff needs an instance newer than LLeMbas
|
||||
2.0.0-beta.18. On an older one the app behaves as before.
|
||||
|
||||
### Added
|
||||
|
||||
- **A file an agent shows is in the chat, whatever it is.** When an agent puts a file in front
|
||||
of you that is not text -- a screenshot it took, a recording, a report -- the reply holds it
|
||||
where generated media is: a picture is drawn, with its name under it; sound and video have
|
||||
Play and the app's own player; a PDF has Open, which lays its pages out over the chat. A 3D
|
||||
model, an archive, a text file that came this way and any other file are a row with the
|
||||
file's name, what it is in words and its size. A kind the app has not heard of is a "File",
|
||||
never an empty place. Every one of them has Open in Files, Download, Share and Open with.
|
||||
Whether a file is shown does not depend on what the model itself can read.
|
||||
- **An edit's approval card shows what would change.** Where a linked computer asks before an
|
||||
edit, the card lists each file with the lines that go and the lines that come, marked by a
|
||||
sign and by colour, with a little unchanged text around them; a new file and a deleted one
|
||||
say so. Long lines scroll sideways inside their own box; a long change is folded to its first
|
||||
lines with "Show all". Both texts are drawn as plain text. Allow and Deny are as they were.
|
||||
A character that cannot be seen or that changes the direction of a line, in a line or in a
|
||||
path, is written as its code point (`<U+202E>`), so what the card shows is what is written. A
|
||||
file whose line endings change says so once instead of showing every line twice. A very long
|
||||
change is compared only at its beginning and says so, and is worked out beside the screen,
|
||||
not in it. The call's arguments stay in view when there is no change to show.
|
||||
|
||||
### Changed
|
||||
|
||||
- **A picture in a chat is fetched only while the app is in front of an unlocked phone**, like
|
||||
every other file of the account; one that comes into view behind the lock waits. The
|
||||
assistant's sheet counts as the app in front, so a picture in it is fetched as before.
|
||||
- **"Open with" offers a file as what it is.** The type handed to the other app is read from the
|
||||
file's own first bytes, or from its name's extension where the bytes carry no mark, and no
|
||||
longer taken from what the instance said of it.
|
||||
- Pinned to the server's `dev` at `809b87b`. A linked computer's files and the editor's two
|
||||
models are read from the instance and not shown anywhere yet: this app has no browser for a
|
||||
computer's files and no screen for the editor's settings.
|
||||
|
||||
- **The launcher icon is the app's own**: the LLeMbas leaf with a small phone beside it, so the app
|
||||
is told apart from the other LLeMbas products. The notification icon stays the leaf.
|
||||
|
||||
## [1.0.0-beta.14] — 2026-11-24
|
||||
|
||||
What is said here of replies that start by themselves needs an instance newer than LLeMbas
|
||||
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
|
||||
|
||||
@@ -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.13"
|
||||
versionName = "1.0.0-beta.15"
|
||||
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
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
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.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
@@ -14,11 +21,13 @@ import java.util.concurrent.atomic.AtomicInteger
|
||||
* is not touched, so what the person started finishes; the next one waits here, and goes on by
|
||||
* itself when the app is in front of an unlocked phone again.
|
||||
*
|
||||
* The process has one ([LembasApp.gate]). It hears of the app's activities starting and stopping
|
||||
* and of the screen going off and the phone being unlocked; [locked] is asked each time.
|
||||
* The process has one ([LembasApp.gate]). It hears of the app's activities starting and stopping,
|
||||
* of the assistant's sheet showing and hiding (a session's window, which is no activity), and of
|
||||
* the screen going off and the phone being unlocked; [locked] is asked each time.
|
||||
*/
|
||||
class InstanceGate(private val locked: () -> Boolean) {
|
||||
private val started = AtomicInteger(0)
|
||||
private val sheet = AtomicBoolean(false)
|
||||
private val state = MutableStateFlow(false)
|
||||
|
||||
/** Whether a request may start now, as it was last looked at. */
|
||||
@@ -34,9 +43,25 @@ class InstanceGate(private val locked: () -> Boolean) {
|
||||
look()
|
||||
}
|
||||
|
||||
/**
|
||||
* The assistant's sheet is up. It is a window of the system's session and no activity, so it
|
||||
* says so itself: the app is in front while it shows, as while an activity is started. Told
|
||||
* once however often the system shows a sheet that is already up. The lock still shuts the
|
||||
* gate: a sheet over the lock screen asks the instance for nothing.
|
||||
*/
|
||||
fun sessionShown() {
|
||||
sheet.set(true)
|
||||
look()
|
||||
}
|
||||
|
||||
fun sessionHidden() {
|
||||
sheet.set(false)
|
||||
look()
|
||||
}
|
||||
|
||||
/** Looks again (the screen went off, the phone was unlocked) and says whether a request may start. */
|
||||
fun look(): Boolean {
|
||||
val now = started.get() > 0 && !locked()
|
||||
val now = (started.get() > 0 || sheet.get()) && !locked()
|
||||
state.value = now
|
||||
return now
|
||||
}
|
||||
@@ -57,11 +82,49 @@ class InstanceGate(private val locked: () -> Boolean) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [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
|
||||
@@ -74,3 +137,16 @@ suspend fun <T> sendFrom(items: List<T>, from: Int, turn: suspend () -> Unit, do
|
||||
done(i + 1)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The assistant's sheet as the gate hears of it: every way the session's window can go says so.
|
||||
* Android may show a sheet that is up again, hide it once, or tear the session down without
|
||||
* hiding it at all -- [gone] is for each of those ends, so the sheet can never be left counted
|
||||
* as the app in front when nothing of the app is.
|
||||
*/
|
||||
class SheetAtGate(private val gate: InstanceGate) {
|
||||
fun shown() = gate.sessionShown()
|
||||
|
||||
/** Hidden, destroyed, or its service gone: whichever comes, and however many of them. */
|
||||
fun gone() = gate.sessionHidden()
|
||||
}
|
||||
@@ -29,11 +29,16 @@ 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. */
|
||||
|
||||
@@ -212,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 {
|
||||
|
||||
@@ -342,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)
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
// An edit's diff on its approval card, worked out on the phone from the two texts the card
|
||||
// carries (`contract/event_ask_edit.json`). Lines only: what is drawn is text with a sign, and
|
||||
// every step is bounded before it is taken, because both texts are a model's and a file's words
|
||||
// of any size.
|
||||
|
||||
/** What a line of a diff is: in both texts, only in the new one, only in the old one, or the mark of lines left out between two changes. */
|
||||
enum class DiffSign { Same, Added, Removed, Gap }
|
||||
|
||||
data class DiffLine(val sign: DiffSign, val text: String)
|
||||
|
||||
/**
|
||||
* One file's change as the card draws it: the changed lines with a little around them, and how
|
||||
* many were added and removed. [endings] says a change of line endings (`"LF" to "CRLF"`), which
|
||||
* is said once instead of as every line going and coming. [cut]: the texts were longer than what
|
||||
* a phone compares, and only their beginning was.
|
||||
*/
|
||||
data class DiffView(val lines: List<DiffLine>, val added: Int, val removed: Int, val endings: Pair<String, String>? = null, val cut: Boolean = false) {
|
||||
/** The lines drawn: the first [DIFF_FOLD] until the person opens it, and never more than [DIFF_MOST]. */
|
||||
fun shown(open: Boolean): List<DiffLine> = lines.take(if (open) DIFF_MOST else DIFF_FOLD)
|
||||
|
||||
/** Whether there is more than the folded card shows. */
|
||||
val folds: Boolean get() = lines.size > DIFF_FOLD
|
||||
|
||||
/** The lines not drawn even when open. */
|
||||
val beyond: Int get() = (lines.size - DIFF_MOST).coerceAtLeast(0)
|
||||
|
||||
/** Whether the block says anything of the change at all; a card whose diffs say nothing keeps its arguments in view. */
|
||||
val says: Boolean get() = lines.isNotEmpty() || endings != null || cut
|
||||
}
|
||||
|
||||
/** How many lines of a file's diff the card shows before it is opened. */
|
||||
const val DIFF_FOLD = 12
|
||||
|
||||
/** The most lines of one file's diff the card lays out: a card is for deciding, not for reading a megabyte. */
|
||||
const val DIFF_MOST = 400
|
||||
|
||||
/** The lines kept around a change. */
|
||||
const val DIFF_CONTEXT = 3
|
||||
|
||||
/** Past this many pairs of lines the two middles are not compared: the old one is shown going and the new one coming. */
|
||||
private const val DIFF_CELLS = 1_000_000L
|
||||
|
||||
/** The most lines of one text that are compared, and the most characters: what is past either is left out before any work is done. */
|
||||
const val DIFF_TEXT_LINES = 2_000
|
||||
const val DIFF_TEXT_CHARS = 200_000
|
||||
|
||||
/** A text's lines as they are compared, and whether the text went on past what is. */
|
||||
data class TextLines(val lines: List<String>, val cut: Boolean)
|
||||
|
||||
/**
|
||||
* The lines of [text], at most [mostLines] of them from at most its first [mostChars]
|
||||
* characters: nothing past either bound is read, split or kept. The newline that ends the last
|
||||
* line starts no empty one, and a line is compared without the `\r` before its newline, so a
|
||||
* file whose line endings change is not a file whose every line changes.
|
||||
*/
|
||||
fun textLines(text: String, mostLines: Int = DIFF_TEXT_LINES, mostChars: Int = DIFF_TEXT_CHARS): TextLines {
|
||||
val end = minOf(text.length, mostChars)
|
||||
val lines = ArrayList<String>()
|
||||
var from = 0
|
||||
while (from < end && lines.size < mostLines) {
|
||||
val newline = text.indexOf('\n', from).let { if (it < 0 || it >= end) -1 else it }
|
||||
val to = if (newline < 0) end else newline
|
||||
lines += text.substring(from, if (to > from && text[to - 1] == '\r') to - 1 else to)
|
||||
from = if (newline < 0) end else newline + 1
|
||||
}
|
||||
return TextLines(lines, cut = from < text.length)
|
||||
}
|
||||
|
||||
/** How [text]'s lines end, where it has any: `CRLF` when its first newline follows a `\r`, else `LF`; null for a text of one line. */
|
||||
internal fun lineEnding(text: String): String? {
|
||||
val newline = text.indexOf('\n')
|
||||
return when {
|
||||
newline < 0 -> null
|
||||
newline > 0 && text[newline - 1] == '\r' -> "CRLF"
|
||||
else -> "LF"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [old] turned into [new], line by line: what both begin and end with is the same without being
|
||||
* compared, and the middle is the longest run of lines the two share -- or, where the middles
|
||||
* are too long to compare on a phone, the old middle removed and the new one added.
|
||||
*/
|
||||
fun diffLines(old: List<String>, new: List<String>): List<DiffLine> {
|
||||
var head = 0
|
||||
while (head < old.size && head < new.size && old[head] == new[head]) head++
|
||||
var tail = 0
|
||||
while (tail < old.size - head && tail < new.size - head && old[old.size - 1 - tail] == new[new.size - 1 - tail]) tail++
|
||||
val a = old.subList(head, old.size - tail)
|
||||
val b = new.subList(head, new.size - tail)
|
||||
val out = ArrayList<DiffLine>(old.size + b.size)
|
||||
for (i in 0 until head) out += DiffLine(DiffSign.Same, old[i])
|
||||
if (a.isEmpty() || b.isEmpty() || a.size.toLong() * b.size > DIFF_CELLS) {
|
||||
a.forEach { out += DiffLine(DiffSign.Removed, it) }
|
||||
b.forEach { out += DiffLine(DiffSign.Added, it) }
|
||||
} else {
|
||||
// shared[i][j]: how many lines the rest of a from i and the rest of b from j have in common, in order.
|
||||
val shared = Array(a.size + 1) { IntArray(b.size + 1) }
|
||||
for (i in a.size - 1 downTo 0) {
|
||||
for (j in b.size - 1 downTo 0) {
|
||||
shared[i][j] = if (a[i] == b[j]) shared[i + 1][j + 1] + 1 else maxOf(shared[i + 1][j], shared[i][j + 1])
|
||||
}
|
||||
}
|
||||
var i = 0
|
||||
var j = 0
|
||||
while (i < a.size && j < b.size) {
|
||||
when {
|
||||
a[i] == b[j] -> {
|
||||
out += DiffLine(DiffSign.Same, a[i])
|
||||
i++
|
||||
j++
|
||||
}
|
||||
|
||||
shared[i + 1][j] >= shared[i][j + 1] -> out += DiffLine(DiffSign.Removed, a[i++])
|
||||
|
||||
else -> out += DiffLine(DiffSign.Added, b[j++])
|
||||
}
|
||||
}
|
||||
while (i < a.size) out += DiffLine(DiffSign.Removed, a[i++])
|
||||
while (j < b.size) out += DiffLine(DiffSign.Added, b[j++])
|
||||
}
|
||||
for (i in old.size - tail until old.size) out += DiffLine(DiffSign.Same, old[i])
|
||||
return out
|
||||
}
|
||||
|
||||
/** The changed lines of [lines] with [context] unchanged ones around each, and one [DiffSign.Gap] where lines between two changes are left out. */
|
||||
fun hunks(lines: List<DiffLine>, context: Int = DIFF_CONTEXT): List<DiffLine> {
|
||||
val keep = BooleanArray(lines.size)
|
||||
lines.forEachIndexed { at, line ->
|
||||
if (line.sign != DiffSign.Same) for (k in maxOf(0, at - context)..minOf(lines.size - 1, at + context)) keep[k] = true
|
||||
}
|
||||
val out = ArrayList<DiffLine>()
|
||||
var left = false
|
||||
lines.forEachIndexed { at, line ->
|
||||
if (keep[at]) {
|
||||
if (left && out.isNotEmpty()) out += DiffLine(DiffSign.Gap, "")
|
||||
left = false
|
||||
out += line
|
||||
} else {
|
||||
left = true
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* This file's change for the card: a file that is made is all added, one that goes is all
|
||||
* removed. Bounded before it starts ([textLines]) and while it runs ([diffLines]); it is still
|
||||
* work for a background thread, never for a frame.
|
||||
*/
|
||||
fun FileDiff.view(): DiffView {
|
||||
val before = oldText.orEmpty()
|
||||
val after = if (deleted) "" else newText
|
||||
val old = textLines(before)
|
||||
val new = textLines(after)
|
||||
val all = diffLines(old.lines, new.lines)
|
||||
val from = lineEnding(before)
|
||||
val to = lineEnding(after)
|
||||
return DiffView(
|
||||
hunks(all),
|
||||
added = all.count { it.sign == DiffSign.Added },
|
||||
removed = all.count { it.sign == DiffSign.Removed },
|
||||
endings = if (from != null && to != null && from != to) from to to else null,
|
||||
cut = old.cut || new.cut,
|
||||
)
|
||||
}
|
||||
|
||||
/** Whether an approval's item shows its `detail` (the call's arguments): always without diffs, and with them when none of them says anything. [views] is null while they are worked out. */
|
||||
fun showsDetail(item: CardItem, views: List<DiffView>?): Boolean = item.diffs.isEmpty() || (views != null && views.none { it.says })
|
||||
|
||||
// Characters a person cannot see, or that would move or break a line: on a card where somebody
|
||||
// decides, each is written as its code point.
|
||||
private fun unseen(c: Char): Boolean = when (c.code) {
|
||||
in 0x00..0x1F, in 0x7F..0x9F -> true
|
||||
0x00AD, 0x061C, 0x180E, 0xFEFF -> true
|
||||
in 0x200B..0x200F, in 0x2028..0x202E, in 0x2060..0x206F -> true
|
||||
in 0xFFF9..0xFFFB -> true
|
||||
else -> false
|
||||
}
|
||||
|
||||
/**
|
||||
* [text] with every invisible, direction-changing or line-breaking character written as
|
||||
* `<U+202E>`: a bidi override, a zero-width space, a line separator, a control. A tab is four
|
||||
* spaces. What is drawn reads as what is written.
|
||||
*/
|
||||
fun visibly(text: String): String {
|
||||
if (text.none { it == '\t' || unseen(it) }) return text
|
||||
return buildString(text.length + 16) {
|
||||
for (c in text) {
|
||||
when {
|
||||
c == '\t' -> append(" ")
|
||||
unseen(c) -> append("<U+").append(c.code.toString(16).uppercase().padStart(4, '0')).append('>')
|
||||
else -> append(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -365,3 +365,52 @@ class RangeReader(private val length: Long, private val block: Int = BLOCK, priv
|
||||
const val BLOCK = 512 * 1024
|
||||
}
|
||||
}
|
||||
|
||||
/** How much of a file's beginning says what it is. */
|
||||
const val SNIFF_BYTES = 16
|
||||
|
||||
private fun ByteArray.begins(at: Int, vararg bytes: Int): Boolean =
|
||||
size >= at + bytes.size && bytes.indices.all { (this[at + it].toInt() and 0xFF) == bytes[it] }
|
||||
|
||||
private fun ByteArray.says(at: Int, word: String): Boolean = size >= at + word.length && word.indices.all { this[at + it].toInt() == word[it].code }
|
||||
|
||||
/**
|
||||
* What a file is by its first bytes ([head], [SNIFF_BYTES] of them are enough), for the kinds a
|
||||
* chat hands out: pictures, sound, video, a PDF, a 3D model, the archives. Null for anything
|
||||
* else -- text has no mark, and a guess is worse than none.
|
||||
*/
|
||||
fun sniffType(head: ByteArray): String? = when {
|
||||
head.begins(0, 0x89, 0x50, 0x4E, 0x47) -> "image/png"
|
||||
head.begins(0, 0xFF, 0xD8, 0xFF) -> "image/jpeg"
|
||||
head.says(0, "GIF8") -> "image/gif"
|
||||
head.says(0, "RIFF") && head.says(8, "WEBP") -> "image/webp"
|
||||
head.says(0, "RIFF") && head.says(8, "WAVE") -> "audio/wav"
|
||||
head.says(0, "BM") -> "image/bmp"
|
||||
head.says(0, "%PDF-") -> "application/pdf"
|
||||
head.says(0, "OggS") -> "audio/ogg"
|
||||
head.says(0, "fLaC") -> "audio/flac"
|
||||
head.says(0, "ID3") || head.begins(0, 0xFF, 0xFB) || head.begins(0, 0xFF, 0xF3) -> "audio/mpeg"
|
||||
head.says(4, "ftyp") -> "video/mp4"
|
||||
head.begins(0, 0x1A, 0x45, 0xDF, 0xA3) -> "video/webm"
|
||||
head.says(0, "glTF") -> "model/gltf-binary"
|
||||
head.says(0, "PK\u0003\u0004") -> "application/zip"
|
||||
head.begins(0, 0x1F, 0x8B) -> "application/gzip"
|
||||
head.says(0, "7z") && head.begins(2, 0xBC, 0xAF) -> "application/x-7z-compressed"
|
||||
else -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* The type a copy is offered to another app as ("Open with"): what its bytes say, else what its
|
||||
* name's extension says ([named], the platform's table), else anything. A zip is the one mark
|
||||
* that many kinds of document carry inside, so there a known extension is the better word. The
|
||||
* type the instance said is not asked: it is not the phone's own reading.
|
||||
*/
|
||||
fun openType(head: ByteArray, named: String?): String {
|
||||
val sniffed = sniffType(head)
|
||||
val byName = named?.ifBlank { null }
|
||||
return when {
|
||||
sniffed == null -> byName ?: "*/*"
|
||||
sniffed == "application/zip" && byName != null -> byName
|
||||
else -> sniffed
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,11 @@ import kotlinx.serialization.Serializable
|
||||
* `model3d`), and the file is in the person's Files at [path] -- a moment's truth, since they may
|
||||
* move it; [nodeId] names it wherever it is. Its bytes are `GET /files/raw?node=`. [width],
|
||||
* [height] and [seconds] are 0 where the server did not know them.
|
||||
*
|
||||
* With [shown] it is a file an agent put in front of the person (`contract/tool_media_shown.json`)
|
||||
* and [kind] is what the file is, read from its bytes: `image`, `audio`, `video`, `pdf`,
|
||||
* `model3d`, `archive`, `binary`, `text`, or a word this app does not know yet. Whatever it is,
|
||||
* its card names it and leads to the file; what the phone can draw is drawn as well.
|
||||
*/
|
||||
@Serializable
|
||||
data class GeneratedMedia(
|
||||
@@ -25,16 +30,22 @@ data class GeneratedMedia(
|
||||
val width: Int = 0,
|
||||
val height: Int = 0,
|
||||
val seconds: Double = 0.0,
|
||||
/** An agent showed this file (the `show` tool on a file that is not text); it did not make it. */
|
||||
val shown: Boolean = false,
|
||||
) {
|
||||
/** How the card shows it, by what was asked for: an unknown kind is its details, never a player. */
|
||||
/** How the card shows it, by its kind: an unknown kind is its details, never a player. */
|
||||
val view: MediaView
|
||||
get() = when (kind) {
|
||||
"image", "image_edit" -> MediaView.Picture
|
||||
"video" -> MediaView.Video
|
||||
"music" -> MediaView.Sound
|
||||
"music", "audio" -> MediaView.Sound
|
||||
"pdf" -> MediaView.Document
|
||||
else -> MediaView.Details
|
||||
}
|
||||
|
||||
/** The kinds this app has a word for; anything else is said as "File" when shown, never as nothing. */
|
||||
val knownKind: Boolean get() = kind in KINDS
|
||||
|
||||
/** What to call it: its name, else the last name of its path. */
|
||||
val title: String get() = name.ifBlank { FileKinds.name(path) }
|
||||
|
||||
@@ -43,10 +54,18 @@ data class GeneratedMedia(
|
||||
|
||||
/** The folder of the person's Files it was written to. */
|
||||
val folder: String get() = FileKinds.parent(path)
|
||||
|
||||
companion object {
|
||||
val KINDS = setOf("image", "image_edit", "video", "music", "audio", "model3d", "pdf", "archive", "binary", "text")
|
||||
}
|
||||
}
|
||||
|
||||
/** What a generated file's card is: a picture drawn, a player, or (a 3D model, anything unknown) the file's details. */
|
||||
enum class MediaView { Picture, Video, Sound, Details }
|
||||
/**
|
||||
* What a file's card is: a picture drawn, a player, a document with pages the phone can lay out
|
||||
* (a PDF), or -- a 3D model, an archive, anything unknown -- the file's details. Every one of
|
||||
* them names the file and has the ways to it.
|
||||
*/
|
||||
enum class MediaView { Picture, Video, Sound, Document, Details }
|
||||
|
||||
/** The job a tool call started (`media_job`): [state] as it was when the call returned. */
|
||||
@Serializable
|
||||
|
||||
@@ -385,6 +385,12 @@ data class LinkedDevice(
|
||||
@SerialName("max_mode") val maxMode: String = "",
|
||||
/** Whether the device remembers the model last used in a directory (spec 3.9.0). */
|
||||
@SerialName("directory_model") val directoryModel: Boolean = false,
|
||||
/** Whether the device hands its files over the link at all (spec 3.11.0, `fs`). Parsed; no screen reads it yet. */
|
||||
val files: Boolean = false,
|
||||
/** False where its highest mode is plan: its files can be read and not changed. */
|
||||
@SerialName("files_writable") val filesWritable: Boolean = false,
|
||||
/** Whether the device lets files that run code (git's own, an agent's configuration) be changed from here. */
|
||||
@SerialName("files_that_run_code") val filesThatRunCode: Boolean = false,
|
||||
) {
|
||||
/** What to call it: its name, else its host. */
|
||||
val label: String get() = name.ifBlank { host.ifBlank { id } }
|
||||
@@ -453,6 +459,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)
|
||||
|
||||
@@ -715,6 +731,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)
|
||||
|
||||
@@ -751,8 +771,40 @@ data class CardItem(
|
||||
* action's own fields, as the server checked them. Carried out by `actions/ActionRunner`.
|
||||
*/
|
||||
val phone: JsonObject? = null,
|
||||
/** An edit's changes, one per file (`contract/event_ask_edit.json`); empty on a card without them. */
|
||||
val diffs: List<FileDiff> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* What an edit would do to one file, on its approval card: [oldText] is null for a file that is
|
||||
* made, [deleted] marks one that goes. Both texts are a model's and a file's words: drawn as
|
||||
* text by the app's own diff view (`api/Diff.kt`), never rendered.
|
||||
*/
|
||||
@Serializable
|
||||
data class FileDiff(
|
||||
val path: String = "",
|
||||
@SerialName("old_text") val oldText: String? = null,
|
||||
@SerialName("new_text") val newText: String = "",
|
||||
val deleted: Boolean = false,
|
||||
) {
|
||||
/** A file that does not exist yet. */
|
||||
val made: Boolean get() = oldText == null && !deleted
|
||||
}
|
||||
|
||||
/**
|
||||
* A person's two models for an editor (`GET /editor`, `contract/editor.json`): parsed so the
|
||||
* shape is pinned; this app has no screen for them.
|
||||
*/
|
||||
@Serializable
|
||||
data class EditorModels(val autocomplete: Autocomplete = Autocomplete(), val main: Main = Main()) {
|
||||
/** [source]: `person`, `instance` or null with no model. [allowed]: the refs an administrator allows, null for any. */
|
||||
@Serializable
|
||||
data class Autocomplete(val model: String? = null, val source: String? = null, val allowed: List<String>? = null)
|
||||
|
||||
@Serializable
|
||||
data class Main(val model: String? = null)
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class CardSubagent(val id: String = "", val name: String = "", val position: String = "")
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -28,6 +28,7 @@ import androidx.savedstate.SavedStateRegistryController
|
||||
import androidx.savedstate.SavedStateRegistryOwner
|
||||
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
|
||||
import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.SheetAtGate
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import eu.llembas.android.wake.AssistLink
|
||||
@@ -79,6 +80,8 @@ class LembasAssistService : VoiceInteractionService() {
|
||||
|
||||
override fun onDestroy() {
|
||||
AssistLink.destroyed(System.currentTimeMillis())
|
||||
// With the service gone no sheet of it is up, whatever its session managed to say.
|
||||
lembas.gate.sessionHidden()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@@ -143,6 +146,7 @@ class LembasAssistSession(context: Context) :
|
||||
|
||||
/** Whether this session's sheet is up, as far as the wake word's pause is concerned. */
|
||||
private var up = false
|
||||
private val atGate = SheetAtGate(context.lembas.gate)
|
||||
|
||||
/** Over the lock screen: waiting for what is heard, to hand it to the sheet's activity. */
|
||||
private var handing: Job? = null
|
||||
@@ -201,6 +205,9 @@ class LembasAssistSession(context: Context) :
|
||||
up = true
|
||||
AssistPresence.shown()
|
||||
}
|
||||
// The sheet is the app in front: what it draws of the account (a reply's picture) may be
|
||||
// asked for, unless the phone is locked. Said each time; the gate keeps it as one.
|
||||
atGate.shown()
|
||||
AssistLink.sheetShown(SystemClock.elapsedRealtime())
|
||||
// One sheet, never two: a sheet the wake word opened as a screen of the app, because
|
||||
// this one was slow to come, goes now that this one is here.
|
||||
@@ -230,6 +237,7 @@ class LembasAssistSession(context: Context) :
|
||||
up = false
|
||||
AssistPresence.hidden()
|
||||
}
|
||||
atGate.gone()
|
||||
controller.close()
|
||||
scope.cancel()
|
||||
scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
@@ -240,6 +248,8 @@ class LembasAssistSession(context: Context) :
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
// A session torn down without being hidden must not leave the gate open behind it.
|
||||
atGate.gone()
|
||||
controller.close()
|
||||
scope.cancel()
|
||||
registry.currentState = Lifecycle.State.DESTROYED
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.CardItem
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.Plan
|
||||
import eu.llembas.android.api.showsDetail
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
|
||||
/** The sentinel the web card's "Something else" row submits (`interaction.OTHER`). */
|
||||
@@ -73,6 +74,7 @@ private fun Approval(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
var refusing by remember { mutableStateOf(false) }
|
||||
Text(stringResource(R.string.card_approval), style = MaterialTheme.typography.titleMedium)
|
||||
card.items.forEach { item ->
|
||||
val views = diffViews(item.diffs)
|
||||
// A subagent asks, not the chat's own turn: said first, as the page says it.
|
||||
val subagent = item.subagent
|
||||
if (subagent != null) {
|
||||
@@ -100,9 +102,12 @@ private fun Approval(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
if (approvalTexts(listOf(item), edits).isNotEmpty()) {
|
||||
Text(stringResource(R.string.card_edit_runs), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
} else if (item.detail.isNotBlank()) {
|
||||
} else if (item.detail.isNotBlank() && showsDetail(item, views)) {
|
||||
Text(item.detail, fontFamily = FontFamily.Monospace)
|
||||
}
|
||||
// An edit says what it would change: the diff stands where the call's arguments would,
|
||||
// as text. Diffs that say nothing (the same text twice) leave the arguments in view.
|
||||
if (item.diffs.isNotEmpty()) CardDiffs(item.diffs, views)
|
||||
if (item.reason.isNotBlank()) Text(item.reason, style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
}
|
||||
// A corrected command goes with an allow, never with a refusal, and only when it was corrected.
|
||||
|
||||
@@ -103,15 +103,19 @@ 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.DocumentDialog
|
||||
import eu.llembas.android.ui.viewer.FileViewer
|
||||
import eu.llembas.android.ui.viewer.PlayerDialog
|
||||
import eu.llembas.android.ui.viewer.Playing
|
||||
import eu.llembas.android.ui.viewer.Reading
|
||||
import kotlinx.coroutines.flow.drop
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@@ -155,6 +159,12 @@ fun ChatScreen(
|
||||
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)
|
||||
@@ -167,6 +177,7 @@ fun ChatScreen(
|
||||
val transfers: TransferViewModel = viewModel(key = "chat-transfers")
|
||||
val saveTo = rememberSaver(transfers)
|
||||
var playing by remember { mutableStateOf<Playing?>(null) }
|
||||
var reading by remember { mutableStateOf<Reading?>(null) }
|
||||
val media = remember(model, transfers) {
|
||||
object : MediaActions {
|
||||
override fun play(media: GeneratedMedia) {
|
||||
@@ -177,6 +188,10 @@ fun ChatScreen(
|
||||
playing = Playing(Raw.Attached(attachment.id), attachment.name, attachment.size, video = attachment.kind == "video")
|
||||
}
|
||||
|
||||
override fun view(media: GeneratedMedia) {
|
||||
reading = Reading(media.raw, media.title, media.size)
|
||||
}
|
||||
|
||||
// Where the file is now, by its id: it may have been renamed or moved since it was made.
|
||||
override fun openInFiles(media: GeneratedMedia) = model.whereIs(media, onFiles)
|
||||
|
||||
@@ -184,7 +199,7 @@ fun ChatScreen(
|
||||
|
||||
override fun share(media: GeneratedMedia) = transfers.share(media.raw, media.title, media.mime)
|
||||
|
||||
override fun openWith(media: GeneratedMedia) = transfers.openWith(media.raw, media.title, media.mime)
|
||||
override fun openWith(media: GeneratedMedia) = transfers.openWith(media.raw, media.title)
|
||||
|
||||
override fun cancel(job: MediaJob) = model.cancelJob(job)
|
||||
}
|
||||
@@ -230,6 +245,7 @@ fun ChatScreen(
|
||||
state.chat?.id?.let { id -> FileViewer(id, file, onClose = { showing = null }) }
|
||||
}
|
||||
playing?.let { PlayerDialog(it, onClose = { playing = null }, gone = stringResource(R.string.media_gone)) }
|
||||
reading?.let { DocumentDialog(it, onClose = { reading = null }, gone = stringResource(R.string.media_gone)) }
|
||||
TransferHost(transfers)
|
||||
}
|
||||
|
||||
@@ -268,6 +284,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 ->
|
||||
@@ -279,6 +296,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
|
||||
@@ -286,13 +305,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
|
||||
}
|
||||
}
|
||||
@@ -307,18 +355,19 @@ 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, LocalChatMedia provides chatMedia) {
|
||||
@@ -453,6 +502,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)) {
|
||||
@@ -461,11 +512,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,
|
||||
@@ -526,6 +589,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(
|
||||
|
||||
@@ -33,6 +33,7 @@ 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
|
||||
@@ -44,12 +45,16 @@ 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
|
||||
@@ -110,6 +115,8 @@ data class ChatState(
|
||||
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,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -233,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
|
||||
@@ -242,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(
|
||||
@@ -260,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) {}
|
||||
@@ -291,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) {}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -383,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 ->
|
||||
@@ -421,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) {
|
||||
@@ -507,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) }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -551,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))
|
||||
}
|
||||
@@ -572,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)) }
|
||||
@@ -647,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
|
||||
@@ -671,12 +846,17 @@ class ChatViewModel(app: Application) :
|
||||
* 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.
|
||||
* 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()) }
|
||||
@@ -687,14 +867,15 @@ class ChatViewModel(app: Application) :
|
||||
} catch (_: Exception) {
|
||||
// An older instance, or one out of reach: the cards say what the calls said.
|
||||
}
|
||||
val waited = mutableMapOf<String, Int>()
|
||||
while (true) {
|
||||
delay(JOB_POLL_MS)
|
||||
val now = _state.value
|
||||
val telling = now.mediaJobs.values.filter { awaitsTelling(it.job) && it.at > 0 && (waited[it.job.id] ?: 0) < TELL_ROUNDS }.map { it.job.id }
|
||||
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) {
|
||||
@@ -707,7 +888,7 @@ class ChatViewModel(app: Application) :
|
||||
} catch (_: Exception) {
|
||||
continue
|
||||
}
|
||||
if (awaitsTelling(read)) waited[id] = (waited[id] ?: 0) + 1
|
||||
if (awaitsTelling(read)) toldWaits[id] = (toldWaits[id] ?: 0) + 1
|
||||
_state.update { it.withJobs(listOf(read), SystemClock.elapsedRealtime()) }
|
||||
if (woke(before, read)) woken = true
|
||||
}
|
||||
@@ -716,33 +897,119 @@ class ChatViewModel(app: Application) :
|
||||
}
|
||||
|
||||
/**
|
||||
* The chat was woken (a job ended): its transcript as the server has it now, and the reply
|
||||
* being written there followed. The telling is written a moment before the reply exists, so
|
||||
* where none is live yet the chat is read once more shortly after. While this screen follows
|
||||
* a reply of its own nothing is touched: the wake waits in the queue, and the stream's `next`
|
||||
* brings it.
|
||||
* 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() {
|
||||
private suspend fun rereadAndFollow(rounds: Int = 2, mark: Long = reads.mark(), wanted: () -> Boolean = { true }) {
|
||||
val chat = _state.value.chat ?: return
|
||||
repeat(2) { round ->
|
||||
if (_state.value.live != null) return
|
||||
val read = try {
|
||||
api().chat(chat.id)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
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()
|
||||
}
|
||||
if (_state.value.live != null) return
|
||||
_state.update { it.copy(chat = read.chat, messages = read.messages, more = read.more) }
|
||||
read.live?.let {
|
||||
follow(it)
|
||||
return
|
||||
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 (round == 0) delay(WAKE_PAUSE_MS)
|
||||
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
|
||||
@@ -825,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)
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalInspectionMode
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.clearAndSetSemantics
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.withStyle
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.DiffLine
|
||||
import eu.llembas.android.api.DiffSign
|
||||
import eu.llembas.android.api.DiffView
|
||||
import eu.llembas.android.api.FileDiff
|
||||
import eu.llembas.android.api.view
|
||||
import eu.llembas.android.api.visibly
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.theme.Palette
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
// An edit's diff on its approval card: per file its path, how many lines come and go, and the
|
||||
// changed lines as text -- a sign before each and the theme's colour behind it, in one width of
|
||||
// letter. The lines scroll sideways in a box of their own, so the card never does. Both texts
|
||||
// are a model's and a file's words: one plain Text draws them, and nothing in them is rendered.
|
||||
|
||||
/** The most of one line that is drawn: a line of a megabyte is still one line of the card. */
|
||||
internal const val DIFF_LINE_MOST = 400
|
||||
|
||||
private val DiffShape = RoundedCornerShape(12.dp)
|
||||
|
||||
/**
|
||||
* A line as the card writes it: its sign, then its text cut at [DIFF_LINE_MOST], with whatever
|
||||
* a person could not see in it -- a direction override, a zero-width space, a line separator --
|
||||
* written as its code point ([visibly]).
|
||||
*/
|
||||
internal fun diffRow(line: DiffLine): String {
|
||||
val sign = when (line.sign) {
|
||||
DiffSign.Added -> "+ "
|
||||
DiffSign.Removed -> "- "
|
||||
DiffSign.Same -> " "
|
||||
DiffSign.Gap -> return "⋯"
|
||||
}
|
||||
val long = line.text.length > DIFF_LINE_MOST
|
||||
return sign + visibly(if (long) line.text.take(DIFF_LINE_MOST) else line.text) + if (long) "…" else ""
|
||||
}
|
||||
|
||||
private fun diffText(lines: List<DiffLine>, palette: Palette): AnnotatedString = buildAnnotatedString {
|
||||
lines.forEachIndexed { at, line ->
|
||||
val style = when (line.sign) {
|
||||
DiffSign.Added -> SpanStyle(color = palette.success, background = palette.successSoft)
|
||||
DiffSign.Removed -> SpanStyle(color = palette.danger, background = palette.dangerSoft)
|
||||
DiffSign.Same -> SpanStyle(color = palette.ink)
|
||||
DiffSign.Gap -> SpanStyle(color = palette.inkFaint)
|
||||
}
|
||||
withStyle(style) { append(diffRow(line)) }
|
||||
if (at < lines.lastIndex) append('\n')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The diffs of an item, worked out: null until they are. Off the main thread -- two texts of a
|
||||
* megabyte are not compared inside a frame -- and one file after another, so fifty files hold
|
||||
* one comparison's memory at a time. A screenshot has no later frame: there it is done at once.
|
||||
*/
|
||||
@Composable
|
||||
fun diffViews(diffs: List<FileDiff>): List<DiffView>? {
|
||||
if (diffs.isEmpty()) return emptyList()
|
||||
if (LocalInspectionMode.current) return remember(diffs) { diffs.map { it.view() } }
|
||||
val views by produceState<List<DiffView>?>(null, diffs) {
|
||||
value = withContext(Dispatchers.Default) {
|
||||
diffs.map {
|
||||
ensureActive()
|
||||
it.view()
|
||||
}
|
||||
}
|
||||
}
|
||||
return views
|
||||
}
|
||||
|
||||
/** The diffs of one item of an approval card, a block per file; [views] as [diffViews] gave them. */
|
||||
@Composable
|
||||
fun CardDiffs(diffs: List<FileDiff>, views: List<DiffView>?, modifier: Modifier = Modifier) {
|
||||
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
diffs.forEachIndexed { at, diff -> key(at, diff.path) { FileDiffBlock(diff, views?.getOrNull(at)) } }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One file's change. The path gives (it wraps) and the two counts keep their width. The lines
|
||||
* are folded to the first few; "Show all" opens them, up to what a card lays out. Until [view]
|
||||
* is worked out the block is its path alone.
|
||||
*/
|
||||
@Composable
|
||||
private fun FileDiffBlock(diff: FileDiff, view: DiffView?) {
|
||||
val palette = LocalPalette.current
|
||||
var open by rememberSaveable(diff.path) { mutableStateOf(false) }
|
||||
val path = remember(diff.path) { visibly(diff.path) }
|
||||
Column(Modifier.fillMaxWidth().clip(DiffShape).background(palette.codeBg).border(1.dp, palette.codeBorder, DiffShape)) {
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(path, style = MaterialTheme.typography.bodySmall, fontFamily = FontFamily.Monospace, color = palette.ink)
|
||||
val state = when {
|
||||
diff.deleted -> stringResource(R.string.diff_deleted)
|
||||
diff.made -> stringResource(R.string.files_new_file)
|
||||
else -> null
|
||||
}
|
||||
if (state != null) Text(state, style = MaterialTheme.typography.labelSmall, color = palette.inkMuted)
|
||||
}
|
||||
if (view != null) {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
val counts = stringResource(R.string.diff_counts, view.added.toString(), view.removed.toString())
|
||||
Row(Modifier.clearAndSetSemantics { contentDescription = counts }, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("+${view.added}", style = MaterialTheme.typography.labelMedium, fontFamily = FontFamily.Monospace, color = palette.success)
|
||||
Text("−${view.removed}", style = MaterialTheme.typography.labelMedium, fontFamily = FontFamily.Monospace, color = palette.danger)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (view != null) {
|
||||
// Said once, where every line would otherwise go and come with the same words.
|
||||
view.endings?.let { (from, to) -> DiffNote(stringResource(R.string.diff_endings, from, to)) }
|
||||
val lines = view.shown(open)
|
||||
if (lines.isNotEmpty()) {
|
||||
val text = remember(lines, palette) { diffText(lines, palette) }
|
||||
Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())) {
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
softWrap = false,
|
||||
modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (open && view.beyond > 0) DiffNote(stringResource(R.string.diff_more, view.beyond.toString()))
|
||||
if (view.cut) DiffNote(stringResource(R.string.diff_cut))
|
||||
if (view.folds) {
|
||||
TextButton(onClick = { open = !open }, modifier = Modifier.heightIn(min = 48.dp).padding(horizontal = 4.dp)) {
|
||||
Text(if (open) stringResource(R.string.diff_show_less) else stringResource(R.string.diff_show_all, view.lines.size.toString()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A sentence of the block's own, under its lines. */
|
||||
@Composable
|
||||
private fun DiffNote(text: String) {
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = LocalPalette.current.inkMuted,
|
||||
modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp),
|
||||
)
|
||||
}
|
||||
@@ -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]--
|
||||
}
|
||||
}
|
||||
@@ -75,6 +75,8 @@ private object Pictures {
|
||||
cache.get(key)?.let { return it }
|
||||
if (key in failed) return null
|
||||
val api = context.lembas.instances.client() ?: return null
|
||||
// A picture that comes into view behind the lock, or with the app not in front, waits there.
|
||||
context.lembas.gate.passLater()
|
||||
val bytes = try {
|
||||
fetch(api).takeIf { it.size <= MAX_BYTES }
|
||||
} catch (e: CancellationException) {
|
||||
@@ -126,6 +128,14 @@ fun GeneratedPicture(media: GeneratedMedia, modifier: Modifier = Modifier) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -140,14 +150,14 @@ private fun Picture(key: String, width: Int, height: Int, modifier: Modifier, fe
|
||||
gone = Pictures.isGone(key)
|
||||
}
|
||||
}
|
||||
val ratio = if (width > 0 && height > 0) width.toFloat() / height else 1f
|
||||
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)
|
||||
|
||||
@@ -15,14 +15,18 @@ import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
|
||||
import androidx.compose.material.icons.automirrored.filled.OpenInNew
|
||||
import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Download
|
||||
import androidx.compose.material.icons.filled.ErrorOutline
|
||||
import androidx.compose.material.icons.filled.FolderOpen
|
||||
import androidx.compose.material.icons.filled.FolderZip
|
||||
import androidx.compose.material.icons.filled.HourglassEmpty
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.Movie
|
||||
import androidx.compose.material.icons.filled.MusicNote
|
||||
import androidx.compose.material.icons.filled.PictureAsPdf
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material.icons.filled.ViewInAr
|
||||
@@ -59,8 +63,9 @@ import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.viewer.playTime
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
// What a model made, in the reply: a card for a file (a picture drawn, a video or a track with
|
||||
// Play, a 3D model or anything else as what it is) and a card for a generation still under way.
|
||||
// What a model made or an agent showed, in the reply: a card for a file (a picture drawn, a video
|
||||
// or a track with Play, a PDF with Open, a 3D model or anything else as what it is) and a card for
|
||||
// a generation still under way.
|
||||
// The file is one of the person's Files, so each card leads there, and out of the app the ways
|
||||
// a file leaves it: saved where the person chooses, shared, or opened with another app. The
|
||||
// cards are drawn only where a chat provides [LocalChatMedia] -- the chat's own screen, which
|
||||
@@ -74,6 +79,9 @@ interface MediaActions {
|
||||
/** Play sound or video the person attached. */
|
||||
fun play(attachment: Attachment) {}
|
||||
|
||||
/** Lay a document's pages out over the chat (a PDF). */
|
||||
fun view(media: GeneratedMedia) {}
|
||||
|
||||
/** The folder of the person's Files the file is in. */
|
||||
fun openInFiles(media: GeneratedMedia) {}
|
||||
|
||||
@@ -96,21 +104,39 @@ val LocalChatMedia = compositionLocalOf<ChatMedia?> { null }
|
||||
|
||||
private val CardShape = RoundedCornerShape(16.dp)
|
||||
|
||||
/** The word for what was asked for: a picture, a video, music, a 3D model; the server's own word for anything else. */
|
||||
@Composable
|
||||
internal fun mediaKind(kind: String): String = when (kind) {
|
||||
"image", "image_edit" -> stringResource(R.string.media_image)
|
||||
"video" -> stringResource(R.string.media_video)
|
||||
"music" -> stringResource(R.string.media_music)
|
||||
"model3d" -> stringResource(R.string.media_model)
|
||||
else -> kind
|
||||
/** The string for a kind this app has a word for; null for any other. */
|
||||
internal fun mediaKindWord(kind: String): Int? = when (kind) {
|
||||
"image", "image_edit" -> R.string.media_image
|
||||
"video" -> R.string.media_video
|
||||
"music" -> R.string.media_music
|
||||
"audio" -> R.string.media_audio
|
||||
"model3d" -> R.string.media_model
|
||||
"pdf" -> R.string.media_pdf
|
||||
"archive" -> R.string.media_archive
|
||||
"text" -> R.string.media_text
|
||||
"binary" -> R.string.media_binary
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun mediaIcon(kind: String): ImageVector = when (kind) {
|
||||
/**
|
||||
* The word for what a file is: a picture, a video, music, audio, a 3D model, a PDF, an archive,
|
||||
* a text file, a file. A kind this app does not know is the server's own word for a generated
|
||||
* file and "File" for one an agent showed ([shown]): a shown file always says what it is.
|
||||
*/
|
||||
@Composable
|
||||
internal fun mediaKind(kind: String, shown: Boolean = false): String =
|
||||
mediaKindWord(kind)?.let { stringResource(it) } ?: if (shown) stringResource(R.string.media_binary) else kind
|
||||
|
||||
/** The mark of a kind; `binary` and a kind this app does not know are a file. */
|
||||
internal fun mediaIcon(kind: String): ImageVector = when (kind) {
|
||||
"image", "image_edit" -> Icons.Filled.Image
|
||||
"video" -> Icons.Filled.Movie
|
||||
"music" -> Icons.Filled.MusicNote
|
||||
else -> Icons.Filled.ViewInAr
|
||||
"music", "audio" -> Icons.Filled.MusicNote
|
||||
"model3d" -> Icons.Filled.ViewInAr
|
||||
"pdf" -> Icons.Filled.PictureAsPdf
|
||||
"archive" -> Icons.Filled.FolderZip
|
||||
"text" -> Icons.Filled.Description
|
||||
else -> Icons.AutoMirrored.Filled.InsertDriveFile
|
||||
}
|
||||
|
||||
/** What is known of a file, in one line: what it is, how long, how large, its size in pixels. */
|
||||
@@ -118,7 +144,7 @@ private fun mediaIcon(kind: String): ImageVector = when (kind) {
|
||||
internal fun mediaFacts(media: GeneratedMedia): String {
|
||||
val context = LocalContext.current
|
||||
return listOfNotNull(
|
||||
mediaKind(media.kind).ifBlank { null },
|
||||
mediaKind(media.kind, media.shown).ifBlank { null },
|
||||
media.seconds.takeIf { it > 0 }?.let { playTime((it * 1000).toInt()) },
|
||||
media.size.takeIf { it > 0 }?.let { Formatter.formatShortFileSize(context, it) },
|
||||
if (media.width > 0 && media.height > 0) "${media.width} × ${media.height}" else null,
|
||||
@@ -126,45 +152,33 @@ internal fun mediaFacts(media: GeneratedMedia): String {
|
||||
}
|
||||
|
||||
/**
|
||||
* A file a tool call made. A picture is drawn -- from its attachment where the call has one
|
||||
* ([image]), else from the file itself; a video or a track is its name with Play (48 dp), which
|
||||
* opens the player over the chat; a 3D model and anything this app does not know is what it is.
|
||||
* Under each, four buttons of one size: Open in Files, Download, Share, Open with.
|
||||
* A file a tool call made, or one an agent showed. A picture is drawn -- from its attachment
|
||||
* where the call has one ([image]), else from the file itself; a video or a track is its name
|
||||
* with Play (48 dp), which opens the player over the chat; a PDF is its name with Open, which
|
||||
* lays its pages out over the chat; a 3D model, an archive and anything this app does not know
|
||||
* is its name and what it is. Under each, four buttons of one size: Open in Files, Download,
|
||||
* Share, Open with.
|
||||
*
|
||||
* A file that was shown is always named: its picture has its name and facts under it, so one
|
||||
* that cannot be drawn on this phone (too large, a format the phone does not read) is still a
|
||||
* name, a kind in words and the ways to the file.
|
||||
*/
|
||||
@Composable
|
||||
fun MediaCard(media: GeneratedMedia, image: GeneratedImage?, actions: MediaActions, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
Column(modifier.widthIn(max = 480.dp).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
when (media.view) {
|
||||
MediaView.Picture -> if (image != null && image.id.isNotBlank()) GeneratedPicture(image) else GeneratedPicture(media)
|
||||
|
||||
MediaView.Video, MediaView.Sound, MediaView.Details -> Row(
|
||||
Modifier.fillMaxWidth().border(1.dp, palette.border, CardShape).padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (media.view == MediaView.Details) {
|
||||
Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) {
|
||||
Icon(mediaIcon(media.kind), contentDescription = null, tint = palette.inkMuted)
|
||||
}
|
||||
} else {
|
||||
FilledIconButton(
|
||||
onClick = { actions.play(media) },
|
||||
colors = IconButtonDefaults.filledIconButtonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.size(48.dp),
|
||||
) { Icon(Icons.Filled.PlayArrow, contentDescription = stringResource(R.string.play)) }
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(media.title, style = MaterialTheme.typography.bodyLarge, color = palette.ink, maxLines = 1, overflow = TextOverflow.MiddleEllipsis)
|
||||
Text(
|
||||
mediaFacts(media),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
MediaView.Picture -> {
|
||||
// A result that names no node has no picture to ask for: its row stands in, so the card is never empty.
|
||||
val drawable = (image != null && image.id.isNotBlank()) || media.nodeId.isNotBlank()
|
||||
if (image != null && image.id.isNotBlank()) GeneratedPicture(image) else GeneratedPicture(media)
|
||||
if (media.shown && drawable) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 4.dp)) { MediaWords(media) }
|
||||
} else if (!drawable) {
|
||||
MediaRow(media, actions)
|
||||
}
|
||||
}
|
||||
|
||||
MediaView.Video, MediaView.Sound, MediaView.Document, MediaView.Details -> MediaRow(media, actions)
|
||||
}
|
||||
// Four buttons of 48 dp: nothing here depends on how long a word is in any language.
|
||||
Row {
|
||||
@@ -176,6 +190,44 @@ fun MediaCard(media: GeneratedMedia, image: GeneratedImage?, actions: MediaActio
|
||||
}
|
||||
}
|
||||
|
||||
/** The file's name on one line (its middle gives) and what is known of it on the next. */
|
||||
@Composable
|
||||
private fun MediaWords(media: GeneratedMedia) {
|
||||
val palette = LocalPalette.current
|
||||
Text(media.title, style = MaterialTheme.typography.bodyLarge, color = palette.ink, maxLines = 1, overflow = TextOverflow.MiddleEllipsis)
|
||||
Text(mediaFacts(media), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
|
||||
/**
|
||||
* A file as a row: a mark of 48 dp -- Play for sound and video, Open for a PDF, else the kind's
|
||||
* icon -- and the file's words, which give.
|
||||
*/
|
||||
@Composable
|
||||
private fun MediaRow(media: GeneratedMedia, actions: MediaActions) {
|
||||
val palette = LocalPalette.current
|
||||
Row(
|
||||
Modifier.fillMaxWidth().border(1.dp, palette.border, CardShape).padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
val filled = IconButtonDefaults.filledIconButtonColors(containerColor = palette.accent, contentColor = palette.accentInk)
|
||||
when (media.view) {
|
||||
MediaView.Video, MediaView.Sound -> FilledIconButton(onClick = { actions.play(media) }, colors = filled, modifier = Modifier.size(48.dp)) {
|
||||
Icon(Icons.Filled.PlayArrow, contentDescription = stringResource(R.string.play))
|
||||
}
|
||||
|
||||
MediaView.Document -> FilledIconButton(onClick = { actions.view(media) }, colors = filled, modifier = Modifier.size(48.dp)) {
|
||||
Icon(mediaIcon(media.kind), contentDescription = stringResource(R.string.viewer_open))
|
||||
}
|
||||
|
||||
MediaView.Picture, MediaView.Details -> Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) {
|
||||
Icon(mediaIcon(media.kind), contentDescription = null, tint = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) { MediaWords(media) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CardButton(icon: ImageVector, label: Int, onClick: () -> Unit) {
|
||||
IconButton(onClick = onClick) { Icon(icon, contentDescription = stringResource(label), tint = LocalPalette.current.inkMuted) }
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,8 @@ 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
|
||||
@@ -91,9 +93,11 @@ 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
|
||||
@@ -112,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) }
|
||||
@@ -165,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))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -253,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
|
||||
@@ -267,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(
|
||||
@@ -354,13 +398,13 @@ internal fun footLine(message: Message, models: List<ModelInfo> = emptyList()):
|
||||
|
||||
/** 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]
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -439,7 +439,7 @@ fun FilesScreen(onBack: () -> Unit, start: String? = null, model: FilesViewModel
|
||||
model.clearSelection()
|
||||
}
|
||||
|
||||
override fun openWith(entry: FileEntry) = transfers.openWith(entry.path, entry.name, entry.mime)
|
||||
override fun openWith(entry: FileEntry) = transfers.openWith(entry.path, entry.name)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -91,13 +91,14 @@ class TransferViewModel(app: Application) : AndroidViewModel(app) {
|
||||
_state.update { it.copy(notice = app.getString(R.string.files_downloaded)) }
|
||||
}
|
||||
|
||||
fun openWith(path: String, name: String, mime: String) = openWith(Raw.Path(path), name, mime)
|
||||
fun openWith(path: String, name: String) = openWith(Raw.Path(path), name)
|
||||
|
||||
fun openWith(what: Raw, name: String, mime: String) = start { api, progress ->
|
||||
/** A copy for another app to open; its type is read from the copy ([Handover.view]), not taken from the instance. */
|
||||
fun openWith(what: Raw, name: String) = start { api, progress ->
|
||||
FileCache.sweepShared(app)
|
||||
turn()
|
||||
val copy = api.copyInto(api.raw(what), FileCache.shared(app, name), progress = progress)
|
||||
_state.update { it.copy(launch = Handover.view(app, copy, mime)) }
|
||||
_state.update { it.copy(launch = Handover.view(app, copy)) }
|
||||
}
|
||||
|
||||
/** One thing that is not named by a path (a generated file by its id), shared as itself. */
|
||||
|
||||
@@ -8,12 +8,15 @@ import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.provider.DocumentsContract
|
||||
import android.provider.OpenableColumns
|
||||
import android.webkit.MimeTypeMap
|
||||
import androidx.activity.result.contract.ActivityResultContract
|
||||
import androidx.core.content.FileProvider
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.FileListing
|
||||
import eu.llembas.android.api.SNIFF_BYTES
|
||||
import eu.llembas.android.api.openType
|
||||
import eu.llembas.android.share.SharedSource
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -185,9 +188,24 @@ suspend fun ApiClient.copyInto(request: okhttp3.Request, file: File, most: Long
|
||||
|
||||
/** Hand [files] (cache copies) to another app: "Open with" for one, Share for one or several. Read-only, for this one grant. */
|
||||
object Handover {
|
||||
fun view(context: Context, file: File, mime: String): Intent {
|
||||
/**
|
||||
* "Open with" for the copy [file]. What it is offered as is read from the copy itself
|
||||
* ([openType]: its first bytes, else its name's extension) -- never the type the instance
|
||||
* said, which for a file an agent showed is one more thing a model had a hand in.
|
||||
*/
|
||||
fun view(context: Context, file: File): Intent {
|
||||
val uri = FileCache.uri(context, file)
|
||||
val intent = Intent(Intent.ACTION_VIEW).setDataAndType(uri, mime.ifBlank { "*/*" }).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
// A copy that cannot be read again is offered by its name alone.
|
||||
val head = try {
|
||||
file.inputStream().use { stream ->
|
||||
val bytes = ByteArray(SNIFF_BYTES)
|
||||
bytes.copyOf(stream.read(bytes).coerceAtLeast(0))
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
ByteArray(0)
|
||||
}
|
||||
val named = MimeTypeMap.getSingleton().getMimeTypeFromExtension(file.extension.lowercase())
|
||||
val intent = Intent(Intent.ACTION_VIEW).setDataAndType(uri, openType(head, named)).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
return Intent.createChooser(intent, null)
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -117,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)
|
||||
|
||||
@@ -137,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) }
|
||||
@@ -164,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
|
||||
@@ -183,6 +199,7 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) {
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
front = false
|
||||
live?.cancel()
|
||||
live = null
|
||||
}
|
||||
@@ -210,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)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.17. Do not edit.
|
||||
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.19. Do not edit.
|
||||
package eu.llembas.android.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
@@ -228,9 +228,19 @@ class PdfPages(private val copy: File) {
|
||||
}
|
||||
}
|
||||
|
||||
/** A PDF, page by page, as wide as the screen. */
|
||||
/** A PDF of the tree, page by page, as wide as the screen. */
|
||||
@Composable
|
||||
fun PdfBody(path: String, name: String, size: Long, fallback: @Composable (String?) -> Unit) {
|
||||
fun PdfBody(path: String, name: String, size: Long, fallback: @Composable (String?) -> Unit) =
|
||||
PdfBody(Raw.Path(path), name, size, gone = null, fallback = fallback)
|
||||
|
||||
/**
|
||||
* The same for any [Raw]: a file a chat names by its node id is copied and laid out as one of
|
||||
* the tree is. [gone] is what to say of a file that is no longer there, where the instance's own
|
||||
* refusal would name an id.
|
||||
*/
|
||||
@Composable
|
||||
fun PdfBody(what: Raw, name: String, size: Long, gone: String? = null, fallback: @Composable (String?) -> Unit) {
|
||||
val path = what
|
||||
val context = LocalContext.current
|
||||
var pages by remember(path) { mutableStateOf<Fetched<PdfPages>>(Fetched.Loading()) }
|
||||
DisposableEffect(path) {
|
||||
@@ -248,7 +258,7 @@ fun PdfBody(path: String, name: String, size: Long, fallback: @Composable (Strin
|
||||
pages = try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
context.lembas.gate.pass()
|
||||
api.copyInto(api.rawFile(path), copy, PDF_MAX_BYTES, stepped { done, total -> pages = Fetched.Loading(done, total) })
|
||||
api.copyInto(api.raw(what), copy, PDF_MAX_BYTES, stepped { done, total -> pages = Fetched.Loading(done, total) })
|
||||
withContext(Dispatchers.IO) { made = PdfPages(copy) }
|
||||
Fetched.Ready(checkNotNull(made))
|
||||
} catch (e: CancellationException) {
|
||||
@@ -259,7 +269,13 @@ fun PdfBody(path: String, name: String, size: Long, fallback: @Composable (Strin
|
||||
made?.closeLater()
|
||||
copy.delete()
|
||||
// A password, or not a PDF after all: the renderer's own words are for a developer.
|
||||
Fetched.Failed(if (e is ApiException || unreachable(e)) viewerSays(context, e) else null)
|
||||
Fetched.Failed(
|
||||
when {
|
||||
gone != null && e is ApiException && e.status == 404 -> gone
|
||||
e is ApiException || unreachable(e) -> viewerSays(context, e)
|
||||
else -> null
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
when (val now = pages) {
|
||||
@@ -469,6 +485,40 @@ fun MediaBody(what: Raw, size: Long, video: Boolean, fallback: @Composable (Stri
|
||||
/** What a player opened over a chat plays: which bytes, what it is called, how large, and whether there is a picture. */
|
||||
data class Playing(val what: Raw, val title: String, val size: Long, val video: Boolean)
|
||||
|
||||
/** A document a chat names, to be laid out over it: a PDF an agent showed. */
|
||||
data class Reading(val what: Raw, val title: String, val size: Long)
|
||||
|
||||
/**
|
||||
* A PDF over the whole screen, for a file a chat names by its node id: its pages as the tree's
|
||||
* viewer lays them out, from a copy in the private cache. One that is no longer there says so
|
||||
* ([gone]); one this phone cannot lay out says that it can still be downloaded. Back or the cross
|
||||
* closes it.
|
||||
*/
|
||||
@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun DocumentDialog(reading: Reading, onClose: () -> Unit, gone: String) {
|
||||
val palette = LocalPalette.current
|
||||
val unreadable: @Composable (String?) -> Unit = { note ->
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(note ?: stringResource(R.string.files_not_shown), color = palette.inkMuted, modifier = Modifier.padding(32.dp))
|
||||
}
|
||||
}
|
||||
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = onClose) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = { Text(reading.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
PdfBody(reading.what, reading.title, reading.size, gone = gone, fallback = unreadable)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** How a player's file was found before it was handed to the player. */
|
||||
private sealed interface Probed {
|
||||
data object Asking : Probed
|
||||
|
||||
@@ -182,7 +182,7 @@ fun TreeFileViewer(path: String, onClose: () -> Unit, startEditing: Boolean = fa
|
||||
object : FileActions {
|
||||
override fun download() = saveTo.launch(CreateFile.Ask(name, file?.mime.orEmpty()))
|
||||
|
||||
override fun openWith() = transfers.openWith(path, name, file?.mime.orEmpty())
|
||||
override fun openWith() = transfers.openWith(path, name)
|
||||
|
||||
override fun share() = transfers.share(listOf(FileEntry(name = name, path = path, mime = file?.mime.orEmpty())))
|
||||
}
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp" android:height="108dp"
|
||||
android:viewportWidth="108" android:viewportHeight="108">
|
||||
<group android:translateX="26" android:translateY="26" android:scaleX="3.5" android:scaleY="3.5">
|
||||
<path android:fillColor="#0B0D10" android:pathData="M10,0h5v1h-5z M8,1h2v1h-2z M15,1h1v1h-1z M6,2h2v1h-2z M15,2h1v1h-1z M5,3h1v1h-1z M15,3h1v1h-1z M5,4h1v1h-1z M14,4h1v1h-1z M4,5h1v1h-1z M14,5h1v1h-1z M4,6h1v1h-1z M14,6h1v1h-1z M3,7h1v1h-1z M13,7h1v1h-1z M3,8h1v1h-1z M12,8h1v1h-1z M3,9h1v1h-1z M11,9h1v1h-1z M3,10h1v1h-1z M10,10h1v1h-1z M3,11h1v1h-1z M7,11h3v1h-3z M2,12h1v1h-1z M4,12h3v1h-3z M1,13h1v1h-1z M3,13h1v1h-1z M0,14h1v1h-1z M2,14h1v1h-1z M1,15h1v1h-1z"/>
|
||||
<path android:fillColor="#4FAE5A" android:pathData="M14,2h1v1h-1z M13,3h2v1h-2z M12,4h2v1h-2z M11,5h3v1h-3z M10,6h4v1h-4z M9,7h4v1h-4z M8,8h4v1h-4z M7,9h4v1h-4z M6,10h4v1h-4z M5,11h2v1h-2z M3,12h1v1h-1z M2,13h1v1h-1z M1,14h1v1h-1z"/>
|
||||
<path android:fillColor="#7EE081" android:pathData="M11,1h4v1h-4z M10,2h2v1h-2z M9,3h2v1h-2z M8,4h2v1h-2z M7,5h2v1h-2z M6,6h2v1h-2z M5,7h2v1h-2z M4,8h2v1h-2z M4,9h1v1h-1z M4,11h1v1h-1z"/>
|
||||
<path android:fillColor="#B6F2A6" android:pathData="M10,1h1v1h-1z M8,2h2v1h-2z M6,3h3v1h-3z M6,4h2v1h-2z M5,5h2v1h-2z M5,6h1v1h-1z M4,7h1v1h-1z"/>
|
||||
<path android:fillColor="#D8FFD0" android:pathData="M12,2h2v1h-2z M11,3h2v1h-2z M10,4h2v1h-2z M9,5h2v1h-2z M8,6h2v1h-2z M7,7h2v1h-2z M6,8h2v1h-2z M5,9h2v1h-2z M4,10h2v1h-2z"/>
|
||||
<group android:translateX="21" android:translateY="21" android:scaleX="2.75" android:scaleY="2.75">
|
||||
<path android:fillColor="#0B0D10" android:pathData="M12,2h5v1h-5z M10,3h2v1h-2z M17,3h1v1h-1z M8,4h2v1h-2z M17,4h1v1h-1z M7,5h1v1h-1z M17,5h1v1h-1z M7,6h1v1h-1z M16,6h1v1h-1z M6,7h1v1h-1z M16,7h1v1h-1z M6,8h1v1h-1z M16,8h1v1h-1z M5,9h1v1h-1z M15,9h1v1h-1z M5,10h1v1h-1z M14,10h1v1h-1z M5,11h1v1h-1z M13,11h1v1h-1z M5,12h1v1h-1z M12,12h1v1h-1z M5,13h1v1h-1z M9,13h3v1h-3z M4,14h1v1h-1z M6,14h3v1h-3z M3,15h1v1h-1z M5,15h1v1h-1z M2,16h1v1h-1z M4,16h1v1h-1z M3,17h1v1h-1z"/>
|
||||
<path android:fillColor="#4FAE5A" android:pathData="M16,4h1v1h-1z M15,5h2v1h-2z M14,6h2v1h-2z M13,7h3v1h-3z M12,8h4v1h-4z M11,9h4v1h-4z M10,10h4v1h-4z M9,11h4v1h-4z M8,12h4v1h-4z M7,13h2v1h-2z M5,14h1v1h-1z M4,15h1v1h-1z M3,16h1v1h-1z"/>
|
||||
<path android:fillColor="#7EE081" android:pathData="M13,3h4v1h-4z M12,4h2v1h-2z M11,5h2v1h-2z M10,6h2v1h-2z M9,7h2v1h-2z M8,8h2v1h-2z M7,9h2v1h-2z M6,10h2v1h-2z M6,11h1v1h-1z M6,13h1v1h-1z"/>
|
||||
<path android:fillColor="#B6F2A6" android:pathData="M12,3h1v1h-1z M10,4h2v1h-2z M8,5h3v1h-3z M8,6h2v1h-2z M7,7h2v1h-2z M7,8h1v1h-1z M6,9h1v1h-1z"/>
|
||||
<path android:fillColor="#C792EA" android:pathData="M15,14h5v1h-5z M15,15h1v1h-1z M19,15h1v1h-1z M15,16h1v1h-1z M19,16h1v1h-1z M15,17h1v1h-1z M19,17h1v1h-1z M15,18h1v1h-1z M19,18h1v1h-1z M15,19h1v1h-1z M17,19h1v1h-1z M19,19h1v1h-1z M15,20h5v1h-5z"/>
|
||||
<path android:fillColor="#D8FFD0" android:pathData="M14,4h2v1h-2z M13,5h2v1h-2z M12,6h2v1h-2z M11,7h2v1h-2z M10,8h2v1h-2z M9,9h2v1h-2z M8,10h2v1h-2z M7,11h2v1h-2z M6,12h2v1h-2z"/>
|
||||
</group>
|
||||
</vector>
|
||||
@@ -3,7 +3,7 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp" android:height="108dp"
|
||||
android:viewportWidth="108" android:viewportHeight="108">
|
||||
<group android:translateX="26" android:translateY="26" android:scaleX="3.5" android:scaleY="3.5">
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M10,0h5v1h-5z M8,1h2v1h-2z M10,1h1v1h-1z M11,1h4v1h-4z M15,1h1v1h-1z M6,2h2v1h-2z M8,2h2v1h-2z M10,2h2v1h-2z M12,2h2v1h-2z M14,2h1v1h-1z M15,2h1v1h-1z M5,3h1v1h-1z M6,3h3v1h-3z M9,3h2v1h-2z M11,3h2v1h-2z M13,3h2v1h-2z M15,3h1v1h-1z M5,4h1v1h-1z M6,4h2v1h-2z M8,4h2v1h-2z M10,4h2v1h-2z M12,4h2v1h-2z M14,4h1v1h-1z M4,5h1v1h-1z M5,5h2v1h-2z M7,5h2v1h-2z M9,5h2v1h-2z M11,5h3v1h-3z M14,5h1v1h-1z M4,6h1v1h-1z M5,6h1v1h-1z M6,6h2v1h-2z M8,6h2v1h-2z M10,6h4v1h-4z M14,6h1v1h-1z M3,7h1v1h-1z M4,7h1v1h-1z M5,7h2v1h-2z M7,7h2v1h-2z M9,7h4v1h-4z M13,7h1v1h-1z M3,8h1v1h-1z M4,8h2v1h-2z M6,8h2v1h-2z M8,8h4v1h-4z M12,8h1v1h-1z M3,9h1v1h-1z M4,9h1v1h-1z M5,9h2v1h-2z M7,9h4v1h-4z M11,9h1v1h-1z M3,10h1v1h-1z M4,10h2v1h-2z M6,10h4v1h-4z M10,10h1v1h-1z M3,11h1v1h-1z M4,11h1v1h-1z M5,11h2v1h-2z M7,11h3v1h-3z M2,12h1v1h-1z M3,12h1v1h-1z M4,12h3v1h-3z M1,13h1v1h-1z M2,13h1v1h-1z M3,13h1v1h-1z M0,14h1v1h-1z M1,14h1v1h-1z M2,14h1v1h-1z M1,15h1v1h-1z"/>
|
||||
<group android:translateX="21" android:translateY="21" android:scaleX="2.75" android:scaleY="2.75">
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M12,2h5v1h-5z M10,3h2v1h-2z M12,3h1v1h-1z M13,3h4v1h-4z M17,3h1v1h-1z M8,4h2v1h-2z M10,4h2v1h-2z M12,4h2v1h-2z M14,4h2v1h-2z M16,4h1v1h-1z M17,4h1v1h-1z M7,5h1v1h-1z M8,5h3v1h-3z M11,5h2v1h-2z M13,5h2v1h-2z M15,5h2v1h-2z M17,5h1v1h-1z M7,6h1v1h-1z M8,6h2v1h-2z M10,6h2v1h-2z M12,6h2v1h-2z M14,6h2v1h-2z M16,6h1v1h-1z M6,7h1v1h-1z M7,7h2v1h-2z M9,7h2v1h-2z M11,7h2v1h-2z M13,7h3v1h-3z M16,7h1v1h-1z M6,8h1v1h-1z M7,8h1v1h-1z M8,8h2v1h-2z M10,8h2v1h-2z M12,8h4v1h-4z M16,8h1v1h-1z M5,9h1v1h-1z M6,9h1v1h-1z M7,9h2v1h-2z M9,9h2v1h-2z M11,9h4v1h-4z M15,9h1v1h-1z M5,10h1v1h-1z M6,10h2v1h-2z M8,10h2v1h-2z M10,10h4v1h-4z M14,10h1v1h-1z M5,11h1v1h-1z M6,11h1v1h-1z M7,11h2v1h-2z M9,11h4v1h-4z M13,11h1v1h-1z M5,12h1v1h-1z M6,12h2v1h-2z M8,12h4v1h-4z M12,12h1v1h-1z M5,13h1v1h-1z M6,13h1v1h-1z M7,13h2v1h-2z M9,13h3v1h-3z M4,14h1v1h-1z M5,14h1v1h-1z M6,14h3v1h-3z M3,15h1v1h-1z M4,15h1v1h-1z M5,15h1v1h-1z M2,16h1v1h-1z M3,16h1v1h-1z M4,16h1v1h-1z M3,17h1v1h-1z M15,14h5v1h-5z M15,15h1v1h-1z M19,15h1v1h-1z M15,16h1v1h-1z M19,16h1v1h-1z M15,17h1v1h-1z M19,17h1v1h-1z M15,18h1v1h-1z M19,18h1v1h-1z M15,19h1v1h-1z M17,19h1v1h-1z M19,19h1v1h-1z M15,20h5v1h-5z"/>
|
||||
</group>
|
||||
</vector>
|
||||
@@ -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>
|
||||
@@ -410,6 +415,18 @@
|
||||
<string name="media_video">Video</string>
|
||||
<string name="media_music">Hudba</string>
|
||||
<string name="media_model">3D model</string>
|
||||
<string name="media_audio">Zvuk</string>
|
||||
<string name="media_pdf">PDF</string>
|
||||
<string name="media_archive">Archiv</string>
|
||||
<string name="media_text">Textový soubor</string>
|
||||
<string name="media_binary">Soubor</string>
|
||||
<string name="diff_deleted">Smazáno</string>
|
||||
<string name="diff_counts">Přidané řádky: %1$s, odebrané: %2$s</string>
|
||||
<string name="diff_show_all">Zobrazit všechny řádky (%1$s)</string>
|
||||
<string name="diff_show_less">Zobrazit méně</string>
|
||||
<string name="diff_more">Další řádky, které se zde nezobrazují: %1$s.</string>
|
||||
<string name="diff_endings">Konce řádků se mění z %1$s na %2$s.</string>
|
||||
<string name="diff_cut">Tato změna je příliš dlouhá na to, aby se zde porovnala. Zobrazen je jen její začátek.</string>
|
||||
<string name="media_gone">Tento soubor už neexistuje.</string>
|
||||
<string name="job_queued">Ve frontě</string>
|
||||
<string name="job_running">Běží</string>
|
||||
|
||||
@@ -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>
|
||||
@@ -410,6 +415,18 @@
|
||||
<string name="media_video">Video</string>
|
||||
<string name="media_music">Musik</string>
|
||||
<string name="media_model">3D-Modell</string>
|
||||
<string name="media_audio">Audio</string>
|
||||
<string name="media_pdf">PDF</string>
|
||||
<string name="media_archive">Archiv</string>
|
||||
<string name="media_text">Textdatei</string>
|
||||
<string name="media_binary">Datei</string>
|
||||
<string name="diff_deleted">Gelöscht</string>
|
||||
<string name="diff_counts">Zeilen hinzugefügt: %1$s, entfernt: %2$s</string>
|
||||
<string name="diff_show_all">Alle %1$s Zeilen anzeigen</string>
|
||||
<string name="diff_show_less">Weniger anzeigen</string>
|
||||
<string name="diff_more">%1$s weitere Zeilen werden hier nicht angezeigt.</string>
|
||||
<string name="diff_endings">Die Zeilenenden ändern sich von %1$s zu %2$s.</string>
|
||||
<string name="diff_cut">Diese Änderung ist zu lang, um hier verglichen zu werden. Nur ihr Anfang wird angezeigt.</string>
|
||||
<string name="media_gone">Diese Datei gibt es nicht mehr.</string>
|
||||
<string name="job_queued">In der Warteschlange</string>
|
||||
<string name="job_running">Läuft</string>
|
||||
|
||||
@@ -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>
|
||||
@@ -410,6 +415,18 @@
|
||||
<string name="media_video">Vídeo</string>
|
||||
<string name="media_music">Música</string>
|
||||
<string name="media_model">Modelo 3D</string>
|
||||
<string name="media_audio">Audio</string>
|
||||
<string name="media_pdf">PDF</string>
|
||||
<string name="media_archive">Archivo comprimido</string>
|
||||
<string name="media_text">Archivo de texto</string>
|
||||
<string name="media_binary">Archivo</string>
|
||||
<string name="diff_deleted">Eliminado</string>
|
||||
<string name="diff_counts">Líneas añadidas: %1$s, eliminadas: %2$s</string>
|
||||
<string name="diff_show_all">Mostrar las %1$s líneas</string>
|
||||
<string name="diff_show_less">Mostrar menos</string>
|
||||
<string name="diff_more">Aquí no se muestran %1$s líneas más.</string>
|
||||
<string name="diff_endings">Los finales de línea cambian de %1$s a %2$s.</string>
|
||||
<string name="diff_cut">Este cambio es demasiado largo para compararlo aquí. Solo se muestra su comienzo.</string>
|
||||
<string name="media_gone">Ese archivo ya no existe.</string>
|
||||
<string name="job_queued">En cola</string>
|
||||
<string name="job_running">En ejecución</string>
|
||||
|
||||
@@ -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>
|
||||
@@ -410,6 +415,18 @@
|
||||
<string name="media_video">Vidéo</string>
|
||||
<string name="media_music">Musique</string>
|
||||
<string name="media_model">Modèle 3D</string>
|
||||
<string name="media_audio">Audio</string>
|
||||
<string name="media_pdf">PDF</string>
|
||||
<string name="media_archive">Archive</string>
|
||||
<string name="media_text">Fichier texte</string>
|
||||
<string name="media_binary">Fichier</string>
|
||||
<string name="diff_deleted">Supprimé</string>
|
||||
<string name="diff_counts">Lignes ajoutées : %1$s, supprimées : %2$s</string>
|
||||
<string name="diff_show_all">Afficher les %1$s lignes</string>
|
||||
<string name="diff_show_less">Afficher moins</string>
|
||||
<string name="diff_more">%1$s lignes de plus ne sont pas affichées ici.</string>
|
||||
<string name="diff_endings">Les fins de ligne passent de %1$s à %2$s.</string>
|
||||
<string name="diff_cut">Cette modification est trop longue pour être comparée ici. Seul son début est affiché.</string>
|
||||
<string name="media_gone">Ce fichier n\'existe plus.</string>
|
||||
<string name="job_queued">En file d’attente</string>
|
||||
<string name="job_running">En cours</string>
|
||||
|
||||
@@ -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>
|
||||
@@ -410,6 +415,18 @@
|
||||
<string name="media_video">Videó</string>
|
||||
<string name="media_music">Zene</string>
|
||||
<string name="media_model">3D-modell</string>
|
||||
<string name="media_audio">Hang</string>
|
||||
<string name="media_pdf">PDF</string>
|
||||
<string name="media_archive">Archívum</string>
|
||||
<string name="media_text">Szövegfájl</string>
|
||||
<string name="media_binary">Fájl</string>
|
||||
<string name="diff_deleted">Törölve</string>
|
||||
<string name="diff_counts">Hozzáadott sorok: %1$s, eltávolított: %2$s</string>
|
||||
<string name="diff_show_all">Mind a(z) %1$s sor megjelenítése</string>
|
||||
<string name="diff_show_less">Kevesebb megjelenítése</string>
|
||||
<string name="diff_more">További %1$s sor itt nem látható.</string>
|
||||
<string name="diff_endings">A sorvégek megváltoznak: %1$s helyett %2$s.</string>
|
||||
<string name="diff_cut">Ez a változás túl hosszú ahhoz, hogy itt össze lehessen hasonlítani. Csak az eleje látható.</string>
|
||||
<string name="media_gone">Ez a fájl már nem létezik.</string>
|
||||
<string name="job_queued">Sorban áll</string>
|
||||
<string name="job_running">Fut</string>
|
||||
|
||||
@@ -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>
|
||||
@@ -410,6 +415,18 @@
|
||||
<string name="media_video">Video</string>
|
||||
<string name="media_music">Musica</string>
|
||||
<string name="media_model">Modello 3D</string>
|
||||
<string name="media_audio">Audio</string>
|
||||
<string name="media_pdf">PDF</string>
|
||||
<string name="media_archive">Archivio</string>
|
||||
<string name="media_text">File di testo</string>
|
||||
<string name="media_binary">File</string>
|
||||
<string name="diff_deleted">Eliminato</string>
|
||||
<string name="diff_counts">Righe aggiunte: %1$s, rimosse: %2$s</string>
|
||||
<string name="diff_show_all">Mostra tutte le %1$s righe</string>
|
||||
<string name="diff_show_less">Mostra meno</string>
|
||||
<string name="diff_more">Altre %1$s righe non sono mostrate qui.</string>
|
||||
<string name="diff_endings">I fine riga cambiano da %1$s a %2$s.</string>
|
||||
<string name="diff_cut">Questa modifica è troppo lunga per essere confrontata qui. Ne è mostrato solo l’inizio.</string>
|
||||
<string name="media_gone">Questo file non esiste più.</string>
|
||||
<string name="job_queued">In coda</string>
|
||||
<string name="job_running">In esecuzione</string>
|
||||
|
||||
@@ -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.17 (moria). Do not edit. -->
|
||||
<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.19 (moria). Do not edit. -->
|
||||
<resources>
|
||||
<color name="token_bg">#FF0B0D10</color>
|
||||
<color name="token_surface">#FF11151A</color>
|
||||
|
||||
@@ -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>
|
||||
@@ -410,6 +415,18 @@
|
||||
<string name="media_video">Wideo</string>
|
||||
<string name="media_music">Muzyka</string>
|
||||
<string name="media_model">Model 3D</string>
|
||||
<string name="media_audio">Dźwięk</string>
|
||||
<string name="media_pdf">PDF</string>
|
||||
<string name="media_archive">Archiwum</string>
|
||||
<string name="media_text">Plik tekstowy</string>
|
||||
<string name="media_binary">Plik</string>
|
||||
<string name="diff_deleted">Usunięto</string>
|
||||
<string name="diff_counts">Dodane wiersze: %1$s, usunięte: %2$s</string>
|
||||
<string name="diff_show_all">Pokaż wszystkie wiersze (%1$s)</string>
|
||||
<string name="diff_show_less">Pokaż mniej</string>
|
||||
<string name="diff_more">Dalsze wiersze, których tu nie pokazano: %1$s.</string>
|
||||
<string name="diff_endings">Końce wierszy zmieniają się z %1$s na %2$s.</string>
|
||||
<string name="diff_cut">Ta zmiana jest zbyt długa, by ją tu porównać. Pokazano tylko jej początek.</string>
|
||||
<string name="media_gone">Ten plik już nie istnieje.</string>
|
||||
<string name="job_queued">W kolejce</string>
|
||||
<string name="job_running">Działa</string>
|
||||
|
||||
@@ -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>
|
||||
@@ -410,6 +415,18 @@
|
||||
<string name="media_video">Video</string>
|
||||
<string name="media_music">Hudba</string>
|
||||
<string name="media_model">3D model</string>
|
||||
<string name="media_audio">Zvuk</string>
|
||||
<string name="media_pdf">PDF</string>
|
||||
<string name="media_archive">Archív</string>
|
||||
<string name="media_text">Textový súbor</string>
|
||||
<string name="media_binary">Súbor</string>
|
||||
<string name="diff_deleted">Zmazané</string>
|
||||
<string name="diff_counts">Pridané riadky: %1$s, odobraté: %2$s</string>
|
||||
<string name="diff_show_all">Zobraziť všetky riadky (%1$s)</string>
|
||||
<string name="diff_show_less">Zobraziť menej</string>
|
||||
<string name="diff_more">Ďalšie riadky, ktoré sa tu nezobrazujú: %1$s.</string>
|
||||
<string name="diff_endings">Konce riadkov sa menia z %1$s na %2$s.</string>
|
||||
<string name="diff_cut">Táto zmena je príliš dlhá na to, aby sa tu porovnala. Zobrazený je len jej začiatok.</string>
|
||||
<string name="media_gone">Tento súbor už neexistuje.</string>
|
||||
<string name="job_queued">Vo fronte</string>
|
||||
<string name="job_running">Beží</string>
|
||||
|
||||
@@ -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>
|
||||
@@ -412,6 +417,18 @@
|
||||
<string name="media_video">Video</string>
|
||||
<string name="media_music">Music</string>
|
||||
<string name="media_model">3D model</string>
|
||||
<string name="media_audio">Audio</string>
|
||||
<string name="media_pdf">PDF</string>
|
||||
<string name="media_archive">Archive</string>
|
||||
<string name="media_text">Text file</string>
|
||||
<string name="media_binary">File</string>
|
||||
<string name="diff_deleted">Deleted</string>
|
||||
<string name="diff_counts">Lines added: %1$s, removed: %2$s</string>
|
||||
<string name="diff_show_all">Show all %1$s lines</string>
|
||||
<string name="diff_show_less">Show less</string>
|
||||
<string name="diff_more">%1$s more lines are not shown here.</string>
|
||||
<string name="diff_endings">The line endings change from %1$s to %2$s.</string>
|
||||
<string name="diff_cut">This change is too long to compare here. Only its beginning is shown.</string>
|
||||
<string name="media_gone">That file no longer exists.</string>
|
||||
<string name="job_queued">Queued</string>
|
||||
<string name="job_running">Running</string>
|
||||
|
||||
@@ -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.17 (shire). Do not edit. -->
|
||||
<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.19 (shire). Do not edit. -->
|
||||
<resources>
|
||||
<color name="token_bg">#FFF1EAD6</color>
|
||||
<color name="token_surface">#FFF8F3E5</color>
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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,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,522 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.AskFrame
|
||||
import eu.llembas.android.api.DIFF_FOLD
|
||||
import eu.llembas.android.api.DIFF_MOST
|
||||
import eu.llembas.android.api.DIFF_TEXT_CHARS
|
||||
import eu.llembas.android.api.DIFF_TEXT_LINES
|
||||
import eu.llembas.android.api.DeviceList
|
||||
import eu.llembas.android.api.DiffLine
|
||||
import eu.llembas.android.api.DiffSign
|
||||
import eu.llembas.android.api.EditorModels
|
||||
import eu.llembas.android.api.FileDiff
|
||||
import eu.llembas.android.api.GeneratedMedia
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.MediaView
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.api.TextLines
|
||||
import eu.llembas.android.api.ToolCall
|
||||
import eu.llembas.android.api.diffLines
|
||||
import eu.llembas.android.api.hunks
|
||||
import eu.llembas.android.api.openType
|
||||
import eu.llembas.android.api.showsDetail
|
||||
import eu.llembas.android.api.sniffType
|
||||
import eu.llembas.android.api.textLines
|
||||
import eu.llembas.android.api.view
|
||||
import eu.llembas.android.api.visibly
|
||||
import eu.llembas.android.ui.chat.DIFF_LINE_MOST
|
||||
import eu.llembas.android.ui.chat.approvalTexts
|
||||
import eu.llembas.android.ui.chat.diffRow
|
||||
import eu.llembas.android.ui.chat.mediaKindWord
|
||||
import eu.llembas.android.ui.chat.offersAlways
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.test.runCurrent
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
import kotlinx.serialization.json.boolean
|
||||
import kotlinx.serialization.json.int
|
||||
import kotlinx.serialization.json.jsonArray
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* What the pin after the editor round brought: a file an agent showed in the chat, an edit's
|
||||
* diff on its approval card, and the shapes that are parsed and not drawn yet (a linked
|
||||
* computer's files, an editor's two models).
|
||||
*/
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class ShownMediaTest {
|
||||
private fun contract(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) {
|
||||
"contract/$name.json is missing"
|
||||
}.readText()
|
||||
|
||||
private fun shown(): List<ToolCall> {
|
||||
val calls = LembasJson.parseToJsonElement(contract("tool_media_shown")).jsonObject.getValue("calls")
|
||||
return LembasJson.decodeFromJsonElement(ListSerializer(ToolCall.serializer()), calls)
|
||||
}
|
||||
|
||||
private fun media(kind: String, shown: Boolean = true) = GeneratedMedia(kind = kind, nodeId = "node1", name = "thing", shown = shown)
|
||||
|
||||
// --- A file an agent showed ---------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun aShownFileIsTheCallsMediaAndNeverAnAttachment() {
|
||||
val (picture, pdf, archive) = shown()
|
||||
listOf(picture, pdf, archive).forEach { call ->
|
||||
assertEquals("show", call.name)
|
||||
assertTrue(call.media!!.shown)
|
||||
// No `show` card and no attachment: the card is drawn from `media` alone.
|
||||
assertNull(call.show)
|
||||
assertNull(call.image)
|
||||
assertNull(call.mediaJob)
|
||||
}
|
||||
val image = picture.media!!
|
||||
assertEquals("image", image.kind)
|
||||
assertEquals(MediaView.Picture, image.view)
|
||||
assertEquals("chart.png", image.title)
|
||||
assertEquals(1280, image.width)
|
||||
assertEquals(720, image.height)
|
||||
// Its bytes are asked for by its id, wherever the file is now.
|
||||
assertEquals(Raw.Node("node8"), image.raw)
|
||||
assertEquals("/home/frodo/oven", image.folder)
|
||||
|
||||
assertEquals(MediaView.Document, pdf.media!!.view)
|
||||
assertEquals("report-20260102-030405.pdf", pdf.media!!.title)
|
||||
assertEquals(90_000L, pdf.media!!.size)
|
||||
assertEquals("/home/frodo/Generated", pdf.media!!.folder)
|
||||
|
||||
assertEquals(MediaView.Details, archive.media!!.view)
|
||||
assertEquals(Raw.Node("node10"), archive.media!!.raw)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aGeneratedFileIsNotAShownOne() {
|
||||
val calls = LembasJson.parseToJsonElement(contract("tool_media")).jsonObject.getValue("calls")
|
||||
val made = LembasJson.decodeFromJsonElement(ListSerializer(ToolCall.serializer()), calls).mapNotNull { it.media }
|
||||
assertTrue(made.isNotEmpty())
|
||||
assertTrue(made.none { it.shown })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun everyKindHasACardAndAudioPlaysAsMusicDoes() {
|
||||
assertEquals(MediaView.Picture, media("image").view)
|
||||
assertEquals(MediaView.Sound, media("audio").view)
|
||||
assertEquals(media("music").view, media("audio").view)
|
||||
assertEquals(MediaView.Video, media("video").view)
|
||||
assertEquals(MediaView.Document, media("pdf").view)
|
||||
// What the phone has no viewer for in a chat is its details: a name, a kind, the ways to the file.
|
||||
listOf("model3d", "archive", "binary", "text", "hologram", "").forEach { assertEquals(it, MediaView.Details, media(it).view) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun everyKindTheServerNamesHasAWordAndAnUnknownOneIsStillAFile() {
|
||||
listOf("image", "audio", "video", "pdf", "model3d", "archive", "binary", "text").forEach { kind ->
|
||||
assertNotNull(kind, mediaKindWord(kind))
|
||||
assertTrue(kind, media(kind).knownKind)
|
||||
}
|
||||
assertEquals(R.string.media_audio, mediaKindWord("audio"))
|
||||
assertEquals(R.string.media_pdf, mediaKindWord("pdf"))
|
||||
assertEquals(R.string.media_archive, mediaKindWord("archive"))
|
||||
// No word of its own: the card says "File" for a shown one (`mediaKind`), never nothing.
|
||||
assertNull(mediaKindWord("hologram"))
|
||||
assertFalse(media("hologram").knownKind)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aShownFileWithoutANameIsCalledByItsPath() {
|
||||
val nameless = GeneratedMedia(kind = "binary", path = "/home/frodo/Generated/dump-20260102.bin", shown = true)
|
||||
assertEquals("dump-20260102.bin", nameless.title)
|
||||
// Without an id it is asked for by its path.
|
||||
assertEquals(Raw.Path("/home/frodo/Generated/dump-20260102.bin"), nameless.raw)
|
||||
}
|
||||
|
||||
// --- An edit's diff on its card -----------------------------------------------------------------
|
||||
|
||||
private fun edit() = contractCard().items.single()
|
||||
|
||||
private fun contractCard() = LembasJson.decodeFromString(AskFrame.serializer(), contract("event_ask_edit")).cards.single()
|
||||
|
||||
@Test
|
||||
fun anEditsCardCarriesADiffPerFile() {
|
||||
val card = contractCard()
|
||||
assertEquals("approval", card.kind)
|
||||
val (changed, made, gone) = edit().diffs
|
||||
assertEquals("src/oven.py", changed.path)
|
||||
assertFalse(changed.made)
|
||||
assertFalse(changed.deleted)
|
||||
assertEquals("src/timer.py", made.path)
|
||||
assertNull(made.oldText)
|
||||
assertTrue(made.made)
|
||||
assertEquals("src/old.py", gone.path)
|
||||
assertTrue(gone.deleted)
|
||||
assertFalse(gone.made)
|
||||
// Allow and Deny are the card's usual ones: nothing of the diff goes back with the answer.
|
||||
assertTrue(offersAlways(card))
|
||||
assertTrue(approvalTexts(card.items, emptyMap()).isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aCardWithoutADiffHasNone() {
|
||||
val cards = LembasJson.decodeFromString(AskFrame.serializer(), contract("event_ask")).cards
|
||||
assertTrue(cards.flatMap { it.items }.all { it.diffs.isEmpty() })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aChangedFileShowsWhatGoesAndWhatComes() {
|
||||
val view = edit().diffs[0].view()
|
||||
assertEquals(2, view.added)
|
||||
assertEquals(1, view.removed)
|
||||
assertEquals(
|
||||
listOf(
|
||||
DiffLine(DiffSign.Same, "def bake(loaf):"),
|
||||
DiffLine(DiffSign.Removed, " return loaf.heat(220)"),
|
||||
DiffLine(DiffSign.Added, " # <img src=x onerror=alert(1)>"),
|
||||
DiffLine(DiffSign.Added, " return loaf.heat(240)"),
|
||||
),
|
||||
view.lines,
|
||||
)
|
||||
// A model's words stay words: the line is written as it is, with its sign before it.
|
||||
assertEquals("+ # <img src=x onerror=alert(1)>", diffRow(view.lines[2]))
|
||||
assertEquals("- return loaf.heat(220)", diffRow(view.lines[1]))
|
||||
assertEquals(" def bake(loaf):", diffRow(view.lines[0]))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aNewFileIsAllAddedAndADeletedOneAllRemoved() {
|
||||
val (_, made, gone) = edit().diffs
|
||||
assertEquals(listOf(DiffLine(DiffSign.Added, "MINUTES = 40")), made.view().lines)
|
||||
assertEquals(1 to 0, made.view().let { it.added to it.removed })
|
||||
assertEquals(listOf(DiffLine(DiffSign.Removed, "x = 1")), gone.view().lines)
|
||||
assertEquals(0 to 1, gone.view().let { it.added to it.removed })
|
||||
// A deleted file's new text is not read, whatever it says.
|
||||
assertEquals(gone.view(), gone.copy(newText = "ignored\n").view())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aChangeKeepsALittleAroundItAndLeavesTheRestOut() {
|
||||
val old = (1..40).map { "line $it" }
|
||||
val new = old.toMutableList().also {
|
||||
it[9] = "line ten"
|
||||
it[29] = "line thirty"
|
||||
}
|
||||
val all = diffLines(old, new)
|
||||
assertEquals(42, all.size)
|
||||
val cut = hunks(all)
|
||||
// Three lines before and after each change, and one mark for the lines between them.
|
||||
assertEquals(1, cut.count { it.sign == DiffSign.Gap })
|
||||
assertEquals("line 7", cut.first().text)
|
||||
assertEquals("line 33", cut.last().text)
|
||||
assertEquals(listOf("line 10", "line 30"), cut.filter { it.sign == DiffSign.Removed }.map { it.text })
|
||||
assertEquals(listOf("line ten", "line thirty"), cut.filter { it.sign == DiffSign.Added }.map { it.text })
|
||||
assertEquals(17, cut.size)
|
||||
assertEquals("⋯", diffRow(cut.first { it.sign == DiffSign.Gap }))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun linesThatMovedAreComparedAsTheLongestSharedRun() {
|
||||
val lines = diffLines(listOf("a", "b", "c", "d"), listOf("a", "c", "d", "b"))
|
||||
assertEquals(
|
||||
listOf(
|
||||
DiffLine(DiffSign.Same, "a"),
|
||||
DiffLine(DiffSign.Removed, "b"),
|
||||
DiffLine(DiffSign.Same, "c"),
|
||||
DiffLine(DiffSign.Same, "d"),
|
||||
DiffLine(DiffSign.Added, "b"),
|
||||
),
|
||||
lines,
|
||||
)
|
||||
// The same text is no change, and so no line on the card.
|
||||
assertTrue(FileDiff(path = "same.txt", oldText = "a\nb\n", newText = "a\nb\n").view().lines.isEmpty())
|
||||
// An empty file that is made adds nothing; one without a last newline keeps its last line.
|
||||
assertTrue(FileDiff(path = "empty", oldText = null, newText = "").view().lines.isEmpty())
|
||||
assertEquals(listOf("a", "b"), FileDiff(path = "p", oldText = null, newText = "a\nb").view().lines.map { it.text })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aLongDiffIsFoldedAndAHugeOneIsBounded() {
|
||||
val long = FileDiff(path = "long.txt", oldText = null, newText = (1..1000).joinToString("\n") { "row $it" })
|
||||
val view = long.view()
|
||||
assertEquals(1000, view.added)
|
||||
assertTrue(view.folds)
|
||||
assertEquals(DIFF_FOLD, view.shown(open = false).size)
|
||||
assertEquals(DIFF_MOST, view.shown(open = true).size)
|
||||
assertEquals(1000 - DIFF_MOST, view.beyond)
|
||||
|
||||
val short = edit().diffs[0].view()
|
||||
assertFalse(short.folds)
|
||||
assertEquals(short.lines, short.shown(open = false))
|
||||
assertEquals(0, short.beyond)
|
||||
|
||||
// Two middles too long to compare line against line are not compared: the old goes, the
|
||||
// new comes. They share every line, in the other order -- compared, some would be "same".
|
||||
val a = (1..1500).map { "line $it" }
|
||||
val both = diffLines(a, a.reversed())
|
||||
assertEquals(3000, both.size)
|
||||
assertTrue(both.none { it.sign == DiffSign.Same })
|
||||
assertTrue(both.take(1500).all { it.sign == DiffSign.Removed })
|
||||
assertTrue(both.drop(1500).all { it.sign == DiffSign.Added })
|
||||
// The same two, short enough, are compared: something is found to be the same.
|
||||
val few = (1..50).map { "line $it" }
|
||||
assertTrue(diffLines(few, few.reversed()).any { it.sign == DiffSign.Same })
|
||||
|
||||
// One line of any length is one bounded line of the card; a tab is spaces.
|
||||
val row = diffRow(DiffLine(DiffSign.Added, "x".repeat(5000)))
|
||||
assertEquals(2 + DIFF_LINE_MOST + 1, row.length)
|
||||
assertEquals(" " + " a", diffRow(DiffLine(DiffSign.Same, "\ta")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aTextIsCutBeforeItIsComparedNotAfter() {
|
||||
// Two megabytes of newlines: only the first lines are ever split off.
|
||||
val newlines = "\n".repeat(2_000_000)
|
||||
val cut = textLines(newlines)
|
||||
assertEquals(DIFF_TEXT_LINES, cut.lines.size)
|
||||
assertTrue(cut.cut)
|
||||
// One line of two megabytes: only its beginning is kept.
|
||||
val one = textLines("x".repeat(2_000_000))
|
||||
assertEquals(1, one.lines.size)
|
||||
assertEquals(DIFF_TEXT_CHARS, one.lines.single().length)
|
||||
assertTrue(one.cut)
|
||||
// A text within both bounds is whole, and says so.
|
||||
assertEquals(TextLines(listOf("a", "b"), cut = false), textLines("a\nb\n"))
|
||||
assertEquals(TextLines(listOf("a", "b"), cut = false), textLines("a\nb"))
|
||||
assertEquals(TextLines(listOf("a"), cut = true), textLines("a\nb\n", mostLines = 1))
|
||||
assertEquals(TextLines(listOf("a"), cut = true), textLines("a\nbcd", mostChars = 2))
|
||||
assertEquals(TextLines(listOf("a", "b"), cut = true), textLines("a\nbcd", mostChars = 3))
|
||||
|
||||
// A new file of that size is a card of bounded size that says it is not all there.
|
||||
val huge = FileDiff(path = "huge.txt", oldText = null, newText = (1..100_000).joinToString("\n") { "row $it" }).view()
|
||||
assertTrue(huge.cut)
|
||||
assertEquals(DIFF_TEXT_LINES, huge.added)
|
||||
assertEquals(DIFF_TEXT_LINES, huge.lines.size)
|
||||
assertTrue(huge.says)
|
||||
assertFalse(edit().diffs[0].view().cut)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aChangeOfLineEndingsIsSaidOnceNotAsEveryLine() {
|
||||
val crlf = FileDiff(path = "a.txt", oldText = "one\ntwo\nthree\n", newText = "one\r\ntwo\r\nthree\r\n").view()
|
||||
assertTrue(crlf.lines.isEmpty())
|
||||
assertEquals(0 to 0, crlf.added to crlf.removed)
|
||||
assertEquals("LF" to "CRLF", crlf.endings)
|
||||
assertTrue(crlf.says)
|
||||
// With a real change beside it, only that line goes and comes.
|
||||
val both = FileDiff(path = "a.txt", oldText = "one\r\ntwo\r\n", newText = "one\nTWO\n").view()
|
||||
assertEquals("CRLF" to "LF", both.endings)
|
||||
assertEquals(listOf(DiffSign.Same, DiffSign.Removed, DiffSign.Added), both.lines.map { it.sign })
|
||||
assertEquals(listOf("one", "two", "TWO"), both.lines.map { it.text })
|
||||
// The same endings, a new file, a file of one line: nothing to say of endings.
|
||||
assertNull(edit().diffs[0].view().endings)
|
||||
assertNull(edit().diffs[1].view().endings)
|
||||
assertNull(FileDiff(path = "p", oldText = "a", newText = "a\r\nb\r\n").view().endings)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whatCannotBeSeenIsWrittenAsItsCodePoint() {
|
||||
// A direction override makes a line read as something it is not; a line separator breaks it in two.
|
||||
assertEquals("+ if (admin<U+202E>) {", diffRow(DiffLine(DiffSign.Added, "if (admin\u202E) {")))
|
||||
assertEquals("- a<U+2028>b", diffRow(DiffLine(DiffSign.Removed, "a\u2028b")))
|
||||
assertEquals("a<U+200B>b<U+FEFF><U+2066><U+0000><U+000D><U+0085>", visibly("a\u200Bb\uFEFF\u2066\u0000\r\u0085"))
|
||||
// A path is read too: it names what is changed.
|
||||
assertEquals("src/<U+202E>yp.nevo", visibly("src/\u202Eyp.nevo"))
|
||||
// Ordinary text, other scripts and wide characters are left as they are.
|
||||
listOf("def bake(loaf):", "žltý kôň — ünïcödé", "日本語 \uD83C\uDF5E", "").forEach { assertEquals(it, visibly(it)) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theArgumentsStayInViewWhenTheDiffsSayNothing() {
|
||||
val item = edit()
|
||||
// Diffs that say something stand in the arguments' place, once they are worked out and while they are.
|
||||
assertFalse(showsDetail(item, item.diffs.map { it.view() }))
|
||||
assertFalse(showsDetail(item, null))
|
||||
// The same text twice, or an entry with nothing in it: the card would say "+0 -0" and nothing else.
|
||||
val same = item.copy(diffs = listOf(FileDiff(path = "a.txt", oldText = "a\n", newText = "a\n"), FileDiff()))
|
||||
assertTrue(same.diffs.map { it.view() }.none { it.says })
|
||||
assertTrue(showsDetail(same, same.diffs.map { it.view() }))
|
||||
// A card without diffs is as it always was.
|
||||
assertTrue(showsDetail(item.copy(diffs = emptyList()), emptyList()))
|
||||
assertTrue(showsDetail(item.copy(diffs = emptyList()), null))
|
||||
}
|
||||
|
||||
// --- The gate and the assistant's sheet ---------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun theAssistantsSheetIsTheAppInFrontAndTheLockStillShutsTheGate() = runTest {
|
||||
var locked = false
|
||||
val gate = InstanceGate { locked }
|
||||
// No activity: the sheet is a session's window. A picture in it waits as a chat's does...
|
||||
val fetched = mutableListOf<String>()
|
||||
val picture = launch {
|
||||
gate.passLater()
|
||||
fetched += "picture"
|
||||
}
|
||||
runCurrent()
|
||||
assertTrue(fetched.isEmpty())
|
||||
// ...until the sheet shows, which no activity's start would ever say.
|
||||
gate.sessionShown()
|
||||
runCurrent()
|
||||
assertEquals(listOf("picture"), fetched)
|
||||
picture.join()
|
||||
// Shown again while up, hidden once: shut.
|
||||
gate.sessionShown()
|
||||
gate.sessionHidden()
|
||||
assertFalse(gate.open.value)
|
||||
|
||||
// Over the lock screen the sheet opens nothing; the unlock does.
|
||||
locked = true
|
||||
gate.sessionShown()
|
||||
assertFalse(gate.open.value)
|
||||
locked = false
|
||||
assertTrue(gate.look())
|
||||
// An activity of the app in front keeps the gate open when the sheet goes.
|
||||
gate.activityStarted()
|
||||
gate.sessionHidden()
|
||||
assertTrue(gate.open.value)
|
||||
gate.activityStopped()
|
||||
assertFalse(gate.open.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aSessionTornDownWithoutBeingHiddenLeavesTheGateShut() = runTest {
|
||||
val gate = InstanceGate { false }
|
||||
val sheet = SheetAtGate(gate)
|
||||
// Shown, then destroyed with no hide between them: the end is said all the same.
|
||||
sheet.shown()
|
||||
assertTrue(gate.open.value)
|
||||
sheet.gone()
|
||||
assertFalse(gate.open.value)
|
||||
assertFalse(gate.look())
|
||||
// Nothing asked for now starts until something of the app is in front again.
|
||||
val fetched = mutableListOf<String>()
|
||||
val picture = launch {
|
||||
gate.passLater()
|
||||
fetched += "picture"
|
||||
}
|
||||
runCurrent()
|
||||
assertTrue(fetched.isEmpty())
|
||||
// Hidden and then destroyed, or destroyed twice, is still one end; the next showing opens it.
|
||||
sheet.gone()
|
||||
sheet.gone()
|
||||
assertFalse(gate.open.value)
|
||||
sheet.shown()
|
||||
runCurrent()
|
||||
assertEquals(listOf("picture"), fetched)
|
||||
picture.join()
|
||||
// An activity in front is not undone by the sheet's end.
|
||||
gate.activityStarted()
|
||||
sheet.gone()
|
||||
assertTrue(gate.open.value)
|
||||
}
|
||||
|
||||
// --- Open with ----------------------------------------------------------------------------------
|
||||
|
||||
private fun bytes(vararg values: Int) = ByteArray(values.size) { values[it].toByte() }
|
||||
|
||||
@Test
|
||||
fun aFileIsOfferedAsWhatItsBytesSayNotAsWhatItWasCalled() {
|
||||
val png = bytes(0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A)
|
||||
val pdf = "%PDF-1.7\n".toByteArray()
|
||||
val zip = bytes(0x50, 0x4B, 0x03, 0x04, 0x14, 0x00)
|
||||
assertEquals("image/png", sniffType(png))
|
||||
assertEquals("application/pdf", sniffType(pdf))
|
||||
assertEquals("image/jpeg", sniffType(bytes(0xFF, 0xD8, 0xFF, 0xE0)))
|
||||
assertEquals("video/mp4", sniffType(bytes(0, 0, 0, 0x20) + "ftypisom".toByteArray()))
|
||||
assertEquals("audio/wav", sniffType("RIFF".toByteArray() + bytes(0, 0, 0, 0) + "WAVE".toByteArray()))
|
||||
assertEquals("image/webp", sniffType("RIFF".toByteArray() + bytes(0, 0, 0, 0) + "WEBP".toByteArray()))
|
||||
assertNull(sniffType("just words".toByteArray()))
|
||||
assertNull(sniffType(ByteArray(0)))
|
||||
assertNull(sniffType(bytes(0x89)))
|
||||
|
||||
// The bytes decide, whatever the name says.
|
||||
assertEquals("application/pdf", openType(pdf, "image/png"))
|
||||
assertEquals("image/png", openType(png, null))
|
||||
// No mark in the bytes: the name's extension, else anything.
|
||||
assertEquals("text/plain", openType("just words".toByteArray(), "text/plain"))
|
||||
assertEquals("*/*", openType("just words".toByteArray(), null))
|
||||
assertEquals("*/*", openType(ByteArray(0), ""))
|
||||
// A zip is what many documents are inside: a known extension is the better word there.
|
||||
assertEquals("application/epub+zip", openType(zip, "application/epub+zip"))
|
||||
assertEquals("application/zip", openType(zip, null))
|
||||
}
|
||||
|
||||
// --- Parsed, and not drawn yet ------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun aDeviceSaysWhetherItHandsItsFilesOver() {
|
||||
val (workstation, laptop) = LembasJson.decodeFromString(DeviceList.serializer(), contract("devices")).devices
|
||||
assertTrue(workstation.files)
|
||||
assertTrue(workstation.filesWritable)
|
||||
assertFalse(workstation.filesThatRunCode)
|
||||
assertFalse(laptop.files)
|
||||
assertFalse(laptop.filesWritable)
|
||||
// An instance from before the files says nothing, and that is "no".
|
||||
assertFalse(LembasJson.decodeFromString(DeviceList.serializer(), """{"devices":[{"id":"t1"}]}""").devices.single().files)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anEditorsTwoModelsAreReadSetAndUnset() {
|
||||
val set = LembasJson.decodeFromString(EditorModels.serializer(), contract("editor"))
|
||||
assertEquals("local/qwen", set.autocomplete.model)
|
||||
assertEquals("person", set.autocomplete.source)
|
||||
assertEquals(listOf("local/qwen", "local/vision-small"), set.autocomplete.allowed)
|
||||
assertEquals("local/gpt-oss", set.main.model)
|
||||
|
||||
val unset = LembasJson.decodeFromString(EditorModels.serializer(), contract("editor_unset"))
|
||||
assertNull(unset.autocomplete.model)
|
||||
assertNull(unset.autocomplete.source)
|
||||
assertNull(unset.autocomplete.allowed)
|
||||
assertNull(unset.main.model)
|
||||
}
|
||||
|
||||
private fun fixture(name: String) = LembasJson.parseToJsonElement(contract(name)).jsonObject
|
||||
|
||||
private fun kotlinx.serialization.json.JsonObject.word(key: String) = getValue(key).jsonPrimitive.content
|
||||
|
||||
@Test
|
||||
fun aComputersFilesAndAMessagesEditorContextSayWhatTheApiSays() {
|
||||
// No screen and no model of these here yet. The fields a browser would stand on are
|
||||
// where App-API puts them, so a pin that moves them fails here.
|
||||
val roots = fixture("device_fs_roots")
|
||||
assertEquals("", roots.word("path"))
|
||||
assertTrue(roots.getValue("entries").jsonArray.isNotEmpty())
|
||||
|
||||
val listing = fixture("device_fs_listing")
|
||||
assertEquals("/home/dev/project", listing.word("path"))
|
||||
val entries = listing.getValue("entries").jsonArray.map { it.jsonObject }
|
||||
val keys = setOf("name", "path", "kind", "size", "mtime", "updated_at", "file_kind", "link", "outside", "protected", "runs_code", "writable")
|
||||
entries.forEach { assertEquals(keys, it.keys) }
|
||||
assertTrue(entries.map { it.word("kind") }.containsAll(listOf("dir", "file")))
|
||||
assertTrue(entries.single { it.word("name") == "shared" }.getValue("outside").jsonPrimitive.boolean)
|
||||
assertTrue(entries.single { it.word("name") == ".env" }.getValue("protected").jsonPrimitive.boolean)
|
||||
|
||||
val content = fixture("device_fs_content")
|
||||
assertTrue(content.word("sha").startsWith("sha256:"))
|
||||
assertTrue(content.word("text").isNotEmpty())
|
||||
val withheld = fixture("device_fs_content_withheld")
|
||||
assertEquals("", withheld.word("text"))
|
||||
assertTrue(withheld.getValue("withheld").jsonObject.word("reason") in setOf("not_text", "too_large"))
|
||||
|
||||
val conflict = fixture("device_fs_conflict")
|
||||
assertEquals("changed", conflict.word("reason"))
|
||||
assertTrue(conflict.getValue("conflict").jsonPrimitive.boolean)
|
||||
assertTrue(conflict.word("sha").startsWith("sha256:"))
|
||||
assertEquals("no_trash", fixture("device_fs_no_trash").word("reason"))
|
||||
assertTrue(fixture("device_fs_written").word("sha").startsWith("sha256:"))
|
||||
|
||||
val batch = fixture("device_fs_batch")
|
||||
assertFalse(batch.getValue("atomic").jsonPrimitive.boolean)
|
||||
assertTrue(batch.getValue("results").jsonArray.all { "ok" in it.jsonObject && "path" in it.jsonObject })
|
||||
|
||||
val editor = fixture("message_editor")
|
||||
assertEquals("/home/dev/project/src/oven.py", editor.word("path"))
|
||||
assertEquals(2, editor.getValue("selection").jsonObject.getValue("start").jsonPrimitive.int)
|
||||
assertEquals("warning", editor.getValue("diagnostics").jsonArray.single().jsonObject.word("severity"))
|
||||
}
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -90,6 +90,67 @@ class MediaShots {
|
||||
shoot("60-media-cards", Phone.SmallScroll, fontScale = 1.5f, content = drawn)
|
||||
}
|
||||
|
||||
private fun shown(kind: String, name: String, size: Long, mime: String = "", width: Int = 0, height: Int = 0) = GeneratedMedia(
|
||||
kind = kind,
|
||||
path = "$made/$name",
|
||||
nodeId = "node-$kind",
|
||||
name = name,
|
||||
mime = mime,
|
||||
size = size,
|
||||
width = width,
|
||||
height = height,
|
||||
shown = true,
|
||||
)
|
||||
|
||||
/** Every kind a shown file can be, and one this app has never heard of: each is a name, a kind in words and the ways to the file. */
|
||||
private val shownFiles = listOf(
|
||||
shown("image", "chart.png", 48_211, "image/png", 1280, 720),
|
||||
shown("audio", "a-recording-of-the-meeting-about-the-ovens-20260102-030405.ogg", 3_300_000, "audio/ogg"),
|
||||
shown("video", "screen-recording-20260102-030405.webm", 12_400_000, "video/webm", 1920, 1080),
|
||||
shown("pdf", "report-20260102-030405.pdf", 90_000, "application/pdf"),
|
||||
shown("model3d", "loaf-20260102.glb", 880_000),
|
||||
shown("archive", "bundle-20260102-030405.zip", 1_200_000, "application/zip"),
|
||||
shown("binary", "core-20260102.dump", 64_000_000),
|
||||
shown("text", "notes-on-the-long-fermentation-of-waybread.txt", 2_048, "text/plain"),
|
||||
shown("hologram", "something-new.holo", 512),
|
||||
)
|
||||
|
||||
@Test
|
||||
fun filesAnAgentShowed() {
|
||||
val drawn: @Composable () -> Unit = {
|
||||
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
shownFiles.forEach { MediaCard(it, null, actions) }
|
||||
}
|
||||
}
|
||||
shoot("63-shown-files", Phone.Scroll, content = drawn)
|
||||
shoot("63-shown-files", Phone.SmallScroll, content = drawn)
|
||||
shoot("63-shown-files", Phone.SmallScroll, fontScale = 1.5f, content = drawn)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aChatWithShownFiles() {
|
||||
fun call(id: String, media: GeneratedMedia) = ToolCall(
|
||||
id = id,
|
||||
name = "show",
|
||||
status = "ok",
|
||||
path = media.path,
|
||||
media = media,
|
||||
block = ToolBlock(kind = "tool", title = media.path, state = "done", label = "Shown"),
|
||||
)
|
||||
val reply = Message(
|
||||
id = "m9",
|
||||
role = "assistant",
|
||||
steps = listOf(
|
||||
Step(index = 0, kind = "tools", calls = listOf(call("c1", shownFiles[0]), call("c2", shownFiles[3]), call("c3", shownFiles[5]))),
|
||||
Step(index = 1, kind = "text", markdown = "The chart, the report and everything else in one archive."),
|
||||
),
|
||||
)
|
||||
val state = Fakes.transcript.copy(messages = listOf(Message(id = "m8", role = "user", text = "Show me what the run left."), reply), summary = null)
|
||||
shoot("64-chat-shown") { ChatContent(state, object : ChatActions {}, agent = false, media = actions) }
|
||||
shoot("64-chat-shown", Phone.Small) { ChatContent(state, object : ChatActions {}, agent = false, media = actions) }
|
||||
shoot("64-chat-shown", Phone.Small, fontScale = 1.5f) { ChatContent(state, object : ChatActions {}, agent = false, media = actions) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aChatWithGeneratedMedia() {
|
||||
fun call(id: String, media: GeneratedMedia? = null, job: MediaJob? = null) = ToolCall(
|
||||
|
||||
@@ -28,6 +28,9 @@ import com.github.takahirom.roborazzi.inspectionMode
|
||||
import com.github.takahirom.roborazzi.size
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.actions.NavApp
|
||||
import eu.llembas.android.api.Card
|
||||
import eu.llembas.android.api.CardItem
|
||||
import eu.llembas.android.api.FileDiff
|
||||
import eu.llembas.android.assist.AssistActions
|
||||
import eu.llembas.android.assist.AssistSheetContent
|
||||
import eu.llembas.android.assist.AssistSheetFrame
|
||||
@@ -133,6 +136,53 @@ 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 editDiffCard() {
|
||||
// An edit's approval card with its diff: a changed file with one line wider than the phone
|
||||
// (it scrolls in its own box), a new file long enough to fold, a file that goes, and one
|
||||
// whose line endings change with a character in it that cannot be seen. The
|
||||
// card itself must not be wider than the phone, at a small one's width and large type too.
|
||||
val long = " return loaf.heat(240, minutes=timer.MINUTES, rack=\"middle\", steam=True, turn_after=20) # <b>hotter</b>, as asked"
|
||||
val card = Card(
|
||||
id = "card9",
|
||||
kind = "approval",
|
||||
items = listOf(
|
||||
CardItem(
|
||||
key = "0",
|
||||
kind = "approval",
|
||||
tool = "edit",
|
||||
title = "Edit a file",
|
||||
detail = "{\"path\": \"src/oven.py\"}",
|
||||
reason = "Manual mode asks before every edit.",
|
||||
purpose = "Bake hotter",
|
||||
freeText = false,
|
||||
diffs = listOf(
|
||||
FileDiff(
|
||||
path = "src/bakery/ovens/oven.py",
|
||||
oldText = "import timer\n\n\ndef bake(loaf):\n loaf.proof()\n return loaf.heat(220)\n",
|
||||
newText = "import timer\n\n\ndef bake(loaf):\n loaf.proof()\n # 220 was cool for waybread.\n$long\n",
|
||||
),
|
||||
FileDiff(path = "src/bakery/timer.py", oldText = null, newText = (1..30).joinToString("\n") { "STEP_$it = ${it * 5}" } + "\n"),
|
||||
FileDiff(path = "src/bakery/old.py", oldText = "x = 1\ny = 2\n", newText = "", deleted = true),
|
||||
// Line endings that change are said once; a direction override in a line is written out.
|
||||
FileDiff(path = "src/bakery/notes.txt", oldText = "keep warm\nserve\n", newText = "keep warm\r\nserve\u202E now\r\n"),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
shoot("09-edit-diff", Phone.Scroll) { SheetOver { CardSheet(card, onAnswer = {}) } }
|
||||
shoot("09-edit-diff", Phone.SmallScroll) { SheetOver { CardSheet(card, onAnswer = {}) } }
|
||||
shoot("09-edit-diff", Phone.SmallScroll, fontScale = 1.5f) { SheetOver { CardSheet(card, onAnswer = {}) } }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun writing() {
|
||||
// The 3.4.0 progress line under the reply: `{{text}} · {{elapsed}}`, the clock still.
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"op": "delete",
|
||||
"to": null,
|
||||
"atomic": false,
|
||||
"done": 1,
|
||||
"failed": 1,
|
||||
"results": [
|
||||
{
|
||||
"path": "/home/dev/project/old.md",
|
||||
"ok": true,
|
||||
"trash": true
|
||||
},
|
||||
{
|
||||
"path": "/mnt/usb/old.bin",
|
||||
"ok": false,
|
||||
"error": "This computer has no trash for /mnt/usb/old.bin: deleting it cannot be undone.",
|
||||
"reason": "no_trash"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"detail": "/home/dev/project/oven.py changed on the computer since you opened it.",
|
||||
"reason": "changed",
|
||||
"conflict": true,
|
||||
"sha": "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
|
||||
"mtime": 1767323050000
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"path": "/home/dev/project/oven.py",
|
||||
"name": "oven.py",
|
||||
"size": 412,
|
||||
"mtime": 1767323045000,
|
||||
"mime": "text/x-python",
|
||||
"kind": "code",
|
||||
"file_kind": "code",
|
||||
"writable": true,
|
||||
"language": "python",
|
||||
"sha": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"text": "def bake():\n return 'lembas'\n"
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"path": "/home/dev/project/loaf.png",
|
||||
"name": "loaf.png",
|
||||
"size": 48211,
|
||||
"mtime": 1767323045000,
|
||||
"mime": "image/png",
|
||||
"kind": "image",
|
||||
"file_kind": "image",
|
||||
"writable": true,
|
||||
"language": "",
|
||||
"sha": "",
|
||||
"text": "",
|
||||
"withheld": {
|
||||
"reason": "not_text",
|
||||
"message": "This is not a text file, so it is not shown here."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"deleted": true,
|
||||
"trash": true
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
{
|
||||
"device": "",
|
||||
"path": "/home/dev/project",
|
||||
"parent": "",
|
||||
"writable": false,
|
||||
"entries": [
|
||||
{
|
||||
"name": "src",
|
||||
"path": "/home/dev/project/src",
|
||||
"kind": "dir",
|
||||
"size": 0,
|
||||
"mtime": 1767323045000,
|
||||
"updated_at": "2026-01-02T03:04:05+00:00",
|
||||
"file_kind": null,
|
||||
"link": null,
|
||||
"outside": false,
|
||||
"protected": false,
|
||||
"runs_code": false,
|
||||
"writable": false
|
||||
},
|
||||
{
|
||||
"name": "shared",
|
||||
"path": "/home/dev/project/shared",
|
||||
"kind": "dir",
|
||||
"size": 0,
|
||||
"mtime": 1767323045000,
|
||||
"updated_at": "2026-01-02T03:04:05+00:00",
|
||||
"file_kind": null,
|
||||
"link": "/srv/shared",
|
||||
"outside": true,
|
||||
"protected": false,
|
||||
"runs_code": false,
|
||||
"writable": false
|
||||
},
|
||||
{
|
||||
"name": ".env",
|
||||
"path": "/home/dev/project/.env",
|
||||
"kind": "file",
|
||||
"size": 0,
|
||||
"mtime": 1767323045000,
|
||||
"updated_at": "2026-01-02T03:04:05+00:00",
|
||||
"file_kind": "text",
|
||||
"link": null,
|
||||
"outside": false,
|
||||
"protected": true,
|
||||
"runs_code": false,
|
||||
"writable": false
|
||||
},
|
||||
{
|
||||
"name": "oven.py",
|
||||
"path": "/home/dev/project/oven.py",
|
||||
"kind": "file",
|
||||
"size": 412,
|
||||
"mtime": 1767323045000,
|
||||
"updated_at": "2026-01-02T03:04:05+00:00",
|
||||
"file_kind": "code",
|
||||
"link": null,
|
||||
"outside": false,
|
||||
"protected": false,
|
||||
"runs_code": false,
|
||||
"writable": false
|
||||
},
|
||||
{
|
||||
"name": "loaf.png",
|
||||
"path": "/home/dev/project/loaf.png",
|
||||
"kind": "file",
|
||||
"size": 48211,
|
||||
"mtime": 1767323045000,
|
||||
"updated_at": "2026-01-02T03:04:05+00:00",
|
||||
"file_kind": "binary",
|
||||
"link": null,
|
||||
"outside": false,
|
||||
"protected": false,
|
||||
"runs_code": false,
|
||||
"writable": false
|
||||
},
|
||||
{
|
||||
"name": ".git",
|
||||
"path": "/home/dev/project/.git",
|
||||
"kind": "dir",
|
||||
"size": 0,
|
||||
"mtime": 1767323045000,
|
||||
"updated_at": "2026-01-02T03:04:05+00:00",
|
||||
"file_kind": null,
|
||||
"link": null,
|
||||
"outside": false,
|
||||
"protected": false,
|
||||
"runs_code": true,
|
||||
"writable": false
|
||||
}
|
||||
],
|
||||
"truncated": false
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"detail": "This computer has no trash for /mnt/usb/old.bin: deleting it cannot be undone.",
|
||||
"reason": "no_trash"
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"device": "",
|
||||
"path": "",
|
||||
"parent": "",
|
||||
"writable": false,
|
||||
"entries": [
|
||||
{
|
||||
"name": "project",
|
||||
"path": "/home/dev/project",
|
||||
"kind": "dir",
|
||||
"size": 0,
|
||||
"mtime": 1767323045000,
|
||||
"updated_at": "2026-01-02T03:04:05+00:00",
|
||||
"file_kind": null,
|
||||
"link": null,
|
||||
"outside": false,
|
||||
"protected": false,
|
||||
"runs_code": false,
|
||||
"writable": false
|
||||
}
|
||||
],
|
||||
"truncated": false
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"root": "/home/dev/project",
|
||||
"truncated": false,
|
||||
"files": [
|
||||
{
|
||||
"path": "src/oven.py",
|
||||
"kind": "file"
|
||||
},
|
||||
{
|
||||
"path": "src",
|
||||
"kind": "dir"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"root": "/home/dev/project",
|
||||
"truncated": true,
|
||||
"matches": [
|
||||
{
|
||||
"path": "src/oven.py",
|
||||
"line": 2,
|
||||
"text": " return 'lembas'"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "oven.py",
|
||||
"path": "/home/dev/project/oven.py",
|
||||
"kind": "file",
|
||||
"size": 412,
|
||||
"mtime": 1767323045000,
|
||||
"updated_at": "2026-01-02T03:04:05+00:00",
|
||||
"file_kind": "code",
|
||||
"link": null,
|
||||
"outside": false,
|
||||
"protected": false,
|
||||
"runs_code": false,
|
||||
"writable": false,
|
||||
"sha": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"path": "/home/dev/project/oven.py",
|
||||
"size": 430,
|
||||
"mtime": 1767323054000,
|
||||
"sha": "sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
|
||||
}
|
||||
@@ -10,7 +10,10 @@
|
||||
"terminal_hint": "",
|
||||
"scheduled": true,
|
||||
"max_mode": "edit",
|
||||
"directory_model": true
|
||||
"directory_model": true,
|
||||
"files": true,
|
||||
"files_writable": true,
|
||||
"files_that_run_code": false
|
||||
},
|
||||
{
|
||||
"id": "token2",
|
||||
@@ -22,7 +25,10 @@
|
||||
"terminal_hint": "laptop does not open terminals. Switch it on there: in LLeMbas Desktop's settings, or with the LLeMbas CLI's remote.terminal setting.",
|
||||
"scheduled": false,
|
||||
"max_mode": "",
|
||||
"directory_model": false
|
||||
"directory_model": false,
|
||||
"files": false,
|
||||
"files_writable": false,
|
||||
"files_that_run_code": false
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"autocomplete": {
|
||||
"model": "local/qwen",
|
||||
"source": "person",
|
||||
"allowed": [
|
||||
"local/qwen",
|
||||
"local/vision-small"
|
||||
]
|
||||
},
|
||||
"main": {
|
||||
"model": "local/gpt-oss"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"autocomplete": {
|
||||
"model": null,
|
||||
"source": null,
|
||||
"allowed": null
|
||||
},
|
||||
"main": {
|
||||
"model": null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"cards": [
|
||||
{
|
||||
"id": "card9",
|
||||
"kind": "approval",
|
||||
"why": "",
|
||||
"dismissable": false,
|
||||
"expires_in": 1800,
|
||||
"items": [
|
||||
{
|
||||
"index": 0,
|
||||
"key": "0",
|
||||
"kind": "approval",
|
||||
"tool": "edit",
|
||||
"title": "Edit a file",
|
||||
"header": "",
|
||||
"detail": "{\"path\": \"src/oven.py\"}",
|
||||
"reason": "Manual mode asks before every edit.",
|
||||
"purpose": "Bake hotter",
|
||||
"options": [],
|
||||
"multiple": false,
|
||||
"free_text": false,
|
||||
"always": true,
|
||||
"editable": false,
|
||||
"plan": null,
|
||||
"mode_choice": true,
|
||||
"job": "",
|
||||
"subagent": null,
|
||||
"diffs": [
|
||||
{
|
||||
"path": "src/oven.py",
|
||||
"old_text": "def bake(loaf):\n return loaf.heat(220)\n",
|
||||
"new_text": "def bake(loaf):\n # <img src=x onerror=alert(1)>\n return loaf.heat(240)\n"
|
||||
},
|
||||
{
|
||||
"path": "src/timer.py",
|
||||
"old_text": null,
|
||||
"new_text": "MINUTES = 40\n"
|
||||
},
|
||||
{
|
||||
"path": "src/old.py",
|
||||
"old_text": "x = 1\n",
|
||||
"new_text": "",
|
||||
"deleted": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"chat_id": "chat1",
|
||||
"message_id": "msg2",
|
||||
"live": true
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"chat_id": "chat1",
|
||||
"message_id": "msg2",
|
||||
"live": false
|
||||
}
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"ref": "v2.0.0-beta.17",
|
||||
"commit": "66c667895d16cdbce3c7b0f6ecca512ae88777aa",
|
||||
"sha256": "08d53765c3578f65cf0b3b95ab06cf6d772e93033968de9d3c2c1a0e80df10e6"
|
||||
"ref": "v2.0.0-beta.19",
|
||||
"commit": "47b6e09e67cd36fb702d298643baa518d4396170",
|
||||
"sha256": "d1ae16aa1ee34c34a960bc2343a40e89cd5d836e8c3106af475d5bdad2d00bd3"
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"id": "msg3",
|
||||
"role": "user",
|
||||
"created_at": "2026-01-02T03:04:05+00:00",
|
||||
"complete": false,
|
||||
"stopped": false,
|
||||
"error": null,
|
||||
"queued": true,
|
||||
"machine": false,
|
||||
"origin": "carried",
|
||||
"model": null,
|
||||
"model_ref": null,
|
||||
"attachments": [],
|
||||
"text": "And the leaves?",
|
||||
"progress": {
|
||||
"phase": "queued",
|
||||
"since": 1767323045000
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"id": "msg3",
|
||||
"discarded": true
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"path": "/home/dev/project/src/oven.py",
|
||||
"cursor": {
|
||||
"line": 2
|
||||
},
|
||||
"selection": {
|
||||
"start": 2,
|
||||
"end": 2,
|
||||
"path": "/home/dev/project/src/oven.py",
|
||||
"text": " return loaf.heat(220)"
|
||||
},
|
||||
"diagnostics": [
|
||||
{
|
||||
"message": "220 is cool for waybread.",
|
||||
"path": "/home/dev/project/src/oven.py",
|
||||
"line": 2,
|
||||
"severity": "warning",
|
||||
"source": "baker"
|
||||
}
|
||||
],
|
||||
"open": [
|
||||
"/home/dev/project/README.md"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"message": {
|
||||
"id": "msg1",
|
||||
"role": "user",
|
||||
"created_at": "2026-01-02T03:04:05+00:00",
|
||||
"complete": true,
|
||||
"stopped": false,
|
||||
"error": null,
|
||||
"queued": false,
|
||||
"machine": false,
|
||||
"origin": "",
|
||||
"model": null,
|
||||
"model_ref": null,
|
||||
"attachments": [],
|
||||
"text": "How is lembas made?",
|
||||
"progress": null
|
||||
},
|
||||
"reply": {
|
||||
"id": "msg4",
|
||||
"role": "assistant",
|
||||
"created_at": "2026-01-02T03:04:05+00:00",
|
||||
"complete": false,
|
||||
"stopped": false,
|
||||
"error": null,
|
||||
"queued": false,
|
||||
"machine": false,
|
||||
"origin": "",
|
||||
"model": "qwen-27b",
|
||||
"model_ref": null,
|
||||
"attachments": [],
|
||||
"end": null,
|
||||
"steps": [],
|
||||
"plan": null,
|
||||
"metrics": {
|
||||
"prompt_tokens": 0,
|
||||
"completion_tokens": 0,
|
||||
"total_tokens": 0,
|
||||
"context_tokens": 0,
|
||||
"context_limit": 0,
|
||||
"estimated": false,
|
||||
"elapsed_ms": 0,
|
||||
"rounds": 1,
|
||||
"thinking_ms": 0,
|
||||
"percent": 0,
|
||||
"tok_s": 0.0
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"id": "msg3",
|
||||
"role": "user",
|
||||
"created_at": "2026-01-02T03:04:05+00:00",
|
||||
"complete": false,
|
||||
"stopped": false,
|
||||
"error": null,
|
||||
"queued": true,
|
||||
"machine": false,
|
||||
"origin": "unsure",
|
||||
"model": null,
|
||||
"model_ref": null,
|
||||
"attachments": [],
|
||||
"text": "And the leaves?",
|
||||
"progress": {
|
||||
"phase": "queued",
|
||||
"since": 1767323045000
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"calls": [
|
||||
{
|
||||
"id": "call8",
|
||||
"name": "show",
|
||||
"status": "ok",
|
||||
"query": "/home/frodo/oven/chart.png",
|
||||
"path": "/home/frodo/oven/chart.png",
|
||||
"media": {
|
||||
"kind": "image",
|
||||
"path": "/home/frodo/oven/chart.png",
|
||||
"node_id": "node8",
|
||||
"version_id": "ver8",
|
||||
"name": "chart.png",
|
||||
"mime": "image/png",
|
||||
"size": 48211,
|
||||
"shown": true,
|
||||
"width": 1280,
|
||||
"height": 720
|
||||
},
|
||||
"block": {
|
||||
"kind": "tool",
|
||||
"title": "/home/frodo/oven/chart.png",
|
||||
"chips": [],
|
||||
"added": 0,
|
||||
"removed": 0,
|
||||
"state": "done",
|
||||
"duration": "",
|
||||
"label": "Shown"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "call9",
|
||||
"name": "show",
|
||||
"status": "ok",
|
||||
"path": "out/report.pdf",
|
||||
"media": {
|
||||
"kind": "pdf",
|
||||
"path": "/home/frodo/Generated/report-20260102-030405.pdf",
|
||||
"node_id": "node9",
|
||||
"version_id": "ver9",
|
||||
"name": "report-20260102-030405.pdf",
|
||||
"mime": "application/pdf",
|
||||
"size": 90000,
|
||||
"shown": true
|
||||
},
|
||||
"block": {
|
||||
"kind": "tool",
|
||||
"title": "",
|
||||
"chips": [],
|
||||
"added": 0,
|
||||
"removed": 0,
|
||||
"state": "done",
|
||||
"duration": "",
|
||||
"label": "Shown"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "call10",
|
||||
"name": "show",
|
||||
"status": "ok",
|
||||
"path": "out/bundle.zip",
|
||||
"media": {
|
||||
"kind": "archive",
|
||||
"path": "/home/frodo/Generated/bundle-20260102-030405.zip",
|
||||
"node_id": "node10",
|
||||
"version_id": "ver10",
|
||||
"name": "bundle-20260102-030405.zip",
|
||||
"mime": "application/zip",
|
||||
"size": 1200000,
|
||||
"shown": true
|
||||
},
|
||||
"block": {
|
||||
"kind": "tool",
|
||||
"title": "",
|
||||
"chips": [],
|
||||
"added": 0,
|
||||
"removed": 0,
|
||||
"state": "done",
|
||||
"duration": "",
|
||||
"label": "Shown"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
+47
-7
@@ -6,9 +6,13 @@
|
||||
The mark is a 16x16 grid of rects, so it converts exactly into Android vector drawables -- one
|
||||
path per colour -- and needs no PNG at any density:
|
||||
|
||||
drawable/ic_launcher_foreground.xml the leaf, in the adaptive icon's 66dp safe zone
|
||||
drawable/ic_launcher_monochrome.xml its silhouette, for themed icons
|
||||
drawable/ic_notification.xml the same silhouette: a status-bar icon is alpha only
|
||||
drawable/ic_launcher_foreground.xml the leaf and the app's own sign, in the adaptive icon's 66dp safe zone
|
||||
drawable/ic_launcher_monochrome.xml their silhouette, for themed icons
|
||||
drawable/ic_notification.xml the leaf's silhouette alone: a status-bar icon is alpha only
|
||||
|
||||
Each LLeMbas product carries the server's leaf with one small pixel sign of its own in the free
|
||||
corner; this app's is a phone. The launcher's art is 24 pixels across: the leaf at (2, 2), the sign
|
||||
at (13, 14).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -37,6 +41,37 @@ def rects(svg: str) -> list[tuple[int, int, int, int, str]]:
|
||||
return found
|
||||
|
||||
|
||||
# The app's sign: a phone, in the launcher only.
|
||||
SIGN_COLOUR = "#C792EA"
|
||||
SIGN = (
|
||||
"..#####..",
|
||||
"..#...#..",
|
||||
"..#...#..",
|
||||
"..#...#..",
|
||||
"..#...#..",
|
||||
"..#.#.#..",
|
||||
"..#####..",
|
||||
)
|
||||
LEAF_AT = (2, 2)
|
||||
SIGN_AT = (13, 14)
|
||||
|
||||
|
||||
def sign() -> list[tuple[int, int, int, int, str]]:
|
||||
cells = []
|
||||
for y, row in enumerate(SIGN):
|
||||
x = 0
|
||||
while x < len(row):
|
||||
if row[x] != "#":
|
||||
x += 1
|
||||
continue
|
||||
w = 1
|
||||
while x + w < len(row) and row[x + w] == "#":
|
||||
w += 1
|
||||
cells.append((x + SIGN_AT[0], y + SIGN_AT[1], w, 1, SIGN_COLOUR))
|
||||
x += w
|
||||
return cells
|
||||
|
||||
|
||||
def path(cells) -> str:
|
||||
return " ".join(f"M{x},{y}h{w}v{h}h-{w}z" for x, y, w, h, _ in cells)
|
||||
|
||||
@@ -61,14 +96,19 @@ def main() -> None:
|
||||
for cell in cells:
|
||||
by_colour[cell[4]].append(cell)
|
||||
|
||||
# 108dp adaptive canvas; the leaf scaled x3.5 (56dp) and centred, inside the 66dp safe zone.
|
||||
# 108dp adaptive canvas; the art is 24 pixels across, scaled x2.75 (66dp) and centred: the safe zone.
|
||||
launcher = [(x + LEAF_AT[0], y + LEAF_AT[1], w, h, c) for x, y, w, h, c in cells] + sign()
|
||||
launcher_by_colour: dict[str, list] = defaultdict(list)
|
||||
for cell in launcher:
|
||||
launcher_by_colour[cell[4]].append(cell)
|
||||
coloured = "".join(
|
||||
f' <path android:fillColor="{colour}" android:pathData="{path(group)}"/>\n'
|
||||
for colour, group in sorted(by_colour.items())
|
||||
for colour, group in sorted(launcher_by_colour.items())
|
||||
)
|
||||
group = f' <group android:translateX="26" android:translateY="26" android:scaleX="3.5" android:scaleY="3.5">\n{coloured} </group>\n'
|
||||
placed = ' <group android:translateX="21" android:translateY="21" android:scaleX="2.75" android:scaleY="2.75">\n'
|
||||
group = f"{placed}{coloured} </group>\n"
|
||||
mono = f'{placed} <path android:fillColor="#FFFFFFFF" android:pathData="{path(launcher)}"/>\n </group>\n'
|
||||
silhouette = f' <path android:fillColor="#FFFFFFFF" android:pathData="{path(cells)}"/>\n'
|
||||
mono = f' <group android:translateX="26" android:translateY="26" android:scaleX="3.5" android:scaleY="3.5">\n{silhouette} </group>\n'
|
||||
|
||||
RES.mkdir(parents=True, exist_ok=True)
|
||||
(RES / "ic_launcher_foreground.xml").write_text(vector(108, 108, group))
|
||||
|
||||
@@ -64,6 +64,15 @@ STRINGS: dict[str, str] = {
|
||||
"continue_reply": "Continue",
|
||||
"older": "Earlier messages",
|
||||
"queued": "Waiting to be sent",
|
||||
# A message handed to the linked computer whose arrival was never heard (`origin` `unsure`): the server's sentence.
|
||||
"fate_unknown": "It is not known whether this reached the computer. Send it again, or discard it.",
|
||||
# A message the linked computer has said it holds (`origin` `carried`): the server's sentence.
|
||||
"fate_carried": "The computer has this message and takes it in with its next turn.",
|
||||
# A waiting message's two actions (the page's own words; "Discard" is `discard`), and what Discard asks first.
|
||||
"send_now": "Send now",
|
||||
"discard_message_confirm": "Discard this message?",
|
||||
# In place of a finished reply that holds nothing, after a turn nobody typed (the server's sentence).
|
||||
"reply_unrecorded": "The reply to this was not recorded.",
|
||||
"thinking": "Thinking",
|
||||
"thought": "Thought",
|
||||
"output_cut": "Output shortened here. The whole of it is on the web page.",
|
||||
@@ -438,6 +447,20 @@ STRINGS: dict[str, str] = {
|
||||
"media_video": "Video",
|
||||
"media_music": "Music",
|
||||
"media_model": "3D model",
|
||||
# A file an agent showed: what it is, in words, for every kind
|
||||
"media_audio": "Audio",
|
||||
"media_pdf": "PDF",
|
||||
"media_archive": "Archive",
|
||||
"media_text": "Text file",
|
||||
"media_binary": "File",
|
||||
# An edit's diff on its approval card
|
||||
"diff_deleted": "Deleted",
|
||||
"diff_counts": "Lines added: %1$s, removed: %2$s",
|
||||
"diff_show_all": "Show all %1$s lines",
|
||||
"diff_show_less": "Show less",
|
||||
"diff_more": "%1$s more lines are not shown here.",
|
||||
"diff_endings": "The line endings change from %1$s to %2$s.",
|
||||
"diff_cut": "This change is too long to compare here. Only its beginning is shown.",
|
||||
"media_gone": "That file no longer exists.",
|
||||
"job_queued": "Queued",
|
||||
"job_running": "Running",
|
||||
|
||||
@@ -424,7 +424,17 @@
|
||||
"mcp_browser_note": "Přihlášení probíhá v prohlížeči, přímo na instanci. Pokud prohlížeč není k instanci přihlášen, nejprve si to vyžádá. Potom se vraťte sem.",
|
||||
"files_waiting": "Čeká se, až bude aplikace otevřená a telefon odemčený.",
|
||||
"share_refused": "Něco ze sdíleného odsud odeslat nelze a bylo vynecháno.",
|
||||
"media_in_trash": "Tento soubor je v koši."
|
||||
"media_in_trash": "Tento soubor je v koši.",
|
||||
"media_pdf": "PDF",
|
||||
"media_archive": "Archiv",
|
||||
"media_text": "Textový soubor",
|
||||
"diff_deleted": "Smazáno",
|
||||
"diff_counts": "Přidané řádky: %1$s, odebrané: %2$s",
|
||||
"diff_show_all": "Zobrazit všechny řádky (%1$s)",
|
||||
"diff_show_less": "Zobrazit méně",
|
||||
"diff_more": "Další řádky, které se zde nezobrazují: %1$s.",
|
||||
"diff_endings": "Konce řádků se mění z %1$s na %2$s.",
|
||||
"diff_cut": "Tato změna je příliš dlouhá na to, aby se zde porovnala. Zobrazen je jen její začátek."
|
||||
},
|
||||
"de": {
|
||||
"about_version": "LLeMbas für Android %1$s",
|
||||
@@ -852,7 +862,17 @@
|
||||
"mcp_browser_note": "Die Anmeldung geschieht im Browser, auf der Instanz selbst. Ist der Browser dort nicht angemeldet, wird zuerst danach gefragt. Danach hierher zurückkehren.",
|
||||
"files_waiting": "Wartet, bis die App geöffnet und das Telefon entsperrt ist.",
|
||||
"share_refused": "Etwas vom Geteilten kann von hier nicht gesendet werden und wurde ausgelassen.",
|
||||
"media_in_trash": "Diese Datei liegt im Papierkorb."
|
||||
"media_in_trash": "Diese Datei liegt im Papierkorb.",
|
||||
"media_pdf": "PDF",
|
||||
"media_archive": "Archiv",
|
||||
"media_text": "Textdatei",
|
||||
"diff_deleted": "Gelöscht",
|
||||
"diff_counts": "Zeilen hinzugefügt: %1$s, entfernt: %2$s",
|
||||
"diff_show_all": "Alle %1$s Zeilen anzeigen",
|
||||
"diff_show_less": "Weniger anzeigen",
|
||||
"diff_more": "%1$s weitere Zeilen werden hier nicht angezeigt.",
|
||||
"diff_endings": "Die Zeilenenden ändern sich von %1$s zu %2$s.",
|
||||
"diff_cut": "Diese Änderung ist zu lang, um hier verglichen zu werden. Nur ihr Anfang wird angezeigt."
|
||||
},
|
||||
"es": {
|
||||
"about_version": "LLeMbas para Android %1$s",
|
||||
@@ -1279,7 +1299,17 @@
|
||||
"mcp_browser_note": "El inicio de sesión se hace en el navegador, en la propia instancia. Si el navegador no tiene la sesión iniciada en la instancia, primero la pide. Después, vuelva aquí.",
|
||||
"files_waiting": "Esperando a que la aplicación esté abierta y el teléfono desbloqueado.",
|
||||
"share_refused": "Algo de lo compartido no se puede enviar desde aquí y se ha omitido.",
|
||||
"media_in_trash": "Ese archivo está en la papelera."
|
||||
"media_in_trash": "Ese archivo está en la papelera.",
|
||||
"media_pdf": "PDF",
|
||||
"media_archive": "Archivo comprimido",
|
||||
"media_text": "Archivo de texto",
|
||||
"diff_deleted": "Eliminado",
|
||||
"diff_counts": "Líneas añadidas: %1$s, eliminadas: %2$s",
|
||||
"diff_show_all": "Mostrar las %1$s líneas",
|
||||
"diff_show_less": "Mostrar menos",
|
||||
"diff_more": "Aquí no se muestran %1$s líneas más.",
|
||||
"diff_endings": "Los finales de línea cambian de %1$s a %2$s.",
|
||||
"diff_cut": "Este cambio es demasiado largo para compararlo aquí. Solo se muestra su comienzo."
|
||||
},
|
||||
"fr": {
|
||||
"about_version": "LLeMbas pour Android %1$s",
|
||||
@@ -1707,7 +1737,17 @@
|
||||
"mcp_browser_note": "La connexion se fait dans le navigateur, sur l’instance elle-même. Si le navigateur n’y est pas connecté, il le demande d’abord. Revenez ensuite ici.",
|
||||
"files_waiting": "En attente que l'application soit ouverte et le téléphone déverrouillé.",
|
||||
"share_refused": "Un élément partagé ne peut pas être envoyé d'ici et a été laissé de côté.",
|
||||
"media_in_trash": "Ce fichier est dans la corbeille."
|
||||
"media_in_trash": "Ce fichier est dans la corbeille.",
|
||||
"media_pdf": "PDF",
|
||||
"media_archive": "Archive",
|
||||
"media_text": "Fichier texte",
|
||||
"diff_deleted": "Supprimé",
|
||||
"diff_counts": "Lignes ajoutées : %1$s, supprimées : %2$s",
|
||||
"diff_show_all": "Afficher les %1$s lignes",
|
||||
"diff_show_less": "Afficher moins",
|
||||
"diff_more": "%1$s lignes de plus ne sont pas affichées ici.",
|
||||
"diff_endings": "Les fins de ligne passent de %1$s à %2$s.",
|
||||
"diff_cut": "Cette modification est trop longue pour être comparée ici. Seul son début est affiché."
|
||||
},
|
||||
"hu": {
|
||||
"about_version": "LLeMbas Androidra %1$s",
|
||||
@@ -2135,7 +2175,17 @@
|
||||
"mcp_browser_note": "A bejelentkezés a böngészőben történik, magán a példányon. Ha a böngésző nincs bejelentkezve a példányba, előbb azt kéri. Utána térjen vissza ide.",
|
||||
"files_waiting": "Várakozás, amíg az alkalmazás meg van nyitva és a telefon fel van oldva.",
|
||||
"share_refused": "A megosztottak közül valami innen nem küldhető el, ezért kimaradt.",
|
||||
"media_in_trash": "Ez a fájl a lomtárban van."
|
||||
"media_in_trash": "Ez a fájl a lomtárban van.",
|
||||
"media_pdf": "PDF",
|
||||
"media_archive": "Archívum",
|
||||
"media_text": "Szövegfájl",
|
||||
"diff_deleted": "Törölve",
|
||||
"diff_counts": "Hozzáadott sorok: %1$s, eltávolított: %2$s",
|
||||
"diff_show_all": "Mind a(z) %1$s sor megjelenítése",
|
||||
"diff_show_less": "Kevesebb megjelenítése",
|
||||
"diff_more": "További %1$s sor itt nem látható.",
|
||||
"diff_endings": "A sorvégek megváltoznak: %1$s helyett %2$s.",
|
||||
"diff_cut": "Ez a változás túl hosszú ahhoz, hogy itt össze lehessen hasonlítani. Csak az eleje látható."
|
||||
},
|
||||
"it": {
|
||||
"about_version": "LLeMbas per Android %1$s",
|
||||
@@ -2562,7 +2612,17 @@
|
||||
"mcp_browser_note": "L’accesso avviene nel browser, sull’istanza stessa. Se il browser non ha effettuato l’accesso all’istanza, prima lo chiede. Poi torna qui.",
|
||||
"files_waiting": "In attesa che l'app sia aperta e il telefono sbloccato.",
|
||||
"share_refused": "Qualcosa di ciò che è stato condiviso non può essere inviato da qui ed è stato escluso.",
|
||||
"media_in_trash": "Questo file è nel cestino."
|
||||
"media_in_trash": "Questo file è nel cestino.",
|
||||
"media_pdf": "PDF",
|
||||
"media_archive": "Archivio",
|
||||
"media_text": "File di testo",
|
||||
"diff_deleted": "Eliminato",
|
||||
"diff_counts": "Righe aggiunte: %1$s, rimosse: %2$s",
|
||||
"diff_show_all": "Mostra tutte le %1$s righe",
|
||||
"diff_show_less": "Mostra meno",
|
||||
"diff_more": "Altre %1$s righe non sono mostrate qui.",
|
||||
"diff_endings": "I fine riga cambiano da %1$s a %2$s.",
|
||||
"diff_cut": "Questa modifica è troppo lunga per essere confrontata qui. Ne è mostrato solo l’inizio."
|
||||
},
|
||||
"pl": {
|
||||
"about_version": "LLeMbas na Androida %1$s",
|
||||
@@ -2989,7 +3049,17 @@
|
||||
"mcp_browser_note": "Logowanie odbywa się w przeglądarce, na samej instancji. Jeśli przeglądarka nie jest zalogowana do instancji, najpierw o to poprosi. Potem wróć tutaj.",
|
||||
"files_waiting": "Oczekiwanie, aż aplikacja będzie otwarta, a telefon odblokowany.",
|
||||
"share_refused": "Czegoś z udostępnionych rzeczy nie można stąd wysłać i zostało pominięte.",
|
||||
"media_in_trash": "Ten plik jest w koszu."
|
||||
"media_in_trash": "Ten plik jest w koszu.",
|
||||
"media_pdf": "PDF",
|
||||
"media_archive": "Archiwum",
|
||||
"media_text": "Plik tekstowy",
|
||||
"diff_deleted": "Usunięto",
|
||||
"diff_counts": "Dodane wiersze: %1$s, usunięte: %2$s",
|
||||
"diff_show_all": "Pokaż wszystkie wiersze (%1$s)",
|
||||
"diff_show_less": "Pokaż mniej",
|
||||
"diff_more": "Dalsze wiersze, których tu nie pokazano: %1$s.",
|
||||
"diff_endings": "Końce wierszy zmieniają się z %1$s na %2$s.",
|
||||
"diff_cut": "Ta zmiana jest zbyt długa, by ją tu porównać. Pokazano tylko jej początek."
|
||||
},
|
||||
"sk": {
|
||||
"about_version": "LLeMbas pre Android %1$s",
|
||||
@@ -3416,6 +3486,16 @@
|
||||
"mcp_browser_note": "Prihlásenie prebieha v prehliadači, priamo na inštancii. Ak prehliadač nie je do inštancie prihlásený, najprv si to vyžiada. Potom sa vráťte sem.",
|
||||
"files_waiting": "Čaká sa, kým bude aplikácia otvorená a telefón odomknutý.",
|
||||
"share_refused": "Niečo zo zdieľaného sa odtiaľto nedá odoslať a bolo vynechané.",
|
||||
"media_in_trash": "Tento súbor je v koši."
|
||||
"media_in_trash": "Tento súbor je v koši.",
|
||||
"media_pdf": "PDF",
|
||||
"media_archive": "Archív",
|
||||
"media_text": "Textový súbor",
|
||||
"diff_deleted": "Zmazané",
|
||||
"diff_counts": "Pridané riadky: %1$s, odobraté: %2$s",
|
||||
"diff_show_all": "Zobraziť všetky riadky (%1$s)",
|
||||
"diff_show_less": "Zobraziť menej",
|
||||
"diff_more": "Ďalšie riadky, ktoré sa tu nezobrazujú: %1$s.",
|
||||
"diff_endings": "Konce riadkov sa menia z %1$s na %2$s.",
|
||||
"diff_cut": "Táto zmena je príliš dlhá na to, aby sa tu porovnala. Zobrazený je len jej začiatok."
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"tag": "v2.0.0-beta.17",
|
||||
"commit": "66c667895d16cdbce3c7b0f6ecca512ae88777aa",
|
||||
"sha256": "5086138e23ce9fb9372c979d153bba623a89f18324f90e065ceba2508938d089",
|
||||
"tag": "v2.0.0-beta.19",
|
||||
"commit": "47b6e09e67cd36fb702d298643baa518d4396170",
|
||||
"sha256": "56095bb3d93a8bc736ff7e7fe27e670ba490c08f2644a5025ec7df5b71d94670",
|
||||
"res": {
|
||||
"values": "68d89bc4e5d2fa79f25f00df4a3a14917901732394e336b6fcf58f05a47b0c4f",
|
||||
"values-night": "40ca5e394783f27a5550a7131b53c9d601a5bfbc7031ae64ab74799b0efe1f4e"
|
||||
"values": "cc5a18f8d91fb9b7a50183c889d84e160f1785aa2c2ff4d5d0505901c20758a3",
|
||||
"values-night": "251f54399a6134f6d9fa631be38c04184259ffc2a05a1a237a863fd768412afd"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user