Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import dev.opencode.mobile.ui.sessionchat.SessionChatScreen
import dev.opencode.mobile.ui.sessionchat.view.SessionChatToolDetailSheet
import dev.opencode.mobile.ui.sessionchat.view.SessionChatToolDetailTarget
import dev.opencode.mobile.ui.sessionchat.view.SessionChatToolGroupScreen
import dev.opencode.mobile.ui.sessionchat.view.toTarget
import dev.opencode.mobile.ui.sessionchat.view.toTargetWithImages
import dev.opencode.mobile.ui.sessioncontext.SessionContextScreen
import dev.opencode.mobile.ui.terminal.TerminalScreen

Expand Down Expand Up @@ -192,7 +192,7 @@ internal fun EntryProviderScope<NavKey>.chatFlowEntries(
var blockedTurnDiff by remember { mutableStateOf<OpenCodeSnackbarMessage?>(null) }
Box(Modifier.fillMaxSize()) {
SessionChatToolGroupScreen(
target = key.toTarget(),
target = key.toTargetWithImages(),
supportsSessionMessageDiff = key.supportsSessionMessageDiff,
onNavigateBack = navigator.navigateBack,
onToolDetailTap = {
Expand Down
2 changes: 2 additions & 0 deletions android/app/src/main/java/dev/opencode/mobile/Navigation.kt
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ import dev.opencode.mobile.ui.componentgallery.components.ActionTileGalleryScree
import dev.opencode.mobile.ui.componentgallery.components.ActivityCardGalleryScreen
import dev.opencode.mobile.ui.componentgallery.components.AssistantMessageGalleryScreen
import dev.opencode.mobile.ui.componentgallery.components.AttachmentGalleryScreen
import dev.opencode.mobile.ui.componentgallery.components.ImageGalleryGalleryScreen
import dev.opencode.mobile.ui.componentgallery.components.BottomFadeGalleryScreen
import dev.opencode.mobile.ui.componentgallery.components.BottomSheetGalleryScreen
import dev.opencode.mobile.ui.componentgallery.components.ButtonGalleryScreen
Expand Down Expand Up @@ -699,6 +700,7 @@ fun MainNavigation() {
ComponentGalleryEntryId.Tag -> TagGalleryScreen()
ComponentGalleryEntryId.KeyValueRow -> KeyValueRowGalleryScreen()
ComponentGalleryEntryId.Attachment -> AttachmentGalleryScreen()
ComponentGalleryEntryId.ImageGallery -> ImageGalleryGalleryScreen()
ComponentGalleryEntryId.OutgoingMessage -> OutgoingMessageGalleryScreen()
ComponentGalleryEntryId.PendingPromptsStrip ->
PendingPromptsStripGalleryScreen()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@ data class MessageToolStateDto(
val interrupted: Boolean? = null,
/** Set when the server closed the call without running it (`executed: false`). */
val malformed: Boolean? = null,
/** v1 completed-state files the tool returned (`url` is a `data:` URL); the v2 live projection fills it too. */
val attachments: List<MessagePartDto>? = null,
)

@Serializable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import dev.opencode.mobile.domain.message.UploadedAttachments
import dev.opencode.mobile.domain.message.ToolArgumentsPreview
import dev.opencode.mobile.domain.message.ToolInterruption
import dev.opencode.mobile.domain.message.ToolPartIdentity
import dev.opencode.mobile.domain.message.ToolResultImages
import dev.opencode.mobile.domain.message.V2ContentPartId
import dev.opencode.mobile.domain.message.V2TimelineNotices
import dev.opencode.mobile.domain.session.SessionActivity
Expand All @@ -21,6 +22,7 @@ import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
Expand Down Expand Up @@ -696,6 +698,7 @@ class EventDomainAdapter(
properties = properties,
messageId = properties.string("assistantMessageID"),
partId = partId,
attachments = toolFileAttachments(properties["content"], partId),
toolName = name,
status = status,
callId = callId,
Expand All @@ -710,6 +713,35 @@ class EventDomainAdapter(
)
}

/**
* `tool.success` (and `tool.failed`) `content[]` files, written as the v1 completed-state
* `attachments` so one adapter path keeps them. Ids match the REST projection.
*/
private fun toolFileAttachments(
content: JsonElement?,
partId: String?,
): JsonArray? {
val files =
(content as? JsonArray)
?.mapNotNull { it as? JsonObject }
?.filter { it.string("type") == "file" }
.orEmpty()
if (files.isEmpty()) return null
return buildJsonArray {
files.forEachIndexed { index, file ->
add(
buildJsonObject {
put("id", ToolResultImages.id(partId, index))
put("type", "file")
file.string("uri")?.let { put("url", it) }
file.string("mime")?.let { put("mime", it) }
file.string("name")?.let { put("filename", it) }
},
)
}
}
}

/**
* v2 tool events carry tool-reported metadata (a subagent's `sessionID`
* arrives on `tool.progress` while it is still running) under `metadata`;
Expand Down Expand Up @@ -985,11 +1017,13 @@ class EventDomainAdapter(
title: String? = null,
interrupted: Boolean = false,
malformed: Boolean = false,
attachments: JsonArray? = null,
): OpencodeEvent {
val sessionId = sessionIdFromProperties(properties)
val state =
buildJsonObject {
put("status", status)
attachments?.let { put("attachments", it) }
if (interrupted) put("interrupted", true)
if (malformed) put("malformed", true)
title?.let { put("title", it) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,11 @@ sealed class MessagePart {
val isInterrupted: Boolean = false,
/** The model emitted a tool call the server could not run (`executed: false`). */
val isMalformed: Boolean = false,
/**
* Images the tool returned (v1 `attachments`, v2 `content[type=file]`), in order. Only
* images the app can show; other returned files are dropped. Each carries its data URL.
*/
val images: List<File> = emptyList(),
) : MessagePart()

data class File(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,17 @@ class AttachmentPreviewCache(
fun warm(messages: List<Message>) {
messages.forEach { message ->
message.parts.forEach { part ->
val file = part as? MessagePart.File ?: return@forEach
val key = key(file) ?: return@forEach
val cached = synchronized(entries) { entries.containsKey(key) }
if (!cached) decodeAndStore(file, key)
val files =
when (part) {
is MessagePart.File -> listOf(part)
is MessagePart.Tool -> part.images
else -> return@forEach
}
files.forEach { file ->
val key = key(file) ?: return@forEach
val cached = synchronized(entries) { entries.containsKey(key) }
if (!cached) decodeAndStore(file, key)
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package dev.opencode.mobile.domain.message

/**
* Images a tool returned (v1 completed-state `attachments`, v2 `content[type=file]`). Only
* `data:` URLs of an image type the timeline can show are kept; other files are dropped.
* The payload is not decoded here: a broken image shows as a failed tile, not a lost part.
*/
object ToolResultImages {
/** Id of the [index]th image of tool part [toolPartId], the same on REST and live events. */
fun id(
toolPartId: String?,
index: Int,
): String = "${toolPartId ?: "tool"}:image:$index"

fun image(
id: String,
dataUrl: String?,
mime: String?,
name: String?,
): MessagePart.File? {
val url = dataUrl?.takeIf { it.startsWith("data:", ignoreCase = true) } ?: return null
// The data URL header is what the decoder checks, so it wins over the declared mime.
val resolvedMime =
(AttachmentDataUrl.mimeFromDataUrl(url) ?: mime ?: name?.let(AttachmentDataUrl::mimeFromFilename))
?.lowercase()
?: return null
if (AttachmentDataUrl.kind(resolvedMime) != AttachmentKind.Image) return null
if (!url.startsWith("data:$resolvedMime;base64,", ignoreCase = true)) return null
return MessagePart.File(
id = id,
filename = displayName(name),
mime = resolvedMime,
kind = AttachmentKind.Image,
dataUrl = url,
)
}

/** v2 `read` names the image by the path it read; the tile shows the file name only. */
private fun displayName(name: String?): String {
val trimmed = name?.trim().orEmpty().trimEnd('/', '\\')
val last = trimmed.substringAfterLast('/').substringAfterLast('\\')
return last.ifEmpty { "Image" }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -179,9 +179,27 @@ class MessageDomainAdapter(
status == ToolStatus.Error &&
(state?.interrupted == true || ToolInterruption.isUserInterruption(state?.error)),
isMalformed = state?.malformed == true,
images = v1ToolImages(state?.attachments, partId = id ?: callId),
)
}

/** v1 tool `attachments` (file parts); the v2 live projection writes the same shape. */
private fun v1ToolImages(
attachments: List<MessagePartDto>?,
partId: String?,
): List<MessagePart.File> =
attachments
.orEmpty()
.filter { it.type == "file" }
.mapIndexedNotNull { index, file ->
ToolResultImages.image(
id = file.id ?: ToolResultImages.id(partId, index),
dataUrl = file.url,
mime = file.mime,
name = file.filename,
)
}

fun toToolStatus(raw: String?): ToolStatus =
when (raw) {
"pending", "streaming" -> ToolStatus.Pending
Expand Down Expand Up @@ -839,11 +857,30 @@ class MessageDomainAdapter(
type = state?.error?.type,
executed = state?.executed,
),
images = v2ToolImages(state, partId = content.id ?: fallbackId),
)
}
else -> null
}

/** v2 tool `content[]` files; live `tool.success` projects the same ids ([ToolResultImages.id]). */
private fun v2ToolImages(
state: V2ToolStateDto?,
partId: String,
): List<MessagePart.File> =
state
?.content
.orEmpty()
.filter { it.type == "file" }
.mapIndexedNotNull { index, item ->
ToolResultImages.image(
id = ToolResultImages.id(partId, index),
dataUrl = item.uri,
mime = item.mime,
name = item.name,
)
}

/** `metadata.attachments` of a v2 prompt: files the client uploaded and named in the text. */
private fun uploadedFileParts(dto: V2SessionMessageDto): List<MessagePart.File> = uploadedFileParts(dto.id, dto.metadata)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1084,6 +1084,8 @@ class InMemoryMessageStore
timeStartEpochMs = incoming.timeStartEpochMs ?: existing.timeStartEpochMs,
isInterrupted = incoming.isInterrupted,
isMalformed = incoming.isMalformed || existing.isMalformed,
// Only the terminal update carries files; a later bare update keeps them.
images = incoming.images.ifEmpty { existing.images },
)
}
existing is MessagePart.Text && incoming is MessagePart.Text -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ enum class ComponentGalleryEntryId {
Tag,
KeyValueRow,
Attachment,
ImageGallery,
OutgoingMessage,
PendingPromptsStrip,
AssistantMessage,
Expand Down Expand Up @@ -351,6 +352,12 @@ val ComponentGalleryEntries =
description = "Pending attachment chips and sent-message attachment rows.",
category = ComponentGalleryCategory.Chat,
),
ComponentGalleryEntry(
id = ComponentGalleryEntryId.ImageGallery,
title = "Image Gallery",
description = "Inline image mosaic by count with +N overflow, and the paged full-screen viewer.",
category = ComponentGalleryCategory.Chat,
),
ComponentGalleryEntry(
id = ComponentGalleryEntryId.MessageList,
title = "Message List",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package dev.opencode.mobile.ui.componentgallery.components

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import dev.opencode.mobile.ui.components.LocalOpenCodeGalleryImageLoader
import dev.opencode.mobile.ui.components.OpenCodeGalleryImage
import dev.opencode.mobile.ui.components.OpenCodeImageGallery
import dev.opencode.mobile.ui.components.OpenCodeImageGalleryViewer
import dev.opencode.mobile.ui.components.OpenCodeOutgoingMessage
import dev.opencode.mobile.ui.components.OpenCodeOutgoingMessageContent
import dev.opencode.mobile.ui.snapshot.SnapshotEvidenceGalleryMocks

/** Image Gallery: every layout by count, loading and failed tiles, a sent group, and the paged viewer. */
@Composable
fun ImageGalleryGalleryScreen() {
var open by remember { mutableStateOf<Pair<List<OpenCodeGalleryImage>, Int>?>(null) }
val loader = remember { SnapshotEvidenceGalleryMocks.Loader() }
val slowLoader = remember { SnapshotEvidenceGalleryMocks.Loader(delayMs = Long.MAX_VALUE) }

@Composable
fun Example(
title: String,
images: List<OpenCodeGalleryImage>,
) {
Text(title, style = MaterialTheme.typography.titleMedium)
OpenCodeImageGallery(images = images, onImageClick = { index -> open = images to index })
}

CompositionLocalProvider(LocalOpenCodeGalleryImageLoader provides loader) {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Example("One image (aspect kept, height capped)", SnapshotEvidenceGalleryMocks.images(1))
Example("Two images", SnapshotEvidenceGalleryMocks.images(2))
Example("Three images", SnapshotEvidenceGalleryMocks.images(3))
Example("Four images", SnapshotEvidenceGalleryMocks.images(4))
Example("Six images (+3 overflow)", SnapshotEvidenceGalleryMocks.images(6))
Example(
"Failed tile beside loaded ones",
SnapshotEvidenceGalleryMocks.images(2) + SnapshotEvidenceGalleryMocks.image(SnapshotEvidenceGalleryMocks.failing),
)
Text("Loading", style = MaterialTheme.typography.titleMedium)
CompositionLocalProvider(LocalOpenCodeGalleryImageLoader provides slowLoader) {
OpenCodeImageGallery(
images =
listOf(
OpenCodeGalleryImage("gallery-loading-1", "loading-1.png"),
OpenCodeGalleryImage("gallery-loading-2", "loading-2.png"),
),
onImageClick = {},
)
}
Text("Sent in a message", style = MaterialTheme.typography.titleMedium)
val sent = SnapshotEvidenceGalleryMocks.images(3)
OpenCodeOutgoingMessage(
text = "Here are the three screens.",
metadataLabel = "Build · Example Model · 9:05 PM",
content =
listOf(
OpenCodeOutgoingMessageContent.ImageGallery(id = "sent", images = sent),
OpenCodeOutgoingMessageContent.Text("Here are the three screens."),
),
onImageClick = { _, index -> open = sent to index },
modifier = Modifier.fillMaxWidth(),
)
}
open?.let { (images, index) ->
OpenCodeImageGalleryViewer(
images = images,
index = index,
onIndexChange = { page -> open = images to page },
onDismiss = { open = null },
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -156,16 +156,18 @@ private fun uploadDetail(upload: OpenCodeAttachmentUploadState.InProgress): Stri
/**
* A sent attachment in the timeline. Images show inline at their own aspect ratio, capped in
* height ([OpenCodeMessageImage]); everything else, and any image that cannot load, is a chip.
* [onOpenImage], when set, is how a tap on the image opens the owner's viewer.
*/
@Composable
fun OpenCodeMessageAttachment(
attachment: OpenCodeAttachmentPresentation,
modifier: Modifier = Modifier,
onOpenImage: (() -> Unit)? = null,
) {
if (attachment.variant == OpenCodeAttachmentVariant.Image &&
(attachment.imageBytes != null || attachment.imageSource != null)
) {
OpenCodeMessageImage(attachment, modifier) { OpenCodeMessageAttachmentChip(attachment, modifier) }
OpenCodeMessageImage(attachment, modifier, onOpen = onOpenImage) { OpenCodeMessageAttachmentChip(attachment, modifier) }
} else {
OpenCodeMessageAttachmentChip(attachment, modifier)
}
Expand Down
Loading