A file an agent shows is in the chat by its kind; an edit's diff is on its approval card
CI / check (push) Canceled after 0s

A tool call's `media` with `shown` is drawn where generated media is: a
picture with its name under it, audio and video with Play, a PDF with Open
(its pages over the chat, by node id), and a 3D model, an archive, a text
file, a binary and any kind the app does not know as a row with the name,
the kind in words and the size. Every card keeps Open in Files, Download,
Share and Open with. `audio` plays as `music` does.

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

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

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-24 13:31:30 +00:00
1 parent 660ff90b3a
commit 5e5e63353a
24 files changed
+1076 -63

No files matched your search

@@ -0,0 +1,114 @@
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, 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. */
data class DiffView(val lines: List<DiffLine>, val added: Int, val removed: Int) {
/** 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)
}
/** 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
/** A text's lines; the newline that ends the last one starts no empty line. */
internal fun textLines(text: String): List<String> {
if (text.isEmpty()) return emptyList()
val lines = text.split('\n')
return if (lines.last().isEmpty()) lines.dropLast(1) else lines
}
/**
* [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. */
fun FileDiff.view(): DiffView {
val all = diffLines(textLines(oldText.orEmpty()), textLines(if (deleted) "" else newText))
return DiffView(hunks(all), added = all.count { it.sign == DiffSign.Added }, removed = all.count { it.sign == DiffSign.Removed })
}
@@ -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 } }
@@ -765,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 = "")
@@ -100,9 +100,11 @@ 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() && item.diffs.isEmpty()) {
Text(item.detail, fontFamily = FontFamily.Monospace)
}
// An edit says what it would change: the diff stands where the call's arguments would, as text.
if (item.diffs.isNotEmpty()) CardDiffs(item.diffs)
if (item.reason.isNotBlank()) Text(item.reason, style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
}
// A corrected command goes with an allow, never with a refusal, and only when it was corrected.
@@ -111,9 +111,11 @@ import eu.llembas.android.ui.files.TransferHost
import eu.llembas.android.ui.files.TransferViewModel
import eu.llembas.android.ui.files.rememberSaver
import eu.llembas.android.ui.theme.LocalPalette
import eu.llembas.android.ui.viewer.DocumentDialog
import eu.llembas.android.ui.viewer.FileViewer
import eu.llembas.android.ui.viewer.PlayerDialog
import eu.llembas.android.ui.viewer.Playing
import eu.llembas.android.ui.viewer.Reading
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.launch
@@ -175,6 +177,7 @@ fun ChatScreen(
val transfers: TransferViewModel = viewModel(key = "chat-transfers")
val saveTo = rememberSaver(transfers)
var playing by remember { mutableStateOf<Playing?>(null) }
var reading by remember { mutableStateOf<Reading?>(null) }
val media = remember(model, transfers) {
object : MediaActions {
override fun play(media: GeneratedMedia) {
@@ -185,6 +188,10 @@ fun ChatScreen(
playing = Playing(Raw.Attached(attachment.id), attachment.name, attachment.size, video = attachment.kind == "video")
}
override fun view(media: GeneratedMedia) {
reading = Reading(media.raw, media.title, media.size)
}
// Where the file is now, by its id: it may have been renamed or moved since it was made.
override fun openInFiles(media: GeneratedMedia) = model.whereIs(media, onFiles)
@@ -238,6 +245,7 @@ fun ChatScreen(
state.chat?.id?.let { id -> FileViewer(id, file, onClose = { showing = null }) }
}
playing?.let { PlayerDialog(it, onClose = { playing = null }, gone = stringResource(R.string.media_gone)) }
reading?.let { DocumentDialog(it, onClose = { reading = null }, gone = stringResource(R.string.media_gone)) }
TransferHost(transfers)
}
@@ -0,0 +1,144 @@
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.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.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.FileDiff
import eu.llembas.android.api.view
import eu.llembas.android.ui.theme.LocalPalette
import eu.llembas.android.ui.theme.Palette
// 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 with tabs as spaces and cut at [DIFF_LINE_MOST]. */
internal fun diffRow(line: DiffLine): String {
val sign = when (line.sign) {
DiffSign.Added -> "+ "
DiffSign.Removed -> "- "
DiffSign.Same -> " "
DiffSign.Gap -> return "⋯"
}
val text = line.text.replace("\r", "").replace("\t", " ")
return sign + if (text.length > DIFF_LINE_MOST) text.take(DIFF_LINE_MOST) + "…" else text
}
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 one item of an approval card, a block per file. */
@Composable
fun CardDiffs(diffs: List<FileDiff>, modifier: Modifier = Modifier) {
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
diffs.forEachIndexed { at, diff -> key(at, diff.path) { FileDiffBlock(diff) } }
}
}
/**
* 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.
*/
@Composable
private fun FileDiffBlock(diff: FileDiff) {
val palette = LocalPalette.current
val view = remember(diff) { diff.view() }
var open by rememberSaveable(diff.path) { mutableStateOf(false) }
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(diff.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)
}
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)
}
}
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) {
Text(
stringResource(R.string.diff_more, view.beyond.toString()),
style = MaterialTheme.typography.bodySmall,
color = palette.inkMuted,
modifier = Modifier.padding(horizontal = 12.dp),
)
}
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()))
}
}
}
}
@@ -75,6 +75,8 @@ private object Pictures {
cache.get(key)?.let { return it }
if (key in failed) return null
val api = context.lembas.instances.client() ?: return null
// A picture that comes into view behind the lock, or with the app not in front, waits there.
context.lembas.gate.passLater()
val bytes = try {
fetch(api).takeIf { it.size <= MAX_BYTES }
} catch (e: CancellationException) {
@@ -15,14 +15,18 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
import androidx.compose.material.icons.automirrored.filled.OpenInNew
import androidx.compose.material.icons.filled.Description
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material.icons.filled.FolderOpen
import androidx.compose.material.icons.filled.FolderZip
import androidx.compose.material.icons.filled.HourglassEmpty
import androidx.compose.material.icons.filled.Image
import androidx.compose.material.icons.filled.Movie
import androidx.compose.material.icons.filled.MusicNote
import androidx.compose.material.icons.filled.PictureAsPdf
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.ViewInAr
@@ -59,8 +63,9 @@ import eu.llembas.android.ui.theme.LocalPalette
import eu.llembas.android.ui.viewer.playTime
import kotlinx.coroutines.delay
// What a model made, in the reply: a card for a file (a picture drawn, a video or a track with
// Play, a 3D model or anything else as what it is) and a card for a generation still under way.
// What a model made or an agent showed, in the reply: a card for a file (a picture drawn, a video
// or a track with Play, a PDF with Open, a 3D model or anything else as what it is) and a card for
// a generation still under way.
// The file is one of the person's Files, so each card leads there, and out of the app the ways
// a file leaves it: saved where the person chooses, shared, or opened with another app. The
// cards are drawn only where a chat provides [LocalChatMedia] -- the chat's own screen, which
@@ -74,6 +79,9 @@ interface MediaActions {
/** Play sound or video the person attached. */
fun play(attachment: Attachment) {}
/** Lay a document's pages out over the chat (a PDF). */
fun view(media: GeneratedMedia) {}
/** The folder of the person's Files the file is in. */
fun openInFiles(media: GeneratedMedia) {}
@@ -96,21 +104,39 @@ val LocalChatMedia = compositionLocalOf<ChatMedia?> { null }
private val CardShape = RoundedCornerShape(16.dp)
/** The word for what was asked for: a picture, a video, music, a 3D model; the server's own word for anything else. */
@Composable
internal fun mediaKind(kind: String): String = when (kind) {
"image", "image_edit" -> stringResource(R.string.media_image)
"video" -> stringResource(R.string.media_video)
"music" -> stringResource(R.string.media_music)
"model3d" -> stringResource(R.string.media_model)
else -> kind
/** The string for a kind this app has a word for; null for any other. */
internal fun mediaKindWord(kind: String): Int? = when (kind) {
"image", "image_edit" -> R.string.media_image
"video" -> R.string.media_video
"music" -> R.string.media_music
"audio" -> R.string.media_audio
"model3d" -> R.string.media_model
"pdf" -> R.string.media_pdf
"archive" -> R.string.media_archive
"text" -> R.string.media_text
"binary" -> R.string.media_binary
else -> null
}
private fun mediaIcon(kind: String): ImageVector = when (kind) {
/**
* The word for what a file is: a picture, a video, music, audio, a 3D model, a PDF, an archive,
* a text file, a file. A kind this app does not know is the server's own word for a generated
* file and "File" for one an agent showed ([shown]): a shown file always says what it is.
*/
@Composable
internal fun mediaKind(kind: String, shown: Boolean = false): String =
mediaKindWord(kind)?.let { stringResource(it) } ?: if (shown) stringResource(R.string.media_binary) else kind
/** The mark of a kind; `binary` and a kind this app does not know are a file. */
internal fun mediaIcon(kind: String): ImageVector = when (kind) {
"image", "image_edit" -> Icons.Filled.Image
"video" -> Icons.Filled.Movie
"music" -> Icons.Filled.MusicNote
else -> Icons.Filled.ViewInAr
"music", "audio" -> Icons.Filled.MusicNote
"model3d" -> Icons.Filled.ViewInAr
"pdf" -> Icons.Filled.PictureAsPdf
"archive" -> Icons.Filled.FolderZip
"text" -> Icons.Filled.Description
else -> Icons.AutoMirrored.Filled.InsertDriveFile
}
/** What is known of a file, in one line: what it is, how long, how large, its size in pixels. */
@@ -118,7 +144,7 @@ private fun mediaIcon(kind: String): ImageVector = when (kind) {
internal fun mediaFacts(media: GeneratedMedia): String {
val context = LocalContext.current
return listOfNotNull(
mediaKind(media.kind).ifBlank { null },
mediaKind(media.kind, media.shown).ifBlank { null },
media.seconds.takeIf { it > 0 }?.let { playTime((it * 1000).toInt()) },
media.size.takeIf { it > 0 }?.let { Formatter.formatShortFileSize(context, it) },
if (media.width > 0 && media.height > 0) "${media.width} × ${media.height}" else null,
@@ -126,45 +152,33 @@ internal fun mediaFacts(media: GeneratedMedia): String {
}
/**
* A file a tool call made. A picture is drawn -- from its attachment where the call has one
* ([image]), else from the file itself; a video or a track is its name with Play (48 dp), which
* opens the player over the chat; a 3D model and anything this app does not know is what it is.
* Under each, four buttons of one size: Open in Files, Download, Share, Open with.
* A file a tool call made, or one an agent showed. A picture is drawn -- from its attachment
* where the call has one ([image]), else from the file itself; a video or a track is its name
* with Play (48 dp), which opens the player over the chat; a PDF is its name with Open, which
* lays its pages out over the chat; a 3D model, an archive and anything this app does not know
* is its name and what it is. Under each, four buttons of one size: Open in Files, Download,
* Share, Open with.
*
* A file that was shown is always named: its picture has its name and facts under it, so one
* that cannot be drawn on this phone (too large, a format the phone does not read) is still a
* name, a kind in words and the ways to the file.
*/
@Composable
fun MediaCard(media: GeneratedMedia, image: GeneratedImage?, actions: MediaActions, modifier: Modifier = Modifier) {
val palette = LocalPalette.current
Column(modifier.widthIn(max = 480.dp).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) {
when (media.view) {
MediaView.Picture -> if (image != null && image.id.isNotBlank()) GeneratedPicture(image) else GeneratedPicture(media)
MediaView.Video, MediaView.Sound, MediaView.Details -> Row(
Modifier.fillMaxWidth().border(1.dp, palette.border, CardShape).padding(horizontal = 12.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
if (media.view == MediaView.Details) {
Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) {
Icon(mediaIcon(media.kind), contentDescription = null, tint = palette.inkMuted)
}
} else {
FilledIconButton(
onClick = { actions.play(media) },
colors = IconButtonDefaults.filledIconButtonColors(containerColor = palette.accent, contentColor = palette.accentInk),
modifier = Modifier.size(48.dp),
) { Icon(Icons.Filled.PlayArrow, contentDescription = stringResource(R.string.play)) }
}
Spacer(Modifier.width(12.dp))
Column(Modifier.weight(1f)) {
Text(media.title, style = MaterialTheme.typography.bodyLarge, color = palette.ink, maxLines = 1, overflow = TextOverflow.MiddleEllipsis)
Text(
mediaFacts(media),
style = MaterialTheme.typography.bodySmall,
color = palette.inkMuted,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
MediaView.Picture -> {
// A result that names no node has no picture to ask for: its row stands in, so the card is never empty.
val drawable = (image != null && image.id.isNotBlank()) || media.nodeId.isNotBlank()
if (image != null && image.id.isNotBlank()) GeneratedPicture(image) else GeneratedPicture(media)
if (media.shown && drawable) {
Column(Modifier.fillMaxWidth().padding(horizontal = 4.dp)) { MediaWords(media) }
} else if (!drawable) {
MediaRow(media, actions)
}
}
MediaView.Video, MediaView.Sound, MediaView.Document, MediaView.Details -> MediaRow(media, actions)
}
// Four buttons of 48 dp: nothing here depends on how long a word is in any language.
Row {
@@ -176,6 +190,44 @@ fun MediaCard(media: GeneratedMedia, image: GeneratedImage?, actions: MediaActio
}
}
/** The file's name on one line (its middle gives) and what is known of it on the next. */
@Composable
private fun MediaWords(media: GeneratedMedia) {
val palette = LocalPalette.current
Text(media.title, style = MaterialTheme.typography.bodyLarge, color = palette.ink, maxLines = 1, overflow = TextOverflow.MiddleEllipsis)
Text(mediaFacts(media), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
/**
* A file as a row: a mark of 48 dp -- Play for sound and video, Open for a PDF, else the kind's
* icon -- and the file's words, which give.
*/
@Composable
private fun MediaRow(media: GeneratedMedia, actions: MediaActions) {
val palette = LocalPalette.current
Row(
Modifier.fillMaxWidth().border(1.dp, palette.border, CardShape).padding(horizontal = 12.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
val filled = IconButtonDefaults.filledIconButtonColors(containerColor = palette.accent, contentColor = palette.accentInk)
when (media.view) {
MediaView.Video, MediaView.Sound -> FilledIconButton(onClick = { actions.play(media) }, colors = filled, modifier = Modifier.size(48.dp)) {
Icon(Icons.Filled.PlayArrow, contentDescription = stringResource(R.string.play))
}
MediaView.Document -> FilledIconButton(onClick = { actions.view(media) }, colors = filled, modifier = Modifier.size(48.dp)) {
Icon(mediaIcon(media.kind), contentDescription = stringResource(R.string.viewer_open))
}
MediaView.Picture, MediaView.Details -> Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) {
Icon(mediaIcon(media.kind), contentDescription = null, tint = palette.inkMuted)
}
}
Spacer(Modifier.width(12.dp))
Column(Modifier.weight(1f)) { MediaWords(media) }
}
}
@Composable
private fun CardButton(icon: ImageVector, label: Int, onClick: () -> Unit) {
IconButton(onClick = onClick) { Icon(icon, contentDescription = stringResource(label), tint = LocalPalette.current.inkMuted) }
@@ -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