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 @@ -2,6 +2,7 @@ package dev.opencode.mobile.data.remote.dto

import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.descriptors.PrimitiveKind
Expand Down Expand Up @@ -64,6 +65,7 @@ data class RunCommandRequestDto(
val model: String? = null,
val variant: String? = null,
val parts: List<CommandFilePartDto> = emptyList(),
@SerialName("messageID") val messageId: String? = null,
)

@Serializable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ data class SendMessageRequestDto(
val model: SendPromptModelDto? = null,
val variant: String? = null,
val agent: String? = null,
@SerialName("messageID") val messageId: String? = null,
)

@Serializable
Expand Down Expand Up @@ -189,6 +190,7 @@ data class AgentPartSourceDto(

@Serializable
data class V2PromptRequestDto(
val id: String? = null,
val text: String,
val files: List<V2PromptFileDto>? = null,
val agents: List<V2PromptAgentDto>? = null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ class CommandDomainAdapter {
filename = attachment.filename,
)
},
messageId = options.messageId,
)

fun toV2RunRequest(options: CommandRunOptions): V2RunCommandRequestDto =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ data class CommandRunOptions(
val delivery: FollowUpDelivery = FollowUpDelivery.Steer,
/** v2 skills mentioned in the draft; the command route carries them as `skills: [{id}]`. */
val skillIds: List<String> = emptyList(),
/** [ClientMessageId] for the user message. v1 keeps it; v2 commands take no id. */
val messageId: String? = null,
)

