diff --git a/CHANGELOG.md b/CHANGELOG.md index e1076f8..cea4038 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,10 @@ is in alpha and releases come off `main`. too), then the rest. A long press on a chat offers **Pin chat** and **Move to folder**; on a folder, **Rename folder** and **Delete folder** (its chats stay). **New folder** is beside New chat at the top of the drawer. +- **Generate images** in a chat, when your instance makes pictures: from **+** in the composer, + the next message asks for one, and the picture shows in the reply at its own size. A tap opens + it whole. Only pictures your instance made and keeps are drawn; nothing is loaded from an + address a reply names. - **Memory**, in the drawer: what models remember about you, as Settings › Memory on the web. A tap changes or forgets one; **Remember** adds one (in the data group you pick, when you have more than one). What a model wrote is marked, and shown as plain text. diff --git a/app/src/main/java/eu/llembas/android/api/ApiClient.kt b/app/src/main/java/eu/llembas/android/api/ApiClient.kt index 273d7bf..f339860 100644 --- a/app/src/main/java/eu/llembas/android/api/ApiClient.kt +++ b/app/src/main/java/eu/llembas/android/api/ApiClient.kt @@ -242,12 +242,14 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli }, ) - suspend fun sendMessage(chatId: String, text: String, attachments: List = emptyList()): Turn = send( + /** A turn. [forceTool] makes the model call that tool (the server allows `image_generate` only). */ + suspend fun sendMessage(chatId: String, text: String, attachments: List = emptyList(), forceTool: String? = null): Turn = send( "POST", "/chats/$chatId/messages", buildJsonObject { put("text", text) put("attachments", JsonArray(attachments.map { JsonPrimitive(it) })) + forceTool?.let { put("force_tool", it) } }, ) diff --git a/app/src/main/java/eu/llembas/android/api/Models.kt b/app/src/main/java/eu/llembas/android/api/Models.kt index c9a0c3a..120e2f3 100644 --- a/app/src/main/java/eu/llembas/android/api/Models.kt +++ b/app/src/main/java/eu/llembas/android/api/Models.kt @@ -89,6 +89,9 @@ data class Me( /** The instance's text-to-speech (the assistant's voice reply, Read aloud). */ val hasTextToSpeech: Boolean get() = services["tts"] == true + + /** The instance makes pictures for this person (`image_generate`, in a chat). */ + val hasImages: Boolean get() = services["images"] == true } @Serializable @@ -334,9 +337,19 @@ data class ToolCall( val children: List? = null, /** The `show` tool's card: a file put in front of the person. Never its text. */ val show: ShowCard? = null, + /** `image_generate`'s picture: the server's own attachment, by id, and its size. */ + val image: GeneratedImage? = null, val block: ToolBlock = ToolBlock(), ) +/** + * A picture the instance made (`event["image"]`): an attachment of the chat's owner, fetched + * with the token from `GET /api/v2/attachments/{id}` and nowhere else. Its size is known before + * it loads, so the space it takes does not jump. + */ +@Serializable +data class GeneratedImage(val id: String = "", val width: Int = 0, val height: Int = 0) + /** * What a `show` call put in front of the person (`event["show"]`, harness spec 3.0.0): the * file's name and where it is, never its contents -- the viewer fetches those. A file from the diff --git a/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt b/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt index 90d68d3..7fb3f72 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt @@ -75,6 +75,8 @@ data class ChatState( val compacting: Boolean = false, /** What a chat not made yet will be made with: chosen in the top bar and the tune sheet. */ val draft: Draft = Draft(), + /** The instance makes pictures for this person (`/me` `services.images`). */ + val imagesOffered: Boolean = false, /** The subagent tree (spec 3.4.0) from this chat's last `tree` frame; null until one came. */ val tree: SubagentTree? = null, /** For a new agent chat: whether it may have subagents, and whether its device runs them. */ @@ -93,8 +95,13 @@ data class Draft( val agentMode: String = "edit", val device: String? = null, val directory: String = "", + /** The next message asks for a picture (`force_tool: image_generate`); cleared once sent. */ + val image: Boolean = false, ) +/** The one tool a message may force (the server's `FORCEABLE_TOOLS`): make a picture. */ +const val IMAGE_TOOL = "image_generate" + /** The model in force: the chat's, else the one chosen for the new chat, else the default. */ val ChatState.modelId: String? get() = chat?.model?.ifBlank { null } ?: draft.model ?: models.firstOrNull { it.default }?.id ?: models.firstOrNull()?.id @@ -227,6 +234,7 @@ class ChatViewModel(app: Application) : if (agent) readAgentFacts() return@launch } + runCatching { client.me() }.onSuccess { me -> _state.update { it.copy(imagesOffered = me.hasImages) } } val detail = client.chat(chatId) _state.update { it.copy(chat = detail.chat, messages = detail.messages, more = detail.more, models = models, loading = false) @@ -361,7 +369,9 @@ class ChatViewModel(app: Application) : _state.update { it.copy(chat = made.chat, messages = listOfNotNull(made.message, made.reply)) } made.reply?.let { follow(it.id) } } else { - took(client.sendMessage(chat.id, text, files)) + val picture = _state.value.draft.image && _state.value.imagesOffered + _state.update { it.copy(draft = it.draft.copy(image = false)) } + took(client.sendMessage(chat.id, text, files, forceTool = if (picture) IMAGE_TOOL else null)) } } catch (e: Exception) { // Nothing was sent: the words and the attachments go back to the composer. diff --git a/app/src/main/java/eu/llembas/android/ui/chat/Composer.kt b/app/src/main/java/eu/llembas/android/ui/chat/Composer.kt index daaff82..980a5ee 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/Composer.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/Composer.kt @@ -31,6 +31,7 @@ import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.ArrowUpward +import androidx.compose.material.icons.filled.Brush import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Folder import androidx.compose.material.icons.filled.Mic @@ -47,6 +48,7 @@ import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.IconButtonDefaults +import androidx.compose.material3.InputChip import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField @@ -220,6 +222,17 @@ fun Composer(state: ChatState, actions: ChatActions, agent: Boolean, onTune: () ) { Column { if (state.uploading) LinearProgressIndicator(Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 4.dp)) + if (state.draft.image) { + // The next message asks for a picture: said where it is typed, and undone here. + InputChip( + selected = true, + onClick = { actions.updateDraft { it.copy(image = false) } }, + label = { Text(stringResource(R.string.image_generate)) }, + leadingIcon = { Icon(Icons.Filled.Brush, contentDescription = null, modifier = Modifier.size(18.dp)) }, + trailingIcon = { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.remove), modifier = Modifier.size(18.dp)) }, + modifier = Modifier.padding(start = 12.dp, top = 8.dp).heightIn(min = 40.dp), + ) + } if (state.pending.isNotEmpty()) { Row( Modifier.horizontalScroll(rememberScrollState()).padding(start = 12.dp, end = 12.dp, top = 12.dp), @@ -310,6 +323,18 @@ fun Composer(state: ChatState, actions: ChatActions, agent: Boolean, onTune: () pickFiles.launch("*/*") }, ) + // A picture made by the instance, in a chat that exists (the server takes + // `force_tool` on a turn, not on the message that makes a chat). + if (state.imagesOffered && state.chat != null && !agent) { + DropdownMenuItem( + leadingIcon = { Icon(Icons.Filled.Brush, contentDescription = null) }, + text = { Text(stringResource(R.string.image_generate)) }, + onClick = { + attachMenu = false + actions.updateDraft { it.copy(image = true) } + }, + ) + } } } // The tune button: the icon, and what is set in a few words. It sits in the one diff --git a/app/src/main/java/eu/llembas/android/ui/chat/GeneratedPicture.kt b/app/src/main/java/eu/llembas/android/ui/chat/GeneratedPicture.kt new file mode 100644 index 0000000..a870bec --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/chat/GeneratedPicture.kt @@ -0,0 +1,122 @@ +package eu.llembas.android.ui.chat + +import android.content.Context +import android.graphics.BitmapFactory +import android.util.LruCache +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Image +import androidx.compose.material3.Icon +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalInspectionMode +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import eu.llembas.android.R +import eu.llembas.android.api.GeneratedImage +import eu.llembas.android.lembas +import eu.llembas.android.ui.theme.LocalPalette +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** + * The pictures the instance made, fetched the one way the app fetches a chat's files: by + * attachment id, from the instance it is signed in to, with its token. There is no URL to + * follow -- a model's words can name an address, but never a picture this draws -- and nothing + * bigger than [MAX_BYTES] is decoded. + */ +private object Pictures { + /** Longest edge decoded: enough for a phone held either way, small enough to keep a few. */ + private const val EDGE = 1600 + private const val MAX_BYTES = 24 * 1024 * 1024 + private val cache = LruCache(8) + private val failed = mutableSetOf() + + fun cached(id: String): ImageBitmap? = cache.get(id) + + suspend fun load(context: Context, id: String): ImageBitmap? { + cache.get(id)?.let { return it } + if (id.isBlank() || id in failed) return null + val api = context.lembas.instances.client() ?: return null + val bytes = runCatching { api.attachmentBytes(id) }.getOrNull()?.takeIf { it.size <= MAX_BYTES } + val image = bytes?.let { decode(it) } + if (image == null) failed += id else cache.put(id, image) + return image + } + + private suspend fun decode(bytes: ByteArray): ImageBitmap? = withContext(Dispatchers.Default) { + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) + if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return@withContext null + var sample = 1 + while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= EDGE) sample *= 2 + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })?.asImageBitmap() + } +} + +/** + * A picture `image_generate` made, in the reply: as wide as the reply allows (at most 480 dp), + * its height from the size the server said, so the transcript does not jump when it arrives. A + * tap shows it on its own, whole, on the page's ground; a tap or Back closes it. + */ +@Composable +fun GeneratedPicture(image: GeneratedImage, modifier: Modifier = Modifier) { + val palette = LocalPalette.current + val context = LocalContext.current + val still = LocalInspectionMode.current + var bitmap by remember(image.id) { mutableStateOf(Pictures.cached(image.id)) } + var whole by remember { mutableStateOf(false) } + LaunchedEffect(image.id) { if (bitmap == null && !still) bitmap = Pictures.load(context, image.id) } + val ratio = if (image.width > 0 && image.height > 0) image.width.toFloat() / image.height else 1f + 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)) + .clip(shape) + .background(palette.surfaceRaised) + .border(1.dp, palette.border, shape) + .then(if (bitmap != null) Modifier.clickable { whole = true } else Modifier), + contentAlignment = Alignment.Center, + ) { + val shown = bitmap + if (shown != null) { + Image(shown, contentDescription = described, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize()) + } else { + Icon(Icons.Filled.Image, contentDescription = described, tint = palette.inkFaint, modifier = Modifier.size(32.dp)) + } + } + val shown = bitmap + if (whole && shown != null) { + Dialog(onDismissRequest = { whole = false }, properties = DialogProperties(usePlatformDefaultWidth = false)) { + Box(Modifier.fillMaxSize().background(palette.bg).clickable { whole = false }, contentAlignment = Alignment.Center) { + Image(shown, contentDescription = described, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize()) + } + } + } +} diff --git a/app/src/main/java/eu/llembas/android/ui/chat/Transcript.kt b/app/src/main/java/eu/llembas/android/ui/chat/Transcript.kt index af61060..ef4877f 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/Transcript.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/Transcript.kt @@ -466,8 +466,8 @@ private fun ThinkingChip(step: Step) { /** * One round of tools as one chip: a single call by its title ("bake --slow"), several by their - * count. Open, each call is its block (command, change, output). A `show` card is drawn apart, - * always in view. + * count. Open, each call is its block (command, change, output). A `show` card and a picture + * the instance made are drawn apart, always in view. */ @Composable private fun ToolsChip(step: Step, onShow: ((ShowCard) -> Unit)?) { @@ -502,6 +502,9 @@ private fun ToolsChip(step: Step, onShow: ((ShowCard) -> Unit)?) { } } shows.forEach { call -> ToolCallBlock(call, onShow = onShow) } + // A picture the instance made stays in view, like a `show` card: it is the answer. + step.calls.mapNotNull { call -> call.image?.takeIf { it.id.isNotBlank() && call.status != "error" && call.error.isNullOrEmpty() } } + .forEach { GeneratedPicture(it) } } @Composable diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 2b8ede7..8fc53e6 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -62,6 +62,8 @@ Vyfotit Vybrat fotky Vybrat soubory + Generovat obrázky + Vygenerovaný obrázek Zkopírovat zprávu Zkopírováno. Přejmenovat konverzaci diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 33c65e4..9d66b50 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -62,6 +62,8 @@ Foto aufnehmen Fotos auswählen Dateien auswählen + Bilder generieren + Das generierte Bild Nachricht kopieren Kopiert. Chat umbenennen diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 9a282ff..1b4ab19 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -62,6 +62,8 @@ Hacer una foto Elegir fotos Elegir archivos + Generar imágenes + La imagen generada Copiar mensaje Copiado. Renombrar chat diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 038f4d1..7d2f331 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -62,6 +62,8 @@ Prendre une photo Choisir des photos Choisir des fichiers + Générer des images + L\'image générée Copier le message Copié. Renommer la conversation diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index bb04ae1..72eb1f4 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -62,6 +62,8 @@ Fénykép készítése Fényképek kiválasztása Fájlok kiválasztása + Képek generálása + A generált kép Üzenet másolása Másolva. Csevegés átnevezése diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index d2df1a9..3e71dea 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -62,6 +62,8 @@ Scatta una foto Scegli foto Scegli file + Generare immagini + L\'immagine generata Copia messaggio Copiato. Rinomina chat diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index d2392fd..27e0d3e 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -62,6 +62,8 @@ Zrób zdjęcie Wybierz zdjęcia Wybierz pliki + Generuj obrazy + Wygenerowany obraz Kopiuj wiadomość Skopiowano. Zmień nazwę czatu diff --git a/app/src/main/res/values-sk/strings.xml b/app/src/main/res/values-sk/strings.xml index 266b10e..c3ba3e8 100644 --- a/app/src/main/res/values-sk/strings.xml +++ b/app/src/main/res/values-sk/strings.xml @@ -62,6 +62,8 @@ Odfotiť Vybrať fotky Vybrať súbory + Generovať obrázky + Vygenerovaný obrázok Skopírovať správu Skopírované. Premenovať konverzáciu diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index fb71988..178702e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -63,6 +63,8 @@ Take a photo Choose photos Choose files + Generate images + The generated image Copy message Copied. Rename chat diff --git a/app/src/test/java/eu/llembas/android/ShowAndServerTest.kt b/app/src/test/java/eu/llembas/android/ShowAndServerTest.kt index e585fc0..0fe545b 100644 --- a/app/src/test/java/eu/llembas/android/ShowAndServerTest.kt +++ b/app/src/test/java/eu/llembas/android/ShowAndServerTest.kt @@ -15,6 +15,21 @@ import org.junit.Test * cards are in `contract/tool_show.json` and read by `ContractTest`. */ class ShowAndServerTest { + @Test + fun aGeneratedPictureIsAnAttachmentIdAndASize() { + // services/images/tool.py: `image: {id, width, height}` on the tool event; no URL at all. + val call = LembasJson.decodeFromString( + ToolCall.serializer(), + """{"id":"t1","name":"image_generate","status":"ok","attachment_id":"att1", + "image":{"id":"att1","width":1216,"height":832},"block":{"kind":"image","title":"a leaf"}}""", + ) + assertEquals("att1", call.image!!.id) + assertEquals(1216, call.image!!.width) + assertEquals(832, call.image!!.height) + assertNull(LembasJson.decodeFromString(ToolCall.serializer(), """{"name":"read"}""").image) + assertEquals("image_generate", eu.llembas.android.ui.chat.IMAGE_TOOL) + } + private fun call(json: String) = LembasJson.decodeFromString(ToolCall.serializer(), json) @Test diff --git a/app/src/test/java/eu/llembas/android/shots/Fakes.kt b/app/src/test/java/eu/llembas/android/shots/Fakes.kt index 22acfff..f3f343c 100644 --- a/app/src/test/java/eu/llembas/android/shots/Fakes.kt +++ b/app/src/test/java/eu/llembas/android/shots/Fakes.kt @@ -10,6 +10,7 @@ import eu.llembas.android.api.Chat import eu.llembas.android.api.ContextPart import eu.llembas.android.api.DataGroup import eu.llembas.android.api.Folder +import eu.llembas.android.api.GeneratedImage import eu.llembas.android.api.LembasJson import eu.llembas.android.api.LinkedDevice import eu.llembas.android.api.LiveReply @@ -115,6 +116,38 @@ object Fakes { val chat = Chat(id = "c1", title = "Packing for the road", model = "qwen", updatedAt = "2026-03-10T09:00:00+00:00") + // A picture the instance made, and the composer asking for the next one. + val picture = ChatState( + chat = chat, + models = models, + imagesOffered = true, + draft = Draft(image = true), + messages = listOf( + Message(id = "p1", role = "user", text = "Draw lembas wrapped in a mallorn leaf, on a wooden table."), + Message( + id = "p2", + role = "assistant", + model = "qwen", + steps = listOf( + Step( + index = 0, + kind = "tools", + calls = listOf( + ToolCall( + id = "g1", + name = "image_generate", + status = "ok", + image = GeneratedImage(id = "att-picture", width = 1216, height = 832), + block = ToolBlock(kind = "image", title = "lembas in a mallorn leaf"), + ), + ), + ), + Step(index = 1, kind = "text", markdown = "Here it is: the leaf folded twice, as the elves wrap it."), + ), + ), + ), + ) + val newChat = ChatState(models = models) val newAgentChat = ChatState( diff --git a/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt b/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt index 915b19e..0cb97d2 100644 --- a/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt +++ b/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt @@ -250,6 +250,13 @@ class ScreenShots { shoot("27-archived-none") { ArchivedContent(ChatsState(), NoArchivedActions) } } + @Test + fun picture() { + // The picture's place is its size before it loads (screenshots fetch nothing). + shoot("29-generated-image") { ChatContent(Fakes.picture, NoChatActions, agent = false) } + shoot("29-generated-image", Phone.Small, fontScale = 1.5f) { ChatContent(Fakes.picture, NoChatActions, agent = false) } + } + @Test fun memory() { shoot("28-memory") { MemoryContent(Fakes.memory, NoMemoryActions) } diff --git a/scripts/strings.py b/scripts/strings.py index 266f6c1..0f25ffe 100755 --- a/scripts/strings.py +++ b/scripts/strings.py @@ -75,6 +75,8 @@ STRINGS: dict[str, str] = { "attach_take_photo": "Take a photo", "attach_choose_photos": "Choose photos", "attach_choose_files": "Choose files", + "image_generate": "Generate images", + "image_generated": "The generated image", "copy_message": "Copy message", "copied": "Copied.", "rename_chat": "Rename chat",