Generate images from the composer; the picture in its own safe composable
CI / check (push) Canceled after 0s

+ › Generate images (when /me services.images) marks the next message, shown as a chip under
the box; it is sent with force_tool image_generate (the server's only forceable tool) on
POST /chats/{id}/messages. The tool event's `image {id, width, height}` is drawn by
GeneratedPicture: fetched only by attachment id from GET /api/v2/attachments/{id} with the
token (no URL is ever followed), at most 24 MB, decoded to a 1600 px edge, its box sized by the
server's width/height before it loads; a tap shows it whole. Markwon stays image-free.

Chosen over /v1/images/generations (models scope, which sign-in already asks): the in-chat tool
keeps the picture in the chat as the web does. A NEW chat cannot force a tool yet (POST /chats
takes no force_tool), so the option shows in an existing chat only -- server follow-up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Opus 5.5 committed 2026-11-10 13:54:34 +00:00
1 parent 87d391c352
commit d9654dd23c
20 files changed
+258 -4

No files matched your search

+4
View File
@@ -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.
@@ -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<String> = 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<String> = 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) }
},
)
@@ -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<ToolCall>? = 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
@@ -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.
@@ -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
@@ -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<String, ImageBitmap>(8)
private val failed = mutableSetOf<String>()
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())
}
}
}
}
@@ -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
+2
View File
@@ -62,6 +62,8 @@
<string name="attach_take_photo">Vyfotit</string>
<string name="attach_choose_photos">Vybrat fotky</string>
<string name="attach_choose_files">Vybrat soubory</string>
<string name="image_generate">Generovat obrázky</string>
<string name="image_generated">Vygenerovaný obrázek</string>
<string name="copy_message">Zkopírovat zprávu</string>
<string name="copied">Zkopírováno.</string>
<string name="rename_chat">Přejmenovat konverzaci</string>
+2
View File
@@ -62,6 +62,8 @@
<string name="attach_take_photo">Foto aufnehmen</string>
<string name="attach_choose_photos">Fotos auswählen</string>
<string name="attach_choose_files">Dateien auswählen</string>
<string name="image_generate">Bilder generieren</string>
<string name="image_generated">Das generierte Bild</string>
<string name="copy_message">Nachricht kopieren</string>
<string name="copied">Kopiert.</string>
<string name="rename_chat">Chat umbenennen</string>
+2
View File
@@ -62,6 +62,8 @@
<string name="attach_take_photo">Hacer una foto</string>
<string name="attach_choose_photos">Elegir fotos</string>
<string name="attach_choose_files">Elegir archivos</string>
<string name="image_generate">Generar imágenes</string>
<string name="image_generated">La imagen generada</string>
<string name="copy_message">Copiar mensaje</string>
<string name="copied">Copiado.</string>
<string name="rename_chat">Renombrar chat</string>
+2
View File
@@ -62,6 +62,8 @@
<string name="attach_take_photo">Prendre une photo</string>
<string name="attach_choose_photos">Choisir des photos</string>
<string name="attach_choose_files">Choisir des fichiers</string>
<string name="image_generate">Générer des images</string>
<string name="image_generated">L\'image générée</string>
<string name="copy_message">Copier le message</string>
<string name="copied">Copié.</string>
<string name="rename_chat">Renommer la conversation</string>
+2
View File
@@ -62,6 +62,8 @@
<string name="attach_take_photo">Fénykép készítése</string>
<string name="attach_choose_photos">Fényképek kiválasztása</string>
<string name="attach_choose_files">Fájlok kiválasztása</string>
<string name="image_generate">Képek generálása</string>
<string name="image_generated">A generált kép</string>
<string name="copy_message">Üzenet másolása</string>
<string name="copied">Másolva.</string>
<string name="rename_chat">Csevegés átnevezése</string>
+2
View File
@@ -62,6 +62,8 @@
<string name="attach_take_photo">Scatta una foto</string>
<string name="attach_choose_photos">Scegli foto</string>
<string name="attach_choose_files">Scegli file</string>
<string name="image_generate">Generare immagini</string>
<string name="image_generated">L\'immagine generata</string>
<string name="copy_message">Copia messaggio</string>
<string name="copied">Copiato.</string>
<string name="rename_chat">Rinomina chat</string>
+2
View File
@@ -62,6 +62,8 @@
<string name="attach_take_photo">Zrób zdjęcie</string>
<string name="attach_choose_photos">Wybierz zdjęcia</string>
<string name="attach_choose_files">Wybierz pliki</string>
<string name="image_generate">Generuj obrazy</string>
<string name="image_generated">Wygenerowany obraz</string>
<string name="copy_message">Kopiuj wiadomość</string>
<string name="copied">Skopiowano.</string>
<string name="rename_chat">Zmień nazwę czatu</string>
+2
View File
@@ -62,6 +62,8 @@
<string name="attach_take_photo">Odfotiť</string>
<string name="attach_choose_photos">Vybrať fotky</string>
<string name="attach_choose_files">Vybrať súbory</string>
<string name="image_generate">Generovať obrázky</string>
<string name="image_generated">Vygenerovaný obrázok</string>
<string name="copy_message">Skopírovať správu</string>
<string name="copied">Skopírované.</string>
<string name="rename_chat">Premenovať konverzáciu</string>
+2
View File
@@ -63,6 +63,8 @@
<string name="attach_take_photo">Take a photo</string>
<string name="attach_choose_photos">Choose photos</string>
<string name="attach_choose_files">Choose files</string>
<string name="image_generate">Generate images</string>
<string name="image_generated">The generated image</string>
<string name="copy_message">Copy message</string>
<string name="copied">Copied.</string>
<string name="rename_chat">Rename chat</string>
@@ -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
@@ -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(
@@ -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) }
+2
View File
@@ -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",