sealed class ComposerSubmitIntent {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ data class ServerCapabilities(
val supportsSessionViewed: Boolean = false,
/** Server moves a session to another worktree (`POST /api/session/{id}/move`, v2). */
val supportsSessionMove: Boolean = false,
/** The command route keeps a client message id (v1 `messageID`); v2 `…/command` takes none. */
val commandKeepsClientMessageId: Boolean = false,
) {
companion object {
fun forProtocol(
Expand All @@ -48,6 +50,7 @@ data class ServerCapabilities(
supportsSessionArchive = true,
supportsFollowUpDelivery = false,
supportsSessionViewed = false,
commandKeepsClientMessageId = true,
)
ServerProtocol.V2 ->
ServerCapabilities(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package dev.opencode.mobile.domain.message

import java.security.SecureRandom
import kotlin.random.Random
import kotlin.random.asKotlinRandom

/**
* Client-made user message ids, built like opencode's own ascending ids so v1 and v2
* accept them: `msg_`, 12 hex characters for the low 48 bits of `epochMillis * 4096 +
* counter`, then 14 base62 characters. A prompt sent with one comes back under the same id, so the
* optimistic row retires on its echo however the server reshapes the text.
*/
object ClientMessageId {
private const val PREFIX = "msg_"
private const val RANDOM_LENGTH = 14
private const val TIME_MASK = 0xFFFF_FFFF_FFFFL
private const val BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

private val secureRandom = SecureRandom().asKotlinRandom()
private var lastTimestamp = 0L
private var counter = 0L

@Synchronized
fun next(
nowMs: Long = System.currentTimeMillis(),
random: Random = secureRandom,
): String {
if (nowMs != lastTimestamp) {
lastTimestamp = nowMs
counter = 0
}
counter++
val time = ((nowMs * 0x1000L + counter) and TIME_MASK).toString(16).padStart(12, '0')
val suffix = buildString { repeat(RANDOM_LENGTH) { append(BASE62[random.nextInt(BASE62.length)]) } }
return PREFIX + time + suffix
}

/** True for an optimistic row whose send carried its id, so only that id retires it. */
fun isClientId(id: String): Boolean = id.startsWith(PREFIX)
}
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,8 @@ data class PromptSendOptions(
/** v2 only: inline skill spans, sent as `skills: [{id, mention}]`. */
val skillMentions: List<SkillMention> = emptyList(),
val delivery: FollowUpDelivery = FollowUpDelivery.Steer,
/** [ClientMessageId] the server gives the user message it creates. */
val messageId: String? = null,
)

data class PromptModelSelection(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ class MessageDomainAdapter {
model = options.model?.let { SendPromptModelDto(providerId = it.providerId, modelId = it.modelId) },
variant = options.variant,
agent = options.mode,
messageId = options.messageId,
)

fun toV1ShellRequest(options: ShellCommandOptions): V1ShellRequestDto =
Expand Down Expand Up @@ -293,6 +294,7 @@ class MessageDomainAdapter {
}.takeIf { it.isNotEmpty() }
val fileMentions = v2FileMentions(options)
return V2PromptRequestDto(
id = options.messageId,
text = options.text,
files = files,
agents = agents,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ object PromptJsonBodyWriter {
writer.key("agent")
writer.writeString(it)
}
body.messageId?.let {
writer.key("messageID")
writer.writeString(it)
}
writer.endObject()
}

Expand All @@ -113,6 +117,10 @@ object PromptJsonBodyWriter {
): File =
write(directory) { writer ->
writer.beginObject()
body.id?.let {
writer.key("id")
writer.writeString(it)
}
writer.key("text")
writer.writeString(body.text)
val mentionFiles = body.fileMentions.orEmpty()
Expand Down Expand Up @@ -231,6 +239,10 @@ object PromptJsonBodyWriter {
}
writer.endArray()
}
body.messageId?.let {
writer.key("messageID")
writer.writeString(it)
}
writer.endObject()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1367,11 +1367,13 @@ class SessionChatViewModel
val sessionId = boundSessionId ?: return
val worktree = boundWorktree ?: return
val shouldQueue = !sessionInfo.state.value.canMutate
val capabilities = activeConnectionManager.currentCapabilities()
composer.sendPrompt(
sessionId = sessionId,
worktree = worktree,
isSessionBusy = sessionInfo.state.value.sessionStatusLabel != null,
supportsFollowUp = activeConnectionManager.currentCapabilities().supportsFollowUpDelivery,
supportsFollowUp = capabilities.supportsFollowUpDelivery,
commandKeepsClientMessageId = capabilities.commandKeepsClientMessageId,
holdUntil = {
if (!shouldQueue) {
true
Expand Down Expand Up @@ -2264,8 +2266,8 @@ class SessionChatViewModel
/**
* Union of server inbox rows and still-unmerged optimistic busy sends.
* [optimistic] must already be the merge leftover (echo dropped the matching
* optimistic row, often under a different id). This function only skips
* optimistic ids that are already in [loaded].
* optimistic row). This function only skips optimistic ids that are already in
* [loaded], as a client-id send's inbox echo is.
*/
internal fun pendingPromptsFrom(
loaded: List<Message>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import dev.opencode.mobile.domain.event.ForegroundEventStream
import dev.opencode.mobile.domain.message.Attachment
import dev.opencode.mobile.domain.message.AttachmentKind
import dev.opencode.mobile.domain.message.AttachmentLimits
import dev.opencode.mobile.domain.message.ClientMessageId
import dev.opencode.mobile.domain.message.FollowUpDelivery
import dev.opencode.mobile.domain.message.MessageError
import dev.opencode.mobile.domain.message.MessageRepository
Expand Down Expand Up @@ -988,6 +989,7 @@ class SessionChatComposer(
onSendFailed: (optimisticId: String, error: String) -> Unit,
isSessionBusy: Boolean,
supportsFollowUp: Boolean,
commandKeepsClientMessageId: Boolean = false,
holdUntil: suspend () -> Boolean = { true },
serverAlreadyAccepted: () -> Boolean = { false },
beforePrompt: suspend () -> Unit = {},
Expand Down Expand Up @@ -1035,11 +1037,22 @@ class SessionChatComposer(
commands = _state.value.serverCommands,
)
val displayText = collapsedDisplay?.text ?: prompt
val intent =
ComposerSubmitRouting.resolve(
text = prompt,
commands = _state.value.serverCommands,
)
// The echo of a send that carries its id comes back under it. v2 commands take
// no id, so their row keeps a local id and retires on text instead.
val messageId =
ClientMessageId.next().takeIf {
intent !is ComposerSubmitIntent.ServerCommand || commandKeepsClientMessageId
}
scope.launch {
val display =
withContext(ioDispatcher) {
messageRepository.prepareOptimisticUserMessage(
id = "pending-${UUID.randomUUID()}",
id = messageId ?: "pending-${UUID.randomUUID()}",
text = displayText,
attachments = attachments,
)
Expand Down Expand Up @@ -1111,11 +1124,6 @@ class SessionChatComposer(
onSendFailed(display.id, PENDING_SEND_TIMEOUT_ERROR)
return@launch
}
val intent =
ComposerSubmitRouting.resolve(
text = prompt,
commands = _state.value.serverCommands,
)
val hasAttachments = attachments.isNotEmpty()
val progress =
PromptSendProgressReporter { sent, total ->
Expand Down Expand Up @@ -1148,6 +1156,7 @@ class SessionChatComposer(
worktree = worktree,
skillMentions = skillMentions,
delivery = delivery,
messageId = messageId,
),
directory = worktree,
)
Expand Down Expand Up @@ -1196,6 +1205,7 @@ class SessionChatComposer(
.skillParts(prompt, skillsForSend)
.map { it.skillId }
.distinct(),
messageId = messageId,
),
directory = worktree,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ class SessionChatTimeline(
private var pendingLiveDisplayApply: PendingDisplayApply? = null
private var mergePendingWhileSending = false
private var pendingOptimisticRows: List<SessionChatMessageItem> = emptyList()
private var pendingBaselineSignatures: Map<String, String> = emptyMap()
private var pendingBaselineIds: Set<String> = emptySet()
private var lastLoadedMessages: List<Message> = emptyList()
private var lastLoadedDisplayMessages: List<DisplayMessage> = emptyList()
private val pendingPromptPatches = mutableMapOf<String, PendingPromptPatch>()
Expand All @@ -211,7 +211,7 @@ class SessionChatTimeline(
boundWorktree = worktree
mergePendingWhileSending = false
pendingOptimisticRows = emptyList()
pendingBaselineSignatures = emptyMap()
pendingBaselineIds = emptySet()
lastLoadedMessages = emptyList()
lastLoadedDisplayMessages = emptyList()
resetChildSessionLookup()
Expand Down Expand Up @@ -248,7 +248,7 @@ class SessionChatTimeline(
boundWorktree = worktree
mergePendingWhileSending = false
pendingOptimisticRows = emptyList()
pendingBaselineSignatures = emptyMap()
pendingBaselineIds = emptySet()
lastLoadedMessages = emptyList()
lastLoadedDisplayMessages = emptyList()
resetChildSessionLookup()
Expand Down Expand Up @@ -397,8 +397,7 @@ class SessionChatTimeline(
fun beginOptimisticSend(enrichedRows: List<SessionChatMessageItem>) {
mergePendingWhileSending = true
pendingOptimisticRows = enrichedRows
pendingBaselineSignatures =
TimelineProjector.reconciliationSignaturesById(lastLoadedServerRows())
pendingBaselineIds = lastLoadedServerRows().mapTo(HashSet()) { it.id }
val displayedItems = TimelineProjector.displayedOptimisticSendItems(enrichedRows)
val displayedRows = displayedItems.map(TimelineProjector::rowFromMessageItem)
val previous = lastTimelineFrame
Expand Down Expand Up @@ -467,25 +466,26 @@ class SessionChatTimeline(
) {
mergePendingWhileSending = false
pendingOptimisticRows = emptyList()
pendingBaselineSignatures = emptyMap()
pendingBaselineIds = emptySet()
val previous = lastTimelineFrame
val frame =
previous?.let { prior ->
val rows = prior.rows.filterNot { it.id == optimisticId }
// An echo already shown under the same client id stays: the server has it.
val rows = prior.rows.filterNot { it.id == optimisticId && it.isPending }
TimelineFrame(
frameRevision = nextFrameRevision++,
rows = rows,
insertedRowIDs = emptySet(),
changedRowIDs = emptySet(),
removedRowIDs = setOf(optimisticId).intersect(prior.rows.map { it.id }.toSet()),
removedRowIDs = (prior.rows.map { it.id }.toSet() - rows.map { it.id }.toSet()),
layoutChangedRowIDs = emptySet(),
listIdAliases = prior.listIdAliases,
)
}
lastTimelineFrame = frame
_state.update {
it.copy(
messages = it.messages.filterNot { item -> item.id == optimisticId },
messages = it.messages.filterNot { item -> item.id == optimisticId && item.isPending },
timelineFrame = frame,
errorMessage = error,
)
Expand All @@ -495,7 +495,7 @@ class SessionChatTimeline(
fun clearSendingState() {
mergePendingWhileSending = false
pendingOptimisticRows = emptyList()
pendingBaselineSignatures = emptyMap()
pendingBaselineIds = emptySet()
}

fun clearReadyError() {
Expand Down Expand Up @@ -781,7 +781,7 @@ class SessionChatTimeline(
pendingOptimisticRows.ifEmpty { stateSnapshot.messages.filter { it.isPending } }
OptimisticInputs(
pendingRows = pendingItems.map(TimelineProjector::rowFromMessageItem),
baselineSignatures = pendingBaselineSignatures,
baselineIds = pendingBaselineIds,
)
} else {
OptimisticInputs()
Expand Down Expand Up @@ -904,7 +904,7 @@ class SessionChatTimeline(
private fun applyLoadError(throwable: Throwable) {
mergePendingWhileSending = false
pendingOptimisticRows = emptyList()
pendingBaselineSignatures = emptyMap()
pendingBaselineIds = emptySet()
// Retain the last good timeline when one exists; only clear on cold failure.
_state.update { current ->
val retainLastGood = current.messages.isNotEmpty()
Expand All @@ -925,28 +925,28 @@ class SessionChatTimeline(
* reconciliation cannot use displayed ids. An optimistic send is done when
* every pending item has a new server echo relative to the send-time
* baseline — the same match [TimelineProjector] uses to drop the optimistic
* row, often under a different id.
* row.
*/
private fun clearOptimisticIfReconciled() {
if (!mergePendingWhileSending) return
val pendingItems = pendingOptimisticItems()
if (pendingItems.isEmpty()) {
mergePendingWhileSending = false
pendingOptimisticRows = emptyList()
pendingBaselineSignatures = emptyMap()
pendingBaselineIds = emptySet()
return
}
val stillUnacked =
TimelineProjector
.unmatchedPending(
pendingRows = pendingItems.map(TimelineProjector::rowFromMessageItem),
serverRows = lastLoadedServerRows(),
baselineSignatures = pendingBaselineSignatures,
baselineIds = pendingBaselineIds,
).isNotEmpty()
if (stillUnacked) return
mergePendingWhileSending = false
pendingOptimisticRows = emptyList()
pendingBaselineSignatures = emptyMap()
pendingBaselineIds = emptySet()
}

private fun lastLoadedServerRows(): List<TimelineRow> =
Expand Down
Loading
Loading