diff --git a/CHANGELOG.md b/CHANGELOG.md index 27dfd2c2..ef2a49fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,7 @@ like `## [0.4.16] - 2026-10-24`. - A picture too large for the model no longer fails the chat or a subagent through CLIProxyAPI: on the OpenAI-compatible wire, as on the Anthropic one, an image over 8000 px a side goes as a note, and for Claude, once a request holds more than 20 images and PDFs, so does one over 3000 px. The stored history keeps the picture. A remaining "image dimensions exceed max allowed size" 400 drops the picture and retries instead of falling back to another model. A full-page browser screenshot of a page wider than 7900 px stops at 7900 px. - Windows: commands work on PCs without Git Bash, using cmd.exe batch scripts. Quoted paths, multiline blocks, percent variables, exit codes and working-directory changes stay intact; command timeouts stop the process tree. - The agent is told the device's actual execution shell and Windows command syntax instead of assuming Unix commands. +- Android: opening a very big chat (a 90 MB transcript full of screenshots) no longer crashes the app. It reads the newest 200 messages with large blocks left out, the same paged API as the web, and reads older pages as you scroll to the top. A picture or document a page left out is read from the hub when it shows or when Edit or Retry sends it again, and chat images are decoded at about the size they show. ## [0.4.104] - 2026-11-19 diff --git a/packages/android/app/src/main/kotlin/dev/conclave/app/ui/chat/ChatScreen.kt b/packages/android/app/src/main/kotlin/dev/conclave/app/ui/chat/ChatScreen.kt index 75f7dcba..504d2b82 100644 --- a/packages/android/app/src/main/kotlin/dev/conclave/app/ui/chat/ChatScreen.kt +++ b/packages/android/app/src/main/kotlin/dev/conclave/app/ui/chat/ChatScreen.kt @@ -19,6 +19,7 @@ import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.icons.Icons @@ -46,7 +47,9 @@ import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext @@ -219,6 +222,7 @@ fun ChatScreen( val context = LocalContext.current val scope = rememberCoroutineScope() val listState = rememberLazyListState() + OlderOnTop(listState, vm::loadOlder) var actionsFor by remember { mutableStateOf(null) } var pickFor by remember { mutableStateOf?>(null) } @@ -784,3 +788,17 @@ private fun MessageActionsSheet( } } +/** + * Near the top of what a transcript holds (a reversed list, so its last + * items): [load] reads the page before it. The count asks again after each + * page lands, so a page that fits the screen still reads the next one. + */ +@Composable +internal fun OlderOnTop(state: LazyListState, load: () -> Unit) { + val current by rememberUpdatedState(load) + LaunchedEffect(state) { + snapshotFlow { state.layoutInfo.run { totalItemsCount.takeIf { it > 0 && (visibleItemsInfo.lastOrNull()?.index ?: 0) >= it - 3 } } } + .collect { if (it != null) current() } + } +} + diff --git a/packages/android/app/src/main/kotlin/dev/conclave/app/ui/chat/ChatViewModel.kt b/packages/android/app/src/main/kotlin/dev/conclave/app/ui/chat/ChatViewModel.kt index 960f1dd4..7fa88147 100644 --- a/packages/android/app/src/main/kotlin/dev/conclave/app/ui/chat/ChatViewModel.kt +++ b/packages/android/app/src/main/kotlin/dev/conclave/app/ui/chat/ChatViewModel.kt @@ -48,6 +48,7 @@ import dev.conclave.client.moveToHub import dev.conclave.client.workflowRuns import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow @@ -145,8 +146,9 @@ class ChatViewModel(hub: HubRepository, val sessionId: String, drafts: DraftStor val after = if (quiet) TranscriptReducer.reloadAfter(transcript.value) else null val askedAt = System.currentTimeMillis() val version = transcript.value.queueVersion - val msgs = hub.api { it.messages(sessionId, afterSeq = after) } - transcript.update { TranscriptReducer.merge(it, msgs) } + // the newest page, light (a 90 MB chat of screenshots ended the app); older pages come on scroll (loadOlder) + val msgs = hub.api { it.messages(sessionId, afterSeq = after, limit = if (after == null) TranscriptReducer.PAGE else null, trim = true) } + transcript.update { TranscriptReducer.loaded(it, msgs, paged = after == null) } // what waits while it works; a hub from before the queue has none to say runCatching { hub.api { it.queue(sessionId) } }.getOrNull()?.let { list -> transcript.update { TranscriptReducer.loadedQueue(it, list, askedAt, version) } @@ -174,6 +176,18 @@ class ChatViewModel(hub: HubRepository, val sessionId: String, drafts: DraftStor } } + private var olderLoad: Job? = null + + /** Scrolled to the top: the page before the first message held, one read at a time. */ + fun loadOlder() { + if (olderLoad?.isActive == true) return + val before = TranscriptReducer.olderBefore(transcript.value) ?: return + olderLoad = action { + val page = hub.api { it.messages(sessionId, beforeSeq = before, limit = TranscriptReducer.PAGE, trim = true) } + transcript.update { TranscriptReducer.olderPage(it, page) } + } + } + /** Open here: a reply that came clears its bold title in the lists, on the hub so the web agrees (logic/Unread.kt). */ private fun seen(s: Session) { if (!Unread.isUnread(s)) return @@ -453,12 +467,14 @@ class ChatViewModel(hub: HubRepository, val sessionId: String, drafts: DraftStor } private suspend fun retryFrom(user: Message) { + // before the rewind: a file a trimmed page left out is read from the message the rewind drops + val files = attachmentsOf(hub, user) if (running.value) hub.api { it.abort(sessionId) } // the hub keeps messages up to the seq it is given and drops the rest _session.value = hub.api { it.rewind(sessionId, user.seq - 1) } transcript.value = Transcript(sessionId) load(quiet = true) - hub.api { it.send(sessionId, SendInput(text = user.content.visibleText(), attachments = attachmentsOf(user).ifEmpty { null })) } + hub.api { it.send(sessionId, SendInput(text = user.content.visibleText(), attachments = files.ifEmpty { null })) } } /** The refused reply sent to the next model: its button reads "Trying" until the hub drops the reply. */ diff --git a/packages/android/app/src/main/kotlin/dev/conclave/app/ui/chat/Messages.kt b/packages/android/app/src/main/kotlin/dev/conclave/app/ui/chat/Messages.kt index 04fdee05..8c76554f 100644 --- a/packages/android/app/src/main/kotlin/dev/conclave/app/ui/chat/Messages.kt +++ b/packages/android/app/src/main/kotlin/dev/conclave/app/ui/chat/Messages.kt @@ -3,7 +3,6 @@ package dev.conclave.app.ui.chat import dev.conclave.client.model.isReminder -import android.graphics.BitmapFactory import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.background @@ -63,18 +62,21 @@ import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.ImageBitmap -import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp +import androidx.compose.ui.platform.LocalDensity +import dev.conclave.app.ui.common.LocalAppContainer import dev.conclave.app.ui.common.MarkdownText import dev.conclave.app.ui.common.ModelMark import dev.conclave.app.ui.common.ModelName import dev.conclave.app.ui.common.rememberNow import dev.conclave.app.ui.conversation.ChatProse import dev.conclave.app.ui.conversation.FullImage +import dev.conclave.app.ui.conversation.decodeScaled +import dev.conclave.app.ui.conversation.imageData import dev.conclave.app.ui.conversation.LocalSessionWork import dev.conclave.app.ui.conversation.SessionWork import dev.conclave.app.ui.conversation.TurnWork @@ -109,7 +111,6 @@ import dev.conclave.client.model.plainText import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -import java.util.Base64 /** * Your message in a session (MOBILE-V2 5): right aligned in a bubble of @@ -518,18 +519,11 @@ fun SummaryLine(message: Message) { @Composable fun InlineImage(block: ImageBlock) { - val data = block.data - val bitmap by produceState(null, data) { - value = if (data.isNullOrBlank()) { - null - } else { - withContext(Dispatchers.Default) { - runCatching { - val bytes = Base64.getDecoder().decode(data) - BitmapFactory.decodeByteArray(bytes, 0, bytes.size)?.asImageBitmap() - }.getOrNull() - } - } + val hub = LocalAppContainer.current.hub + // decoded at about the size it shows, not full size; one a trimmed page left out is read from the hub now + val target = with(LocalDensity.current) { 560.dp.roundToPx() } + val bitmap by produceState(null, block, target) { + value = withContext(Dispatchers.Default) { hub.imageData(block)?.let { decodeScaled(it, target) } } } val img = bitmap var shown by remember { mutableStateOf(false) } diff --git a/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/ChatThread.kt b/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/ChatThread.kt index 62e522cb..f1d09295 100644 --- a/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/ChatThread.kt +++ b/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/ChatThread.kt @@ -59,6 +59,7 @@ import androidx.lifecycle.viewmodel.compose.viewModel import dev.conclave.app.ui.chat.ApprovalPrompt import dev.conclave.app.ui.chat.NotesStrip import dev.conclave.app.ui.chat.NotesViewModel +import dev.conclave.app.ui.chat.OlderOnTop import dev.conclave.app.ui.chat.QuestionPrompt import dev.conclave.app.ui.common.ConfirmDialog import dev.conclave.app.ui.common.ErrorBanner @@ -320,6 +321,7 @@ fun ChatThreadScreen( } val listState = rememberLazyListState() + OlderOnTop(listState, vm::loadOlder) val reduced = reducedMotion() // sending brings you back to the bottom LaunchedEffect(pending?.at) { diff --git a/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/ChatViewModels.kt b/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/ChatViewModels.kt index 441f3d60..840cfcdc 100644 --- a/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/ChatViewModels.kt +++ b/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/ChatViewModels.kt @@ -55,6 +55,7 @@ import dev.conclave.client.model.ThinkingLevel import dev.conclave.client.model.visibleText import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted @@ -146,11 +147,11 @@ internal object ChatStarts { fun done(key: String) = _all.update { it - key } } -/** The attachments a message was sent with, so Edit and Retry send them again. */ -fun attachmentsOf(m: Message): List = m.content.mapNotNull { b -> +/** The attachments a message was sent with, so Edit and Retry send them again; one a trimmed page left out is read from the hub. */ +suspend fun attachmentsOf(hub: HubRepository, m: Message): List = m.content.mapNotNull { b -> when (b) { - is ImageBlock -> b.data?.let { Attachment(mediaType = b.mediaType, data = it, name = "image") } - is DocumentBlock -> b.data?.let { Attachment(mediaType = b.mediaType, data = it, name = b.title ?: "document") } + is ImageBlock -> hub.blockData(b.data, b.url)?.let { Attachment(mediaType = b.mediaType, data = it, name = "image") } + is DocumentBlock -> hub.blockData(b.data, b.url)?.let { Attachment(mediaType = b.mediaType, data = it, name = b.title ?: "document") } else -> null } } @@ -351,8 +352,9 @@ class ChatThreadViewModel( val after = if (quiet) TranscriptReducer.reloadAfter(transcript.value) else null val askedAt = System.currentTimeMillis() val version = transcript.value.queueVersion - val msgs = hub.api { it.messages(sessionId, afterSeq = after) } - transcript.update { TranscriptReducer.merge(it, msgs) } + // the newest page, light (a 90 MB chat of screenshots ended the app); older pages come on scroll (loadOlder) + val msgs = hub.api { it.messages(sessionId, afterSeq = after, limit = if (after == null) TranscriptReducer.PAGE else null, trim = true) } + transcript.update { TranscriptReducer.loaded(it, msgs, paged = after == null) } // what waits behind the reply; a hub from before the queue has none to say runCatching { hub.api { it.queue(sessionId) } }.getOrNull()?.let { list -> transcript.update { TranscriptReducer.loadedQueue(it, list, askedAt, version) } @@ -407,6 +409,18 @@ class ChatThreadViewModel( private fun knownIds(): Set = transcript.value.messages.map { it.id }.toSet() + private var olderLoad: Job? = null + + /** Scrolled to the top: the page before the first message held, one read at a time. */ + fun loadOlder() { + if (olderLoad?.isActive == true) return + val before = TranscriptReducer.olderBefore(transcript.value) ?: return + olderLoad = action { + val page = hub.api { it.messages(sessionId, beforeSeq = before, limit = TranscriptReducer.PAGE, trim = true) } + transcript.update { TranscriptReducer.olderPage(it, page) } + } + } + /** Sends the draft. While a reply runs it queues: it shows at once, Queued, and goes out when that reply ends. */ fun send() = send(loss = null) @@ -552,8 +566,8 @@ class ChatThreadViewModel( val s = hub.api { it.rewind(sessionId, from.seq - 1) } rewound = true onSession(s) - val msgs = hub.api { it.messages(sessionId) } - transcript.value = TranscriptReducer.merge(Transcript(sessionId), msgs) + val msgs = hub.api { it.messages(sessionId, limit = TranscriptReducer.PAGE, trim = true) } + transcript.value = TranscriptReducer.loaded(Transcript(sessionId), msgs, paged = true) hidden.value = emptySet() hub.api { it.send(sessionId, SendInput(text = text, attachments = files.ifEmpty { null })) } } catch (e: CancellationException) { @@ -593,11 +607,11 @@ class ChatThreadViewModel( return@launch } } - replaceFrom(user, user.content.visibleText(), attachmentsOf(user)) + action { replaceFrom(user, user.content.visibleText(), attachmentsOf(hub, user)) } } } - fun edit(message: Message, text: String) = replaceFrom(message, text.trim(), attachmentsOf(message)) + fun edit(message: Message, text: String) = action { replaceFrom(message, text.trim(), attachmentsOf(hub, message)) } /** Retry after a failure: send your last message again. */ fun retryLast() { @@ -606,7 +620,7 @@ class ChatThreadViewModel( return } val user = transcript.value.messages.lastOrNull { it.role == Role.USER && it.kind == MessageKind.NORMAL && !ChatItems.isToolResultsOnly(it) && !AgentResults.isContextOnly(it) } ?: return - replaceFrom(user, user.content.visibleText(), attachmentsOf(user)) + action { replaceFrom(user, user.content.visibleText(), attachmentsOf(hub, user)) } } /** The refused reply sent to the next model: its button reads "Trying" until the hub drops the reply. */ diff --git a/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/Reply.kt b/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/Reply.kt index d9a62747..375ac4ee 100644 --- a/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/Reply.kt +++ b/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/Reply.kt @@ -83,6 +83,8 @@ import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties +import dev.conclave.app.data.HubRepository +import dev.conclave.app.ui.common.LocalAppContainer import dev.conclave.app.ui.common.ModelName import dev.conclave.app.ui.motion.Fold import dev.conclave.app.ui.motion.Knot @@ -93,6 +95,7 @@ import dev.conclave.app.ui.motion.Steps import dev.conclave.app.ui.motion.Swap import dev.conclave.app.ui.theme.Conclave import dev.conclave.app.ui.theme.ConclaveType +import dev.conclave.client.logic.BlockRef import dev.conclave.client.logic.ChatLive import dev.conclave.client.logic.ChatSources import dev.conclave.client.logic.ChatTools @@ -112,6 +115,7 @@ import dev.conclave.client.model.ThinkingBlock import dev.conclave.client.model.ToolResultBlock import dev.conclave.client.model.plainText import dev.conclave.client.motion.KnotState +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.withContext @@ -219,7 +223,7 @@ fun UserBubble( val max = maxWidth * 0.85f Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.End) { images.forEach { img -> - val open = if (img.data.isNullOrBlank()) Modifier else Modifier.clickable(onClickLabel = "Open full screen") { shown = img } + val open = if (img.data.isNullOrBlank() && BlockRef.of(img.url) == null) Modifier else Modifier.clickable(onClickLabel = "Open full screen") { shown = img } Box(Modifier.padding(bottom = 6.dp).widthIn(max = max)) { ChatImage(img, maxHeight = 160.dp, modifier = open) } } files.forEach { name -> @@ -264,10 +268,11 @@ fun UserBubble( @Composable fun ChatImage(block: ImageBlock, maxHeight: Dp, modifier: Modifier = Modifier) { val c = Conclave.colors + val hub = LocalAppContainer.current.hub val data = block.data val target = with(LocalDensity.current) { (maxHeight * 2).roundToPx() } - val bitmap by produceState(null, data, target) { - value = if (data.isNullOrBlank()) null else withContext(Dispatchers.Default) { decodeScaled(data, target) } + val bitmap by produceState(null, block, target) { + value = withContext(Dispatchers.Default) { hub.imageData(block)?.let { decodeScaled(it, target) } } } val img = bitmap if (img != null) { @@ -277,7 +282,7 @@ fun ChatImage(block: ImageBlock, maxHeight: Dp, modifier: Modifier = Modifier) { contentScale = ContentScale.Fit, modifier = modifier.heightIn(max = maxHeight).clip(RoundedCornerShape(5.dp)).border(1.dp, c.rule, RoundedCornerShape(5.dp)), ) - } else if (data.isNullOrBlank()) { + } else if (data.isNullOrBlank() && BlockRef.of(block.url) == null) { Text("Image", style = ConclaveType.meta, color = c.fg3, modifier = modifier.border(1.dp, c.rule, RoundedCornerShape(5.dp)).padding(horizontal = 10.dp, vertical = 6.dp)) } } @@ -285,7 +290,10 @@ fun ChatImage(block: ImageBlock, maxHeight: Dp, modifier: Modifier = Modifier) { /** An image in a message, over everything and fitted to the screen: pinch to zoom, a tap, Back or Close shuts it. Save and Share sit at the bottom (FileCards.kt ImageActions); [name] names the saved file. */ @Composable internal fun FullImage(block: ImageBlock, name: String? = null, onDismiss: () -> Unit) { - val data = block.data + val hub = LocalAppContainer.current.hub + // one a trimmed page left out is read while the viewer is open, so Save and Share have its bytes + val fetched by produceState(block.data, block) { if (value.isNullOrBlank()) value = hub.imageData(block) } + val data = fetched Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) { BoxWithConstraints(Modifier.fillMaxSize().background(Color.Black).clickable(onClickLabel = "Close", onClick = onDismiss), contentAlignment = Alignment.Center) { val target = maxOf(constraints.maxWidth, constraints.maxHeight) @@ -314,11 +322,27 @@ internal fun FullImage(block: ImageBlock, name: String? = null, onDismiss: () -> IconButton(onClick = onDismiss, modifier = Modifier.align(Alignment.TopEnd).statusBarsPadding().padding(8.dp)) { Icon(Icons.Outlined.Close, contentDescription = "Close", tint = Color.White) } - if (bitmap != null) ImageActions(block, name, Modifier.align(Alignment.BottomCenter).navigationBarsPadding().padding(8.dp)) + if (bitmap != null) ImageActions(block.copy(data = data), name, Modifier.align(Alignment.BottomCenter).navigationBarsPadding().padding(8.dp)) } } } +/** An image's base64 to draw: its own, or for one a trimmed page left out (Trimmed.kt) read from the hub now. Null when neither or it fails. */ +internal suspend fun HubRepository.imageData(block: ImageBlock): String? = try { + blockData(block.data, block.url) +} catch (e: CancellationException) { + throw e +} catch (_: Exception) { + null +} + +/** A block's base64: [data], or the hub's copy when [url] is a trimmed page's ref (Trimmed.kt). Throws when the hub cannot say. */ +internal suspend fun HubRepository.blockData(data: String?, url: String?): String? { + data?.takeIf { it.isNotBlank() }?.let { return it } + val ref = BlockRef.of(url) ?: return null + return api { it.blockData(ref) } +} + /** A bitmap no more than about [target] px on its long side, or null when the data is not an image. */ internal fun decodeScaled(data: String, target: Int): ImageBitmap? = runCatching { java.util.Base64.getDecoder().decode(data) }.getOrNull()?.let { decodeScaled(it, target) } diff --git a/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/ToolFold.kt b/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/ToolFold.kt index bc5fdda4..14e0edc7 100644 --- a/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/ToolFold.kt +++ b/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/ToolFold.kt @@ -321,7 +321,7 @@ private fun Thumbnail.viewerItem(hub: HubRepository, sessionId: String?): Viewer if (shared && sessionId != null) { card.viewerItem(hub, sessionId) } else { - ViewerItem(card) { withContext(Dispatchers.Default) { java.util.Base64.getDecoder().decode(block?.data.orEmpty()) } } + ViewerItem(card) { withContext(Dispatchers.Default) { java.util.Base64.getDecoder().decode(block?.let { hub.imageData(it) }.orEmpty()) } } } /** @@ -353,7 +353,8 @@ private fun Thumb(t: Thumbnail, sessionId: String?, onClick: () -> Unit) { val bitmap by produceState(null, t.key, sessionId) { if (video) return@produceState val got = try { - val inline = t.block?.data + // a picture a trimmed page left out (Trimmed.kt) is read from the hub as it shows + val inline = t.block?.let { hub.imageData(it) } if (inline != null) { withContext(Dispatchers.Default) { decodeScaled(inline, target) } } else { diff --git a/packages/android/client/src/main/kotlin/dev/conclave/client/ConclaveClient.kt b/packages/android/client/src/main/kotlin/dev/conclave/client/ConclaveClient.kt index a7067551..c01900ef 100644 --- a/packages/android/client/src/main/kotlin/dev/conclave/client/ConclaveClient.kt +++ b/packages/android/client/src/main/kotlin/dev/conclave/client/ConclaveClient.kt @@ -6,7 +6,10 @@ import dev.conclave.client.model.ApprovalRequest import dev.conclave.client.model.ApprovalResponse import dev.conclave.client.model.AuditEntry import dev.conclave.client.model.BtwAnswer +import dev.conclave.client.logic.BlockRef +import dev.conclave.client.logic.Trimmed import dev.conclave.client.model.Checkpoint +import dev.conclave.client.model.ContentBlock import dev.conclave.client.model.CommandDef import dev.conclave.client.model.CommandResult import dev.conclave.client.model.ConfigResponse @@ -15,6 +18,7 @@ import dev.conclave.client.model.CreateSessionInput import dev.conclave.client.model.Device import dev.conclave.client.model.DevicePatch import dev.conclave.client.model.DiffResult +import dev.conclave.client.model.DocumentBlock import dev.conclave.client.model.ExportResult import dev.conclave.client.model.ExternalSessionInfo import dev.conclave.client.model.FileContent @@ -24,6 +28,7 @@ import dev.conclave.client.model.FolderPath import dev.conclave.client.model.GatewayKey import dev.conclave.client.model.HubIdentity import dev.conclave.client.model.HubInfo +import dev.conclave.client.model.ImageBlock import dev.conclave.client.model.IdentityProof import dev.conclave.client.model.LimitState import dev.conclave.client.model.LoginRequest @@ -76,6 +81,7 @@ import dev.conclave.client.model.Task import dev.conclave.client.model.TaskInput import dev.conclave.client.model.TaskStatus import dev.conclave.client.model.Todo +import dev.conclave.client.model.ToolResultBlock import dev.conclave.client.model.ToolInfo import dev.conclave.client.model.UsageRecord import dev.conclave.client.model.UsageSummary @@ -97,6 +103,7 @@ import kotlinx.serialization.builtins.ListSerializer import kotlinx.serialization.builtins.MapSerializer import kotlinx.serialization.builtins.serializer import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject @@ -521,8 +528,27 @@ class ConclaveClient( Session.serializer(), ) - suspend fun messages(id: String, afterSeq: Long? = null): List = - get(p("api", "sessions", id, "messages"), ListSerializer(Message.serializer()), mapOf("afterSeq" to afterSeq)) + /** + * The transcript, whole when no cursor or [limit] is given. [limit] without [afterSeq] is the newest page, + * [beforeSeq] the page before it. [trim]: blocks over 100 KB come light; their pictures get a [BlockRef] url (Trimmed.kt). + */ + suspend fun messages(id: String, afterSeq: Long? = null, beforeSeq: Long? = null, limit: Int? = null, trim: Boolean = false): List { + val list = get( + p("api", "sessions", id, "messages"), ListSerializer(Message.serializer()), + mapOf("afterSeq" to afterSeq, "beforeSeq" to beforeSeq, "limit" to limit, "trim" to if (trim) 1 else null), + ) + return if (trim) list.map(Trimmed::mark) else list + } + + /** The base64 of the picture or document [ref] names, read from the hub's block route; null when the block holds none. */ + suspend fun blockData(ref: BlockRef): String? { + val block = get(p("api", "sessions", ref.sessionId, "messages", ref.messageId, "blocks", ref.index.toString()), ContentBlock.serializer()) + if (block is ImageBlock) return block.data + if (block is DocumentBlock) return block.data + // a tool's picture: the hub's {data} or Anthropic's {source: {data}} (Media.toolImages) + val part = ((block as? ToolResultBlock)?.content as? JsonArray)?.getOrNull(ref.part ?: -1) as? JsonObject ?: return null + return ((part["data"] ?: (part["source"] as? JsonObject)?.get("data")) as? JsonPrimitive)?.contentOrNull + } suspend fun send(id: String, input: SendInput): SendResult = send("POST", p("api", "sessions", id, "messages"), SendInput.serializer(), input, SendResult.serializer()) diff --git a/packages/android/client/src/main/kotlin/dev/conclave/client/logic/Media.kt b/packages/android/client/src/main/kotlin/dev/conclave/client/logic/Media.kt index 3201fb1a..742e1f46 100644 --- a/packages/android/client/src/main/kotlin/dev/conclave/client/logic/Media.kt +++ b/packages/android/client/src/main/kotlin/dev/conclave/client/logic/Media.kt @@ -100,10 +100,13 @@ object Media { val o = el as? JsonObject ?: return@mapNotNull null if (o.str("type") != "image") return@mapNotNull null val src = o["source"] as? JsonObject - val data = (o.str("data") ?: src?.str("data"))?.takeIf { it.isNotBlank() } ?: return@mapNotNull null + val data = (o.str("data") ?: src?.str("data"))?.takeIf { it.isNotBlank() } + // a picture a trimmed page left out comes by its ref when it shows (Trimmed.kt) + val ref = o.str("url")?.takeIf { data == null && BlockRef.of(it) != null } + if (data == null && ref == null) return@mapNotNull null val type = o.str("mediaType") ?: src?.str("media_type") ?: src?.str("mediaType") ?: "image/png" if (FileCards.extension(type) == null) return@mapNotNull null - ImageBlock(mediaType = type, data = data) + ImageBlock(mediaType = type, data = data, url = ref) } } diff --git a/packages/android/client/src/main/kotlin/dev/conclave/client/logic/Transcript.kt b/packages/android/client/src/main/kotlin/dev/conclave/client/logic/Transcript.kt index 3e28cfbc..8b3a7397 100644 --- a/packages/android/client/src/main/kotlin/dev/conclave/client/logic/Transcript.kt +++ b/packages/android/client/src/main/kotlin/dev/conclave/client/logic/Transcript.kt @@ -37,6 +37,8 @@ data class Transcript( val sending: List = emptyList(), /** session.queue events applied, so a load never lays an older list over a newer one. */ val queueVersion: Int = 0, + /** The hub has messages before the first one held: scrolling to the top reads the page before it. */ + val older: Boolean = false, ) { val lastSeq: Long get() = messages.maxOfOrNull { it.seq } ?: 0L @@ -46,6 +48,19 @@ data class Transcript( object TranscriptReducer { + /** Messages a load or an older page reads at once (the web's store.ts PAGE): a big chat never comes whole. */ + const val PAGE = 200 + + /** A load: [paged] when it read the newest page (no cursor), which says whether older messages wait. */ + fun loaded(t: Transcript, fetched: List, paged: Boolean): Transcript = + merge(t, fetched).let { if (paged) it.copy(older = fetched.size >= PAGE) else it } + + /** The page before the first message held, laid in front of it. */ + fun olderPage(t: Transcript, page: List): Transcript = merge(t, page).copy(older = page.size >= PAGE) + + /** The seq the next older page reads before, or null when there is none to read. */ + fun olderBefore(t: Transcript): Long? = t.messages.firstOrNull()?.seq?.takeIf { t.older } + /** * Merge messages fetched over REST (initial load or after a reconnect). * A reply that ended here stays: a copy without a stop reason was read diff --git a/packages/android/client/src/main/kotlin/dev/conclave/client/logic/Trimmed.kt b/packages/android/client/src/main/kotlin/dev/conclave/client/logic/Trimmed.kt new file mode 100644 index 00000000..2fd4c16e --- /dev/null +++ b/packages/android/client/src/main/kotlin/dev/conclave/client/logic/Trimmed.kt @@ -0,0 +1,59 @@ +package dev.conclave.client.logic + +import dev.conclave.client.model.DocumentBlock +import dev.conclave.client.model.ImageBlock +import dev.conclave.client.model.Message +import dev.conclave.client.model.ToolResultBlock +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.intOrNull + +/** Where a picture or document a trimmed page left out lives: block [index] of message [messageId], part [part] of a tool result. */ +data class BlockRef(val sessionId: String, val messageId: String, val index: Int, val part: Int? = null) { + val url: String get() = SCHEME + listOfNotNull(sessionId, messageId, index, part).joinToString("/") + + companion object { + private const val SCHEME = "conclave-block:" + + /** The ref [url] names, or null for any other url (or none). */ + fun of(url: String?): BlockRef? { + val parts = url?.takeIf { it.startsWith(SCHEME) }?.removePrefix(SCHEME)?.split('/') ?: return null + if (parts.size !in 3..4) return null + val index = parts[2].toIntOrNull() ?: return null + return BlockRef(parts[0], parts[1], index, parts.getOrNull(3)?.toIntOrNull()) + } + } +} + +/** + * A transcript page read with trim=1 (hub core session/trim.ts): a block over + * 100 KB comes without its image or document data, listed in meta.trimmed. + * Each picture or document it cut gets a [BlockRef] url, so the screen + * fetches that one block (GET .../messages/:id/blocks/:index) only when it + * shows or is sent again, and a big chat never holds every screenshot's + * base64 at once. Cut text stays cut. + */ +object Trimmed { + + fun mark(m: Message): Message { + val cut = (m.meta?.get("trimmed") as? JsonArray) + ?.mapNotNull { ((it as? JsonObject)?.get("index") as? JsonPrimitive)?.intOrNull }?.toSet() + if (cut.isNullOrEmpty()) return m + val sid = m.sessionId + return m.copy(content = m.content.mapIndexed { i, b -> + when { + i !in cut -> b + b is ImageBlock && b.data == null && b.url == null -> b.copy(url = BlockRef(sid, m.id, i).url) + b is DocumentBlock && b.data == null && b.url == null -> b.copy(url = BlockRef(sid, m.id, i).url) + b is ToolResultBlock && b.content is JsonArray -> b.copy(content = JsonArray(b.content.mapIndexed { k, part -> + val o = part as? JsonObject + if (o != null && (o["type"] as? JsonPrimitive)?.content == "image" && o["data"] == null && o["url"] == null) { + JsonObject(o + ("url" to JsonPrimitive(BlockRef(sid, m.id, i, k).url))) + } else part + })) + else -> b + } + }) + } +} diff --git a/packages/android/client/src/test/kotlin/dev/conclave/client/PagingTest.kt b/packages/android/client/src/test/kotlin/dev/conclave/client/PagingTest.kt new file mode 100644 index 00000000..a425af4a --- /dev/null +++ b/packages/android/client/src/test/kotlin/dev/conclave/client/PagingTest.kt @@ -0,0 +1,138 @@ +package dev.conclave.client + +import dev.conclave.client.logic.BlockRef +import dev.conclave.client.logic.Media +import dev.conclave.client.logic.Transcript +import dev.conclave.client.logic.TranscriptReducer +import dev.conclave.client.model.ImageBlock +import dev.conclave.client.model.Message +import dev.conclave.client.model.Role +import dev.conclave.client.model.TextBlock +import dev.conclave.client.model.ToolResultBlock +import kotlinx.coroutines.runBlocking +import mockwebserver3.MockResponse +import mockwebserver3.MockWebServer +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * A big chat on Android (a 90 MB transcript of screenshots ended the app): + * the newest page comes light (trim=1), older pages come on scroll with + * beforeSeq, and a picture the page left out is read from its block only + * when it shows. The same paged API as the web (store.ts PAGE, loadOlder). + */ +class PagingTest { + private lateinit var server: MockWebServer + + @BeforeTest + fun setUp() { + server = MockWebServer() + server.start() + } + + @AfterTest + fun tearDown() { + server.close() + } + + private fun client() = ConclaveClient(server.url("/").toString(), "t") + + private fun msg(seq: Long) = Message(id = "m$seq", sessionId = "s1", seq = seq, role = Role.USER, content = listOf(TextBlock("$seq"))) + + @Test + fun readsTheNewestPageLightAndMarksWhatItCut() = runBlocking { + server.enqueue(MockResponse(body = """[ + {"id":"m1","sessionId":"s1","seq":1,"role":"user","content":[{"type":"text","text":"hi"},{"type":"image","mediaType":"image/png"}],"meta":{"trimmed":[{"index":1,"bytes":4000000}]}}, + {"id":"m2","sessionId":"s1","seq":2,"role":"user","content":[{"type":"tool_result","toolUseId":"t1","content":[{"type":"text","text":"shot"},{"type":"image","mediaType":"image/png"}]}],"meta":{"trimmed":[{"index":0,"bytes":5000000}]}}, + {"id":"m3","sessionId":"s1","seq":3,"role":"user","content":[{"type":"image","mediaType":"image/png","data":"AAAA"}]} + ]""")) + val list = client().messages("s1", limit = TranscriptReducer.PAGE, trim = true) + val url = server.takeRequest().url + assertEquals("/api/sessions/s1/messages", url.encodedPath) + assertEquals("200", url.queryParameter("limit")) + assertEquals("1", url.queryParameter("trim")) + assertNull(url.queryParameter("afterSeq")) + + // a cut picture names its block; a small one keeps its data and gets no ref + val img = list[0].content[1] as ImageBlock + assertEquals(BlockRef("s1", "m1", 1), BlockRef.of(img.url)) + assertEquals("AAAA", (list[2].content[0] as ImageBlock).data) + assertNull((list[2].content[0] as ImageBlock).url) + + // a tool's picture names its part, and still shows as a thumbnail + val shots = Media.toolImages(list[1].content[0] as ToolResultBlock) + assertEquals(1, shots.size) + assertNull(shots[0].data) + assertEquals(BlockRef("s1", "m2", 0, 1), BlockRef.of(shots[0].url)) + } + + @Test + fun aWholeReadStaysAsItWas() = runBlocking { + server.enqueue(MockResponse(body = """[{"id":"m1","sessionId":"s1","seq":1,"role":"user","content":[]}]""")) + client().messages("s1", afterSeq = 7) + val url = server.takeRequest().url + assertEquals("7", url.queryParameter("afterSeq")) + assertNull(url.queryParameter("limit")) + assertNull(url.queryParameter("trim")) + assertNull(url.queryParameter("beforeSeq")) + } + + @Test + fun readsACutPictureFromItsBlock() = runBlocking { + server.enqueue(MockResponse(body = """{"type":"image","mediaType":"image/png","data":"QUJD"}""")) + assertEquals("QUJD", client().blockData(BlockRef("s1", "m1", 1))) + assertEquals("/api/sessions/s1/messages/m1/blocks/1", server.takeRequest().url.encodedPath) + + server.enqueue(MockResponse(body = """{"type":"tool_result","toolUseId":"t1","content":[{"type":"text","text":"shot"},{"type":"image","mediaType":"image/png","data":"WFla"}]}""")) + assertEquals("WFla", client().blockData(BlockRef("s1", "m2", 0, 1))) + assertEquals("/api/sessions/s1/messages/m2/blocks/0", server.takeRequest().url.encodedPath) + } + + @Test + fun refsRoundTripAndOtherUrlsAreNotRefs() { + val ref = BlockRef("ses_0mwubt3145w1mp4ql0k", "msg_1", 3, 2) + assertEquals(ref, BlockRef.of(ref.url)) + assertEquals(BlockRef("s", "m", 0), BlockRef.of(BlockRef("s", "m", 0).url)) + assertNull(BlockRef.of("https://example.com/a.png")) + assertNull(BlockRef.of(null)) + assertNull(BlockRef.of("conclave-block:s/m/x")) + } + + @Test + fun pagesBackToTheStart() { + // a full newest page: older messages wait, read before the first one held + val newest = (101L..300L).map(::msg) + var t = TranscriptReducer.loaded(Transcript("s1"), newest, paged = true) + assertTrue(t.older) + assertEquals(101L, TranscriptReducer.olderBefore(t)) + + // a short older page: the start, and nothing more to read + t = TranscriptReducer.olderPage(t, (1L..100L).map(::msg)) + assertFalse(t.older) + assertNull(TranscriptReducer.olderBefore(t)) + assertEquals((1L..300L).toList(), t.messages.map { it.seq }) + } + + @Test + fun aFullOlderPageKeepsGoingAndAShortChatHasNone() { + var t = TranscriptReducer.loaded(Transcript("s1"), (401L..600L).map(::msg), paged = true) + t = TranscriptReducer.olderPage(t, (201L..400L).map(::msg)) + assertTrue(t.older) + assertEquals(201L, TranscriptReducer.olderBefore(t)) + + // a chat shorter than a page is whole at once + val short = TranscriptReducer.loaded(Transcript("s1"), (1L..5L).map(::msg), paged = true) + assertFalse(short.older) + assertNull(TranscriptReducer.olderBefore(short)) + + // a reload after a reconnect (afterSeq) leaves what the paging knew + val again = TranscriptReducer.loaded(t, listOf(msg(601)), paged = false) + assertTrue(again.older) + assertEquals(601L, again.lastSeq) + } +}