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
3 changes: 3 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 @@ -79,6 +79,7 @@ import dev.opencode.mobile.ui.componentgallery.components.CodeSnippetGalleryScre
import dev.opencode.mobile.ui.componentgallery.components.ComposerSuggestionOverlayGalleryScreen
import dev.opencode.mobile.ui.componentgallery.components.DialogGalleryScreen
import dev.opencode.mobile.ui.componentgallery.components.DictationCardGalleryScreen
import dev.opencode.mobile.ui.componentgallery.components.DropOverlayGalleryScreen
import dev.opencode.mobile.ui.componentgallery.components.DiffStatGalleryScreen
import dev.opencode.mobile.ui.componentgallery.components.EmptyStateGalleryScreen
import dev.opencode.mobile.ui.componentgallery.components.FileIconGalleryScreen
Expand Down Expand Up @@ -808,6 +809,8 @@ fun MainNavigation() {
SessionComposerGalleryScreen()
ComponentGalleryEntryId.DictationCard ->
DictationCardGalleryScreen()
ComponentGalleryEntryId.DropOverlay ->
DropOverlayGalleryScreen()
ComponentGalleryEntryId.RenderedMarkdown ->
RenderedMarkdownGalleryScreen()
ComponentGalleryEntryId.MessageList -> Unit
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
package dev.opencode.mobile.domain.message

/** What a pasted or dropped item is, decided before its bytes are read (#870). */
enum class AttachmentDropKind {
Image,
Pdf,
Text,
File,
Folder,
}

/** A pasted or dropped item. A drag names its items only loosely, so name and size may be unknown. */
data class AttachmentDropItem(
val kind: AttachmentDropKind,
val filename: String? = null,
val byteCount: Long? = null,
)

/** The selected model, the server and the draft, as far as routing a dropped item needs them. */
data class AttachmentDropContext(
val imagesSupported: Boolean = true,
val pdfSupported: Boolean = true,
val uploadAvailable: Boolean = false,
val draft: List<Attachment> = emptyList(),
)

sealed interface AttachmentDropRoute {
data object Accepted : AttachmentDropRoute

data class Skipped(
val reason: String,
) : AttachmentDropRoute
}

/** The drag-over card: what a drop would attach, or why nothing can be. */
data class AttachmentDropSummary(
val title: String,
val subtitle: String,
/** Kinds of the first accepted items, at most [AttachmentDropRouting.MAX_PREVIEWS]. */
val previews: List<AttachmentDropKind>,
/** Nothing in the drag can be attached: the card shows its error style. */
val rejected: Boolean,
)

/**
* Routes pasted and dropped items through the #644 policy before their bytes are read, and words
* the drag-over card. Shared with iOS through `shared/attachment-drop/attachment-drop-cases.json`.
*/
object AttachmentDropRouting {
const val FOLDER_ERROR = "Folders can't be attached."
const val IMAGE_UNSUPPORTED_ERROR = "This model does not support image attachments."
const val PDF_UNSUPPORTED_ERROR = "This model does not support PDF attachments."
const val MAX_PREVIEWS = 4

/** `DocumentsContract.Document.MIME_TYPE_DIR`, without pulling the Android class into the domain. */
const val DIRECTORY_MIME = "vnd.android.document/directory"
private const val INODE_DIRECTORY_MIME = "inode/directory"
private const val ADDS_TO_DRAFT = "Adds them to the message you are writing"
private val pastedImageName = Regex("""^Pasted image (\d+)\.png$""")

fun route(
item: AttachmentDropItem,
context: AttachmentDropContext,
): AttachmentDropRoute {
if (item.kind == AttachmentDropKind.Folder) return AttachmentDropRoute.Skipped(FOLDER_ERROR)
val duplicate =
item.filename != null &&
item.byteCount != null &&
context.draft.any { it.filename == item.filename && it.byteCount == item.byteCount }
if (duplicate) return AttachmentDropRoute.Skipped(AttachmentUploadPolicy.DUPLICATE_ERROR)
val fits = item.byteCount == null || item.byteCount <= AttachmentLimits.MAX_DECODED_BYTES
val inline =
when (item.kind) {
AttachmentDropKind.Image -> context.imagesSupported
AttachmentDropKind.Pdf -> context.pdfSupported
AttachmentDropKind.Text -> true
AttachmentDropKind.File, AttachmentDropKind.Folder -> false
}
if ((inline && fits) || context.uploadAvailable) return AttachmentDropRoute.Accepted
val reason =
when {
item.kind == AttachmentDropKind.Image && !context.imagesSupported -> IMAGE_UNSUPPORTED_ERROR
item.kind == AttachmentDropKind.Pdf && !context.pdfSupported -> PDF_UNSUPPORTED_ERROR
!fits -> AttachmentLimits.TOO_LARGE_ERROR
else -> AttachmentIngestionService.UNSUPPORTED_ERROR
}
return AttachmentDropRoute.Skipped(reason)
}

/**
* Null when [items] is empty (a text-only drag shows no card). [countKnown] is false when the
* platform names only the kinds in a drag, not how many items it holds (Android before the drop).
*/
fun summary(
items: List<AttachmentDropItem>,
context: AttachmentDropContext,
countKnown: Boolean = true,
): AttachmentDropSummary? {
if (items.isEmpty()) return null
val routed = items.map { it to route(it, context) }
val accepted = routed.filter { it.second == AttachmentDropRoute.Accepted }.map { it.first }
val firstReason =
routed
.firstNotNullOfOrNull { (it.second as? AttachmentDropRoute.Skipped)?.reason }
val skipped = routed.size - accepted.size
if (accepted.isEmpty()) {
return AttachmentDropSummary(
title = if (countKnown && items.size == 1) "Can't attach this" else "Can't attach these",
subtitle = firstReason.orEmpty(),
previews = emptyList(),
rejected = true,
)
}
val noun = if (accepted.all { it.kind == AttachmentDropKind.Image }) "image" else "file"
val title =
if (countKnown) {
"Drop to attach ${accepted.size} $noun${if (accepted.size == 1) "" else "s"}"
} else {
"Drop to attach ${noun}s"
}
val subtitle =
when {
firstReason == null -> ADDS_TO_DRAFT
countKnown -> "$skipped will be skipped · $firstReason"
else -> "Some will be skipped · $firstReason"
}
return AttachmentDropSummary(
title = title,
subtitle = subtitle,
previews = accepted.take(MAX_PREVIEWS).map { it.kind },
rejected = false,
)
}

/** `Pasted image N.png`, one past the highest N already in the draft. */
fun pastedImageName(draftFilenames: List<String>): String {
val highest =
draftFilenames
.mapNotNull { name ->
pastedImageName
.find(name)
?.groupValues
?.get(1)
?.toIntOrNull()
}.maxOrNull() ?: 0
return "Pasted image ${highest + 1}.png"
}

/** Kind of an item from its type and name, the way ingestion will classify it. */
fun kind(
mime: String?,
filename: String?,
): AttachmentDropKind {
val type = mime?.substringBefore(';')?.trim()?.lowercase()
if (type == DIRECTORY_MIME || type == INODE_DIRECTORY_MIME) return AttachmentDropKind.Folder
// A drag may name only `image/*` before the drop; photos are png or jpeg in practice.
if (type == "image/*") return AttachmentDropKind.Image
val name = filename.orEmpty()
val declared = AttachmentMime.resolveDeclared(type, name)?.lowercase()
val extension = name.substringAfterLast('.', "").lowercase()
return when {
declared != null && AttachmentDataUrl.kind(declared) == AttachmentKind.Image -> AttachmentDropKind.Image
declared == "application/pdf" -> AttachmentDropKind.Pdf
declared != null && AttachmentMime.isTextLike(declared) -> AttachmentDropKind.Text
(declared == null || declared == AttachmentMime.BINARY) && extension in AttachmentIngestionService.TEXT_EXTENSIONS ->
AttachmentDropKind.Text
else -> AttachmentDropKind.File
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,18 @@ class AttachmentIngestionService private constructor(
* [uploadAvailable]: the server takes streamed uploads, so a file is copied to the store with no
* size cap and any type is accepted (unknown types are classified by [AttachmentMime]). Without
* it, ingestion is the data-URL path unchanged: 20 MB cap, images, PDFs and text only.
* [nameWhenMissing] names content whose provider gives no display name, from its type (a pasted
* image becomes `Pasted image N.png`, #870); null keeps the URI's last path segment.
*/
fun ingest(
uris: List<Uri>,
uploadAvailable: Boolean = false,
nameWhenMissing: (mime: String?) -> String? = { null },
): AttachmentIngestionResult {
val attachments = mutableListOf<Attachment>()
val errors = mutableListOf<String>()
uris.forEach { uri ->
runCatching { if (uploadAvailable) ingestStreamed(uri) else ingest(uri) }
runCatching { if (uploadAvailable) ingestStreamed(uri, nameWhenMissing) else ingest(uri, nameWhenMissing) }
.onSuccess { attachments += it }
.onFailure { throwable ->
val message = throwable.message ?: READ_ERROR
Expand All @@ -48,9 +51,12 @@ class AttachmentIngestionService private constructor(
return AttachmentIngestionResult(attachments, errors)
}

private fun ingestStreamed(uri: Uri): Attachment {
private fun ingestStreamed(
uri: Uri,
nameWhenMissing: (String?) -> String?,
): Attachment {
val contentResolver = requireNotNull(contentResolver)
val metadata = metadata(uri)
val metadata = metadata(uri, nameWhenMissing)
val declared = AttachmentMime.resolveDeclared(contentResolver.getType(uri), metadata.filename)
val stored = newStoreFile(metadata.filename)
val head = ByteArrayOutputStream()
Expand Down Expand Up @@ -84,9 +90,12 @@ class AttachmentIngestionService private constructor(
)
}

private fun ingest(uri: Uri): Attachment {
private fun ingest(
uri: Uri,
nameWhenMissing: (String?) -> String?,
): Attachment {
val contentResolver = requireNotNull(contentResolver)
val metadata = metadata(uri)
val metadata = metadata(uri, nameWhenMissing)
if (metadata.size != null && metadata.size > AttachmentLimits.MAX_DECODED_BYTES) {
throw IllegalArgumentException(AttachmentLimits.TOO_LARGE_ERROR)
}
Expand Down Expand Up @@ -151,7 +160,10 @@ class AttachmentIngestionService private constructor(
return File(directory, "${UUID.randomUUID()}-$safeName")
}

private fun metadata(uri: Uri): AttachmentMetadata {
private fun metadata(
uri: Uri,
nameWhenMissing: (String?) -> String?,
): AttachmentMetadata {
val contentResolver = requireNotNull(contentResolver)
var filename: String? = null
var size: Long? = null
Expand All @@ -171,7 +183,11 @@ class AttachmentIngestionService private constructor(
}
}
return AttachmentMetadata(
filename = filename?.takeIf { it.isNotBlank() } ?: uri.lastPathSegment ?: "Attachment",
filename =
filename?.takeIf { it.isNotBlank() }
?: nameWhenMissing(contentResolver.getType(uri))
?: uri.lastPathSegment
?: "Attachment",
size = size,
)
}
Expand Down Expand Up @@ -254,7 +270,7 @@ class AttachmentIngestionService private constructor(
const val READ_ERROR = "The attachment could not be read."
internal const val MAX_PREVIEW_BYTES = 128 * 1024
private val IMAGE_MIMES = setOf("image/png", "image/jpeg", "image/gif", "image/webp")
private val TEXT_EXTENSIONS =
internal val TEXT_EXTENSIONS =
setOf(
"txt",
"md",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,15 @@ object AttachmentMime {
?.takeIf { it.isNotEmpty() }
return when {
mime in keptTypes -> mime!!
mime != null && (mime.startsWith("text/") || mime in textTypes) -> TEXT
mime != null && isTextLike(mime) -> TEXT
head.take(SNIFF_BYTES).any { it == 0.toByte() } -> mime ?: BINARY
else -> TEXT
}
}

/** Any `text/` type or a text-like application type; [mime] is already trimmed and lowercased. */
fun isTextLike(mime: String): Boolean = mime.startsWith("text/") || mime in textTypes

/**
* The type to classify with: the provider's, unless it names nothing useful (null, blank or the
* generic `application/octet-stream`) and the extension is one the app reads natively.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,8 @@ object ProductAnalytics {
const val ATTACH_PICK_PHOTOS = "attach_pick_photos"
const val ATTACH_PICK_FILES = "attach_pick_files"
const val ATTACH_PICK_LOG_FILE = "attach_pick_log_file"
const val ATTACH_PASTE = "attach_paste"
const val ATTACH_DROP = "attach_drop"
const val MODEL_PICKER_DISMISS = "model_picker_dismiss"
const val MODEL_PICKER_SELECT_PROVIDER = "model_picker_select_provider"
const val MODEL_PICKER_BACK_TO_PROVIDERS = "model_picker_back_to_providers"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ enum class ComponentGalleryEntryId {
SessionBranchPill,
SessionComposer,
DictationCard,
DropOverlay,
RenderedMarkdown,
MessageList,
}
Expand Down Expand Up @@ -455,6 +456,12 @@ val ComponentGalleryEntries =
description = "Listening takeover for composer dictation.",
category = ComponentGalleryCategory.Session,
),
ComponentGalleryEntry(
id = ComponentGalleryEntryId.DropOverlay,
title = "Drop Overlay",
description = "Drag-over scrim card for images and files dropped on Session Chat.",
category = ComponentGalleryCategory.Session,
),
ComponentGalleryEntry(
id = ComponentGalleryEntryId.SessionBranchPill,
title = "Session Branch Pill",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package dev.opencode.mobile.ui.componentgallery.components

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import dev.opencode.mobile.ui.components.OpenCodeAttachmentVariant
import dev.opencode.mobile.ui.components.OpenCodeDropOverlay
import dev.opencode.mobile.ui.components.OpenCodeDropOverlayVariant

@Composable
fun DropOverlayGalleryScreen(modifier: Modifier = Modifier) {
Column(modifier = modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(16.dp)) {
Box(Modifier.fillMaxWidth().height(320.dp)) {
OpenCodeDropOverlay(
variant = OpenCodeDropOverlayVariant.Accept,
title = "Drop to attach 3 images",
subtitle = "Adds them to the message you are writing",
previews = List(3) { OpenCodeAttachmentVariant.Image },
)
}
Box(Modifier.fillMaxWidth().height(320.dp)) {
OpenCodeDropOverlay(
variant = OpenCodeDropOverlayVariant.Accept,
title = "Drop to attach 2 files",
subtitle = "1 will be skipped · Folders can't be attached.",
previews = listOf(OpenCodeAttachmentVariant.Image, OpenCodeAttachmentVariant.Text),
)
}
Box(Modifier.fillMaxWidth().height(320.dp)) {
OpenCodeDropOverlay(
variant = OpenCodeDropOverlayVariant.Reject,
title = "Can't attach this",
subtitle = "Folders can't be attached.",
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,7 @@ private val OpenCodeSessionComposerAction.label: String
OpenCodeSessionComposerAction.Attach -> "Attach"
OpenCodeSessionComposerAction.OpenCommands -> "Open commands"
is OpenCodeSessionComposerAction.RemoveAttachment -> "Remove attachment"
is OpenCodeSessionComposerAction.PasteContent -> "Paste attachment"
OpenCodeSessionComposerAction.CancelRevert -> "Cancel revert"
OpenCodeSessionComposerAction.ExitShellMode -> "Exit shell mode"
OpenCodeSessionComposerAction.ExitSideQuestionMode -> "Exit side question mode"
Expand Down
Loading
Loading