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 @@ -12,6 +12,8 @@ data class V2SessionMessageDto(
val text: String? = null,
val files: List<V2FileAttachmentDto> = emptyList(),
val agents: List<V2AgentAttachmentDto> = emptyList(),
/** Skills admitted on a `user` prompt. The body is model-facing and not decoded. */
val skills: List<V2UserSkillDto> = emptyList(),
val agent: String? = null,
val model: V2ModelRefDto? = null,
val content: List<V2AssistantContentDto> = emptyList(),
Expand Down Expand Up @@ -93,6 +95,13 @@ data class V2FileSourceDto(
val text: String? = null,
)

@Serializable
data class V2UserSkillDto(
val id: String? = null,
val name: String? = null,
val mention: V2PromptSourceDto? = null,
)

@Serializable
data class V2AgentAttachmentDto(
val name: String? = null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull

/**
* A skill admitted on a v2 user prompt. The skill body stays on the server;
* chat only needs the id and slash name so the prompt can show as `[/name]`.
*/
data class PromptSkill(
val id: String,
val name: String,
/** Mention text already present in the prompt, when another client recorded one. */
val mentionText: String? = null,
)

data class Message(
val id: String,
val role: MessageRole,
Expand All @@ -29,6 +40,8 @@ data class Message(
val stopReason: MessageStopReason? = null,
/** A run failure to show under the reply. Null when the run did not fail, or the user stopped it. */
val failure: SessionFailure? = null,
/** Skills admitted with this prompt. Empty for v1 and for messages that did not load a skill. */
val promptSkills: List<PromptSkill> = emptyList(),
)

/** An assistant reply that ended before the model finished its answer. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,7 @@ class MessageDomainAdapter {
id = dto.id,
role = MessageRole.User,
parts = parts,
promptSkills = promptSkills(dto),
mode = dto.agent ?: agent.ifBlank { null },
model = dto.model ?: model,
sentAtEpochMs = dto.time?.created,
Expand Down Expand Up @@ -686,6 +687,7 @@ class MessageDomainAdapter {
role: MessageRole,
parts: List<MessagePart>,
fallbackText: String = "",
promptSkills: List<PromptSkill> = emptyList(),
cost: Double? = null,
tokens: MessageTokenUsage? = null,
mode: String? = null,
Expand All @@ -705,6 +707,7 @@ class MessageDomainAdapter {
failure = failure,
text = flatText.ifBlank { fallbackText },
parts = parts,
promptSkills = promptSkills,
cost = cost,
tokens = tokens,
model = model?.id,
Expand All @@ -719,6 +722,22 @@ class MessageDomainAdapter {
)
}

/**
* Skills ride on the user message. Keep id and name only — `text` is the
* model-facing skill body and must not become a second chat bubble.
*/
private fun promptSkills(dto: V2SessionMessageDto): List<PromptSkill> =
dto.skills.mapNotNull { skill ->
val id = skill.id?.trim().orEmpty().ifEmpty { skill.name?.trim().orEmpty() }
val name = skill.name?.trim().orEmpty().ifEmpty { id }
if (name.isEmpty()) return@mapNotNull null
PromptSkill(
id = id.ifEmpty { name },
name = name,
mentionText = skill.mention?.text?.trim()?.takeIf { it.isNotEmpty() },
)
}

private fun toV2AssistantPart(
content: V2AssistantContentDto,
fallbackId: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1120,20 +1120,13 @@ class SessionChatTimeline(
message = message,
isStreaming = display.isStreaming,
blocks =
SessionChatTimelineBlocks.collapseCommandInvocations(
role = message.role,
blocks =
SessionChatTimelineBlocks.buildOrFallback(
role = message.role,
parts = message.parts,
messageId = message.id,
fallbackText = message.text,
collapseConsecutiveToolCalls = collapseConsecutiveToolCalls,
chipTimeline = chipTimeline,
stepRail = stepRailTimeline,
activityCard = activityCardTimeline,
),
SessionChatTimelineBlocks.present(
message = message,
commands = serverCommands,
collapseConsecutiveToolCalls = collapseConsecutiveToolCalls,
chipTimeline = chipTimeline,
stepRail = stepRailTimeline,
activityCard = activityCardTimeline,
),
)
if (resolvedBlocks.isEmpty() && message.failure == null) return null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import dev.opencode.mobile.domain.message.FailureAction
import dev.opencode.mobile.domain.message.Message
import dev.opencode.mobile.domain.message.MessagePart
import dev.opencode.mobile.domain.message.MessageRole
import dev.opencode.mobile.domain.message.PromptSkill
import dev.opencode.mobile.domain.message.MessageStopReason
import dev.opencode.mobile.domain.message.ThoughtPartChrome
import dev.opencode.mobile.domain.message.TimelineNotice
Expand Down Expand Up @@ -1510,6 +1511,120 @@ object SessionChatTimelineBlocks {
-> false
}

/**
* Builds the blocks Session Chat shows for one message: part blocks, then
* the slash token for a skill admitted beside the user's text, then
* template collapse. Skill admission has to happen before collapse so a
* skill-plus-image send displays as one `[/name] args` row and matches the
* optimistic send instead of leaving a second copy of the image.
*/
fun present(
message: Message,
commands: List<ServerCommand>,
collapseConsecutiveToolCalls: Boolean = false,
chipTimeline: Boolean = false,
stepRail: Boolean = false,
activityCard: Boolean = false,
): List<SessionChatTimelineBlock> {
val built =
buildOrFallback(
role = message.role,
parts = message.parts,
messageId = message.id,
fallbackText = message.text,
collapseConsecutiveToolCalls = collapseConsecutiveToolCalls,
chipTimeline = chipTimeline,
stepRail = stepRail,
activityCard = activityCard,
)
return collapseCommandInvocations(
role = message.role,
blocks = admitPromptSkills(message.role, built, message.promptSkills, commands),
commands = commands,
)
}

/**
* A v2 skill prompt stores the user's arguments as the message text and the
* skill beside it. Restore `/name` so collapse can show `[/name] args` on
* that same row. Skip when the text is already a slash invocation or an
* expanded template — prefixing those would hide the command collapse.
*/
fun admitPromptSkills(
role: MessageRole,
blocks: List<SessionChatTimelineBlock>,
skills: List<PromptSkill>,
commands: List<ServerCommand>,
): List<SessionChatTimelineBlock> {
if (role != MessageRole.User || skills.isEmpty()) return blocks
val names = skills.mapNotNull { slashName(it, commands) }.distinct()
if (names.isEmpty()) return blocks
val textIndex = blocks.indexOfFirst { it is SessionChatTimelineBlock.Text }
val existing = (blocks.getOrNull(textIndex) as? SessionChatTimelineBlock.Text)?.text.orEmpty()
if (existing.isNotBlank() && CommandInvocationCollapser.collapse(existing, commands) != null) {
return blocks
}
val missing = names.filter { name -> !alreadyAdmitted(existing, name, skills) }
if (missing.isEmpty()) return blocks
val prefix = missing.joinToString(" ") { "/$it" }
val nextText = if (existing.isBlank()) prefix else "$prefix ${existing.trimStart()}"
if (textIndex >= 0) {
return blocks.mapIndexed { index, block ->
if (index != textIndex || block !is SessionChatTimelineBlock.Text) {
block
} else {
block.copy(text = nextText, renderedMarkdown = null)
}
}
}
val inserted =
SessionChatTimelineBlock.Text(
blockID = PresentationBlockId.direct("prompt-skill:${names.first()}"),
text = prefix,
)
return listOf(inserted) + blocks
}

private fun slashName(
skill: PromptSkill,
commands: List<ServerCommand>,
): String? {
val id = skill.id.trim()
val name = skill.name.trim()
val fromCatalog =
commands
.firstOrNull { command ->
val skillId = command.skillId?.trim().orEmpty()
skillId.isNotEmpty() && (skillId == id || skillId == name)
}?.name
?: commands.firstOrNull { it.name == name || (id.isNotEmpty() && it.name == id) }?.name
val resolved = fromCatalog?.trim().orEmpty().ifEmpty { name.ifEmpty { id } }
return resolved.takeIf { it.isNotEmpty() }
}

private fun alreadyAdmitted(
text: String,
name: String,
skills: List<PromptSkill>,
): Boolean {
val trimmed = text.trim()
if (trimmed.startsWith("[/$name]") || startsWithSlashToken(trimmed, name)) return true
return skills.any { skill ->
val mention = skill.mentionText?.trim().orEmpty()
mention.isNotEmpty() && text.contains(mention) &&
(skill.name == name || skill.id == name)
}
}

private fun startsWithSlashToken(
text: String,
name: String,
): Boolean {
val token = "/$name"
if (!text.startsWith(token)) return false
return text.length == token.length || text[token.length].isWhitespace()
}

/**
* Rewrites user text blocks that are expanded slash-command / skill
* templates into `[/name] args` for Session Chat display.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1568,6 +1568,37 @@ class MessageDomainAdapterTest {
assertEquals(1, adapter.projectV2(dtos).size)
}

@Test
fun projectV2_userSkillAndFile_keepsArgumentsAndSkillRefWithoutSkillBody() {
val message =
projectV2(
"""
[
{
"id":"msg_user",
"type":"user",
"text":"prototype me a better list item",
"files":[{"name":"16136.png","mime":"image/png","uri":"data:image/png;base64,YQ=="}],
"skills":[{
"id":"publish-prototype",
"name":"publish-prototype",
"text":"SKILL BODY should stay off the transcript"
}]
}
]
""",
).single()

assertEquals("prototype me a better list item", message.text)
assertFalse(message.text.contains("SKILL BODY"))
assertFalse(message.parts.any { it is MessagePart.Text && it.text.contains("SKILL BODY") })
assertEquals(
listOf(PromptSkill(id = "publish-prototype", name = "publish-prototype")),
message.promptSkills,
)
assertEquals(1, message.parts.filterIsInstance<MessagePart.File>().size)
}

@Test
fun mergeInbox_emptyInboxIsNoOp() {
val messages = listOf(Message(id = "msg-1", role = MessageRole.User, text = "Hello"))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package dev.opencode.mobile.ui.sessionchat

import dev.opencode.mobile.domain.command.ServerCommand
import dev.opencode.mobile.domain.command.ServerCommandSource
import dev.opencode.mobile.domain.message.AttachmentKind
import dev.opencode.mobile.domain.message.DisplayMessage
import dev.opencode.mobile.domain.message.FollowUpDelivery
import dev.opencode.mobile.domain.message.Message
import dev.opencode.mobile.domain.message.MessagePart
import dev.opencode.mobile.domain.message.MessageRole
import dev.opencode.mobile.domain.message.PromptSkill
import dev.opencode.mobile.domain.message.ToolStatus
import dev.opencode.mobile.markdown.MarkdownDocument
import dev.opencode.mobile.ui.components.OpenCodeAttachmentVariant
Expand Down Expand Up @@ -385,6 +388,90 @@ class TimelineProjectorTest {
assertEquals(setOf("optimistic-photo"), reconciled.removedRowIDs)
}

@Test
fun project_skillPromptWithImage_collapsesOntoOneRowAndDropsOptimisticCopy() {
val args = "prototype me a better list item"
val collapsed = "[/publish-prototype] $args"
val message =
Message(
id = "msg-user",
role = MessageRole.User,
text = args,
parts =
listOf(
MessagePart.Text(text = args, id = "u1"),
MessagePart.File(
id = "server-file",
filename = "16136.png",
mime = "image/png",
kind = AttachmentKind.Image,
dataUrl = "",
),
),
promptSkills = listOf(PromptSkill(id = "publish-prototype", name = "publish-prototype")),
)
val blocks =
SessionChatTimelineBlocks.present(
message = message,
commands =
listOf(
ServerCommand(
name = "publish-prototype",
source = ServerCommandSource.Skill,
skillId = "publish-prototype",
),
),
)
assertEquals(listOf(collapsed), blocks.filterIsInstance<SessionChatTimelineBlock.Text>().map { it.text })
assertEquals(1, blocks.filterIsInstance<SessionChatTimelineBlock.Attachment>().size)

val pendingAttachment =
SessionChatAttachmentItem(
id = "local-file",
filename = "16136.png",
variant = OpenCodeAttachmentVariant.Image,
signature = "local",
)
val pending =
TimelineProjector.rowFromMessageItem(
SessionChatMessageItem(
id = "optimistic",
role = MessageRole.User,
text = collapsed,
metadataLabel = "Build · 12:48 AM",
isPending = true,
blocks =
listOf(
SessionChatTimelineBlock.Text(
blockID = PresentationBlockId.messageFallback("optimistic"),
text = collapsed,
),
SessionChatTimelineBlock.Attachment(
blockID = PresentationBlockId.direct("local-file"),
attachment = pendingAttachment,
),
),
attachments = listOf(pendingAttachment),
),
)
val reconciled =
TimelineProjector.project(
frame =
DisplayFrame(
sessionKey = "session",
frameRevision = 1L,
sourceRevision = 0L,
messages = listOf(DisplayMessageBody(message = message, blocks = blocks)),
),
optimisticInputs = OptimisticInputs(pendingRows = listOf(pending)),
)

assertEquals(listOf("msg-user"), reconciled.rows.map { it.id })
assertEquals(collapsed, reconciled.rows.single().text)
assertEquals(1, reconciled.rows.single().attachments.size)
assertFalse(reconciled.rows.any { it.isPending })
}

@Test
fun project_optimisticFile_reconcilesWhenLiveInboxOmitsFile() {
val pendingAttachment =
Expand Down
Loading
Loading