diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 151fdb0b..d2cd1fce 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -52,6 +52,18 @@ + + + + + diff --git a/android/app/src/main/kotlin/app/hapi/companion/Navigation.kt b/android/app/src/main/kotlin/app/hapi/companion/Navigation.kt index c59a794e..3fec7b11 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/Navigation.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/Navigation.kt @@ -330,6 +330,10 @@ private class ChatViewModelHolder( override fun onCleared() { dictation.cancel() + // Leaving the chat for good (not rotation): un-sent uploaded + // attachments are discarded after a best-effort hub delete (B-M3f; + // attachments are not part of drafts v1). + viewModel.discardAttachments() viewModel.stop() scope.cancel() } diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatScreen.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatScreen.kt index 3300f56f..081f43fa 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatScreen.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatScreen.kt @@ -2,7 +2,9 @@ package app.hapi.companion.feature.chat import android.Manifest import android.content.pm.PackageManager +import android.net.Uri import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement @@ -50,6 +52,8 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.listSaver +import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -58,6 +62,10 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.core.content.ContextCompat +import app.hapi.companion.feature.chat.attachments.AttachmentPickerSheet +import app.hapi.companion.feature.chat.attachments.AttachmentPreparer +import app.hapi.companion.feature.chat.attachments.CameraCapture +import app.hapi.companion.feature.chat.attachments.PrepareResult import app.hapi.companion.feature.chat.composer.ChatComposer import app.hapi.companion.feature.chat.composer.DictationController import app.hapi.companion.feature.chat.composer.DictationEvent @@ -68,11 +76,22 @@ import app.hapi.companion.feature.sessions.RenameSessionDialog import app.hapi.companion.ui.markdown.LocalMarkdownLinkHandler import app.hapi.companion.ui.theme.hapi import app.hapi.protocol.chat.VisibleChatBlock +import java.io.File import kotlinx.coroutines.launch /** How close to the oldest rendered block the viewport may get before paging. */ private const val LOAD_OLDER_PREFETCH_ITEMS = 4 +/** Pending camera capture across rotation/process death: uri + scratch path. */ +private val CameraCaptureSaver = listSaver( + save = { capture -> + if (capture == null) emptyList() else listOf(capture.uri.toString(), capture.file.absolutePath) + }, + restore = { saved -> + if (saved.size < 2) null else CameraCapture(Uri.parse(saved[0]), File(saved[1])) + }, +) + /** * The chat screen: `LazyColumn(reverseLayout = true)` over the reduced * [VisibleChatBlock]s — newest at the bottom, stable ids as keys so scroll @@ -89,6 +108,12 @@ private const val LOAD_OLDER_PREFETCH_ITEMS = 4 * append), the slash-command dropdown, and session ops: a top-bar overflow * menu (Rename / Reopen / Delete) plus an inactive-session affordance bar * above the composer (send already auto-resumes; Reopen is the explicit path). + * + * B-M3f adds composer attachments: the "+" sheet (photo library / camera / + * files), pick preparation ([AttachmentPreparer]: ContentResolver read + + * image downscale + 50 MB reject) feeding the ViewModel's upload tray, and + * the camera scratch capture (FileProvider Uri, `rememberSaveable` across + * rotation while the camera app is up). */ @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -164,6 +189,79 @@ fun ChatScreen( } val slashSuggestions by viewModel.slashSuggestions.collectAsState() + // --------------------------------------------------------- attachments -- + val attachmentItems by viewModel.attachments.items.collectAsState() + var attachmentSheetOpen by remember { mutableStateOf(false) } + val preparer = remember { AttachmentPreparer(context) } + + /** Read + policy-apply one pick, then hand it to the upload tray. */ + suspend fun ingestUri(uri: Uri) { + when (val result = preparer.prepare(uri)) { + is PrepareResult.Ready -> viewModel.attachments.add(result.attachment) + is PrepareResult.TooLarge -> snackbarHostState.showSnackbar( + "${result.filename} is over the 50 MB upload limit", + ) + is PrepareResult.Unreadable -> snackbarHostState.showSnackbar( + "Couldn't read ${result.filename}", + ) + } + } + + fun ingestUris(uris: List) { + if (uris.isEmpty()) return + scope.launch { uris.forEach { ingestUri(it) } } + } + + val photoPickerLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.PickMultipleVisualMedia(), + ) { uris -> ingestUris(uris) } + val documentPickerLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.OpenMultipleDocuments(), + ) { uris -> ingestUris(uris) } + + // The camera app may rotate/kill us while open — keep the scratch target. + var pendingCapture by rememberSaveable(stateSaver = CameraCaptureSaver) { + mutableStateOf(null) + } + val takePictureLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.TakePicture(), + ) { success -> + val capture = pendingCapture + pendingCapture = null + if (capture == null) return@rememberLauncherForActivityResult + if (!success) { + capture.discard() + return@rememberLauncherForActivityResult + } + scope.launch { + ingestUri(capture.uri) + capture.discard() + } + } + + fun launchCamera() { + val capture = preparer.newCameraCapture() + pendingCapture = capture + takePictureLauncher.launch(capture.uri) + } + + val cameraPermissionLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.RequestPermission(), + ) { granted -> + if (granted) { + launchCamera() + } else { + scope.launch { snackbarHostState.showSnackbar("Camera permission is needed to take a photo") } + } + } + val onTakePhoto: () -> Unit = { + // The manifest declares CAMERA (QR pairing), which makes the runtime + // grant mandatory for ACTION_IMAGE_CAPTURE too. + val granted = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == + PackageManager.PERMISSION_GRANTED + if (granted) launchCamera() else cameraPermissionLauncher.launch(Manifest.permission.CAMERA) + } + val interactions = remember(state.flavor, state.permissionOverrides, viewModel) { ChatInteractions( flavor = state.flavor, @@ -216,6 +314,10 @@ fun ChatScreen( onSend = { viewModel.sendMessage() }, onSendSteer = { viewModel.sendMessage(steer = true) }, onAbort = viewModel::abortSession, + attachments = attachmentItems, + onAddAttachment = { attachmentSheetOpen = true }, + onAttachmentRetry = viewModel.attachments::retry, + onAttachmentRemove = viewModel.attachments::remove, slashSuggestions = slashSuggestions, onSlashCommandSelected = viewModel::selectSlashCommand, dictation = if (dictation != null) dictationState else null, @@ -250,6 +352,18 @@ fun ChatScreen( } } + if (attachmentSheetOpen) { + AttachmentPickerSheet( + onDismiss = { attachmentSheetOpen = false }, + onPickPhotos = { + photoPickerLauncher.launch( + PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageAndVideo), + ) + }, + onTakePhoto = onTakePhoto, + onPickFiles = { documentPickerLauncher.launch(arrayOf("*/*")) }, + ) + } if (configSheetOpen) { SessionConfigSheet( config = configState, diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatViewModel.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatViewModel.kt index 8ac549c8..0a5e44e8 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatViewModel.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatViewModel.kt @@ -1,5 +1,6 @@ package app.hapi.companion.feature.chat +import app.hapi.companion.feature.chat.attachments.ComposerAttachments import app.hapi.companion.feature.chat.composer.ChatDrafts import app.hapi.companion.feature.chat.composer.SlashCommands import app.hapi.companion.feature.chat.composer.appendTranscript @@ -225,6 +226,18 @@ sealed interface PermissionAction { * pickers with optimistic detail updates, rolled back to server truth on * error; codex model catalog fetched per session ([loadModelOptions]). * + * B-M3f adds: + * - **Attachments** ([attachments], a [ComposerAttachments] tray): picks are + * prepared by the screen (ContentResolver read + image downscale) and + * uploaded immediately; [sendMessage] refuses while any chip is unsettled, + * then rides the Ready set as `SendMessageRequest.attachments` — the + * optimistic row carries them so the user bubble shows thumbnails at once, + * and [retryFailedMessage] re-extracts them from the row's wire content. + * Attachments are NOT part of drafts (v1 simplification vs the web's + * IndexedDB attachment drafts): leaving the chat for good + * ([discardAttachments], holder `onCleared`) drops un-sent chips after a + * best-effort hub delete. + * * B-M3ce adds: * - **Slash commands** ([slashSuggestions]/[selectSlashCommand]): `/token` * composer input opens the dropdown; sources = `metadata.slashCommands` @@ -281,6 +294,12 @@ class ChatViewModel( private val composerText = MutableStateFlow("") private val sendInFlight = MutableStateFlow(false) + + /** + * Composer attachment tray (B-M3f). The screen feeds prepared picks in + * and renders `attachments.items`; [sendMessage] consumes the Ready set. + */ + val attachments = ComposerAttachments(api = api, sessionId = sessionId, scope = scope) private val queuedOpPending = MutableStateFlow(false) private val permissionOverrides = MutableStateFlow>(emptyMap()) private val configOpPending = MutableStateFlow(false) @@ -552,11 +571,24 @@ class ChatViewModel( /** * Submit the composer. Delivery defaults to durable queue; [steer] is the * explicit long-press intent that delivers into the active turn - * (`deliveryMode: "steer"` — `messageDelivery.ts` semantics). + * (`deliveryMode: "steer"` — `messageDelivery.ts` semantics; attachments + * may ride a steer, only `scheduledAt` excludes them). + * + * Ready attachments are consumed into `SendMessageRequest.attachments`; + * an unsettled chip (uploading/failed) blocks the send with a notice. + * Text may be empty when attachments exist (wire: text OR attachments). */ fun sendMessage(steer: Boolean = false) { + if (sendInFlight.value) return + if (attachments.hasUnsettled()) { + _events.tryEmit( + ChatEvent.Notice("Attachments are still uploading — wait, or retry/remove the failed ones"), + ) + return + } val text = composerText.value.trim() - if (text.isEmpty() || sendInFlight.value) return + val attachmentMetadata = attachments.consume() + if (text.isEmpty() && attachmentMetadata == null) return composerText.value = "" draftJob?.cancel() scope.launch { @@ -566,11 +598,21 @@ class ChatViewModel( localId = localIdGenerator(), createdAt = now(), deliveryMode = if (steer) "steer" else "queue", + attachments = attachmentMetadata, isRetry = false, ) } } + /** + * The screen is going away for good (holder `onCleared`, not a config + * change): un-sent uploads are discarded after a best-effort hub delete. + * Attachments deliberately do not persist in drafts v1. + */ + fun discardAttachments() { + attachments.discardAllDetached() + } + /** Tap-to-retry on a failed optimistic row: re-fires the send with the same localId. */ fun retryFailedMessage(localId: String) { if (sendInFlight.value) return @@ -617,6 +659,12 @@ class ChatViewModel( scheduledAt: Long? = null, isRetry: Boolean, ) { + // Wire constraint (SendMessageRequestSchema): scheduled sends exclude + // attachments (and steer). No Android surface can produce the combo + // today — this trips loudly if a scheduled-send UI ever forgets it. + check(scheduledAt == null || attachments.isNullOrEmpty()) { + "scheduled sends cannot carry attachments" + } sendInFlight.value = true try { val store = awaitWindowStore() diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/attachments/AttachmentPickerSheet.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/attachments/AttachmentPickerSheet.kt new file mode 100644 index 00000000..a22c5f78 --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/attachments/AttachmentPickerSheet.kt @@ -0,0 +1,79 @@ +package app.hapi.companion.feature.chat.attachments + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import app.hapi.companion.ui.theme.HapiTheme +import app.hapi.companion.ui.theme.hapi + +/** + * The composer "+" sheet (B-M3f): three attachment sources. The launchers + * (photo picker / TakePicture / OpenDocument) live in the screen — this is + * pure chrome. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun AttachmentPickerSheet( + onDismiss: () -> Unit, + onPickPhotos: () -> Unit, + onTakePhoto: () -> Unit, + onPickFiles: () -> Unit, +) { + ModalBottomSheet(onDismissRequest = onDismiss) { + Column(modifier = Modifier.padding(bottom = 20.dp)) { + Text( + text = "Attach", + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.hapi.hint, + modifier = Modifier.padding(horizontal = 20.dp, vertical = 6.dp), + ) + PickerRow(glyph = "🖼", label = "Photo library", onClick = { onDismiss(); onPickPhotos() }) + PickerRow(glyph = "📷", label = "Camera", onClick = { onDismiss(); onTakePhoto() }) + PickerRow(glyph = "📄", label = "Files", onClick = { onDismiss(); onPickFiles() }) + } + } +} + +@Composable +private fun PickerRow(glyph: String, label: String, onClick: () -> Unit) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .padding(horizontal = 20.dp, vertical = 14.dp), + ) { + Text(text = glyph, fontSize = 20.sp) + Spacer(modifier = Modifier.width(16.dp)) + Text(text = label, style = MaterialTheme.typography.bodyLarge) + } +} + +@Preview(showBackground = true) +@Composable +private fun AttachmentPickerRowsPreview() { + HapiTheme { + Surface { + Column { + PickerRow(glyph = "🖼", label = "Photo library", onClick = {}) + PickerRow(glyph = "📷", label = "Camera", onClick = {}) + PickerRow(glyph = "📄", label = "Files", onClick = {}) + } + } + } +} diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/attachments/AttachmentPolicy.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/attachments/AttachmentPolicy.kt new file mode 100644 index 00000000..335fc537 --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/attachments/AttachmentPolicy.kt @@ -0,0 +1,159 @@ +package app.hapi.companion.feature.chat.attachments + +import java.util.Base64 + +/** + * Pure sizing/compression policy for composer attachments (B-M3f) — no + * Android types, so every decision is JVM-testable. + * + * Wire contract (`rest.md` uploads): `POST /api/sessions/:id/upload` is + * JSON + base64 with a hard 50 MB decoded limit. The web sends originals + * (`attachmentAdapter.ts`); on mobile data that is hostile for camera + * photos, so images above [IMAGE_COMPRESS_THRESHOLD_BYTES] are downscaled + * to [MAX_IMAGE_DIMENSION] px and re-encoded as JPEG ([COMPRESS_JPEG_QUALITY]) + * before upload. Non-image files always keep their original bytes. + */ +object AttachmentPolicy { + + /** Hub upload ceiling (decoded bytes) — `MAX_UPLOAD_BYTES` on the web. */ + const val MAX_UPLOAD_BYTES: Long = 50L * 1024 * 1024 + + /** Images larger than this get downscaled + JPEG-recompressed. */ + const val IMAGE_COMPRESS_THRESHOLD_BYTES: Long = 4L * 1024 * 1024 + + /** Longest edge after downscaling. */ + const val MAX_IMAGE_DIMENSION: Int = 2048 + + /** JPEG quality for recompressed uploads. */ + const val COMPRESS_JPEG_QUALITY: Int = 85 + + /** + * Longest edge of the thumbnail embedded as `AttachmentMetadata.previewUrl` + * (a JPEG data URL). The web embeds the full original (≤ 5 MB) there; a + * small thumb keeps `SendMessageRequest` bodies tiny while still giving + * every client (web included) something to render in the user bubble. + */ + const val PREVIEW_MAX_DIMENSION: Int = 512 + + /** JPEG quality for the embedded preview thumbnail. */ + const val PREVIEW_JPEG_QUALITY: Int = 80 + + /** + * Heap guard for reading picked content whose provider reports no size: + * recompressible images may legitimately exceed 50 MB pre-compression, + * everything else stops at the wire cap (see [readCapFor]). + */ + const val MAX_IMAGE_SOURCE_BYTES: Long = 192L * 1024 * 1024 + + /** + * Formats that are safe to decode + re-encode as a still JPEG. GIFs are + * excluded (recompression would drop animation) and SVG/unknown types + * are not bitmap-decodable — those upload as originals or get rejected. + */ + private val RECOMPRESSIBLE_IMAGE_MIMES = setOf( + "image/jpeg", + "image/jpg", + "image/png", + "image/webp", + "image/heic", + "image/heif", + ) + + /** What the preparer should do with a picked file. */ + sealed interface Plan { + /** Upload the original bytes untouched. */ + data object KeepOriginal : Plan + + /** Downscale to [MAX_IMAGE_DIMENSION] + JPEG-recompress, then upload. */ + data object CompressImage : Plan + + /** Over the 50 MB wire cap and not recoverable by compression. */ + data object Reject : Plan + } + + /** + * Decide the handling for a file of [mimeType] and [sizeBytes]. + * + * Recompressible images over the threshold are compressed even when the + * original exceeds 50 MB — downscaling brings any camera photo far under + * the cap (the post-compression size is re-checked by the preparer). + */ + fun planFor(mimeType: String, sizeBytes: Long): Plan = when { + isRecompressibleImageMime(mimeType) && sizeBytes > IMAGE_COMPRESS_THRESHOLD_BYTES -> + Plan.CompressImage + sizeBytes > MAX_UPLOAD_BYTES -> Plan.Reject + else -> Plan.KeepOriginal + } + + /** How many bytes to read at most before giving up on a pick as too large. */ + fun readCapFor(mimeType: String): Long = + if (isRecompressibleImageMime(mimeType)) MAX_IMAGE_SOURCE_BYTES else MAX_UPLOAD_BYTES + + fun isImageMime(mimeType: String): Boolean = mimeType.startsWith("image/") + + fun isRecompressibleImageMime(mimeType: String): Boolean = + mimeType.lowercase() in RECOMPRESSIBLE_IMAGE_MIMES + + /** + * Power-of-two `BitmapFactory.Options.inSampleSize` so the decoded bitmap + * is the smallest one whose longest edge is still ≥ [maxDimension] + * (exact scaling happens after decode via [scaledDimensions]). + */ + fun sampleSizeFor(width: Int, height: Int, maxDimension: Int): Int { + if (width <= 0 || height <= 0) return 1 + var sample = 1 + val longest = maxOf(width, height) + while (longest / (sample * 2) >= maxDimension) { + sample *= 2 + } + return sample + } + + /** Final (width, height) with the longest edge clamped to [maxDimension]. */ + fun scaledDimensions(width: Int, height: Int, maxDimension: Int): Pair { + val longest = maxOf(width, height) + if (longest <= maxDimension || longest <= 0) return width to height + val scale = maxDimension.toDouble() / longest + val w = (width * scale).toInt().coerceAtLeast(1) + val h = (height * scale).toInt().coerceAtLeast(1) + return w to h + } + + /** + * Recompression re-encodes as JPEG, so the advertised filename swaps its + * extension to `.jpg` (a `shot.png` upload that is actually JPEG bytes + * would confuse the agent reading it from disk). + */ + fun compressedFilename(original: String): String { + val dot = original.lastIndexOf('.') + val stem = if (dot > 0) original.substring(0, dot) else original + return "$stem.jpg" + } + + /** `data:;base64,<...>` — the wire `previewUrl` format (web parity). */ + fun dataUrl(mimeType: String, bytes: ByteArray): String = + "data:$mimeType;base64,${Base64.getEncoder().encodeToString(bytes)}" + + /** + * The base64 payload of a data URL, or null when [url] is not one. + * Accepts any `data:*;base64,` head — web previews are `data:image/png` + * etc., Android-authored ones are always JPEG. + */ + fun base64FromDataUrl(url: String): String? { + if (!url.startsWith("data:")) return null + val comma = url.indexOf(',') + if (comma < 0) return null + if (!url.substring(0, comma).endsWith(";base64")) return null + return url.substring(comma + 1).takeIf { it.isNotEmpty() } + } + + /** Decoded bytes of a base64 data URL, or null when unparseable. */ + fun bytesFromDataUrl(url: String): ByteArray? { + val base64 = base64FromDataUrl(url) ?: return null + return try { + Base64.getDecoder().decode(base64) + } catch (_: IllegalArgumentException) { + null + } + } +} diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/attachments/AttachmentPreparer.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/attachments/AttachmentPreparer.kt new file mode 100644 index 00000000..6d31e296 --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/attachments/AttachmentPreparer.kt @@ -0,0 +1,246 @@ +package app.hapi.companion.feature.chat.attachments + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.net.Uri +import android.provider.OpenableColumns +import android.webkit.MimeTypeMap +import androidx.core.content.FileProvider +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.InputStream +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale +import java.util.UUID +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** Outcome of preparing one picked/captured file for upload. */ +sealed interface PrepareResult { + data class Ready(val attachment: PreparedAttachment) : PrepareResult + + /** Over the 50 MB wire cap (and not recoverable by image compression). */ + data class TooLarge(val filename: String, val sizeBytes: Long) : PrepareResult + + /** The content provider would not give us the bytes. */ + data class Unreadable(val filename: String) : PrepareResult +} + +/** + * A pending camera capture: the FileProvider [uri] handed to the camera app + + * its backing [file] ([file] is exposed so the screen can `rememberSaveable` + * the pending capture across rotation/process death while the camera is open). + */ +class CameraCapture(val uri: Uri, val file: File) { + /** Delete the cache-file scratch once the capture was ingested (or abandoned). */ + fun discard() { + runCatching { file.delete() } + } +} + +/** + * Reads picked content into [PreparedAttachment]s ready for + * [ComposerAttachments.add] (B-M3f). All policy decisions live in the pure + * [AttachmentPolicy]; this class supplies the Android parts: ContentResolver + * metadata + bytes, `BitmapFactory` downscaling, JPEG re-encode, thumbnail + * generation, and the FileProvider scratch file for `TakePicture`. + * + * Compression stance (differs from web, which uploads originals): images over + * [AttachmentPolicy.IMAGE_COMPRESS_THRESHOLD_BYTES] are downscaled to + * [AttachmentPolicy.MAX_IMAGE_DIMENSION] px JPEG — phone photos are 5–15 MB + * of mostly-wasted agent context on mobile data. Non-image files always keep + * their original bytes; anything still over 50 MB is rejected. + */ +class AttachmentPreparer( + context: Context, + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, +) { + private val appContext = context.applicationContext + + suspend fun prepare(uri: Uri): PrepareResult = withContext(ioDispatcher) { + val resolver = appContext.contentResolver + + var displayName: String? = null + var statedSize: Long? = null + runCatching { + resolver.query(uri, null, null, null, null)?.use { cursor -> + if (cursor.moveToFirst()) { + val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) + if (nameIndex >= 0 && !cursor.isNull(nameIndex)) displayName = cursor.getString(nameIndex) + val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE) + if (sizeIndex >= 0 && !cursor.isNull(sizeIndex)) statedSize = cursor.getLong(sizeIndex) + } + } + } + + val mimeType = resolver.getType(uri) + ?: displayName?.let { guessMimeFromName(it) } + ?: "application/octet-stream" + val filename = displayName ?: fallbackFilename(mimeType) + + // Reject before reading when the provider already told us it's hopeless. + statedSize?.let { size -> + if (AttachmentPolicy.planFor(mimeType, size) == AttachmentPolicy.Plan.Reject) { + return@withContext PrepareResult.TooLarge(filename, size) + } + } + + // Providers may report no size — read behind a capped stream so a + // surprise multi-GB pick cannot OOM the process. + val readCap = AttachmentPolicy.readCapFor(mimeType) + val original = try { + resolver.openInputStream(uri)?.use { readUpTo(it, readCap) } + } catch (_: Exception) { + return@withContext PrepareResult.Unreadable(filename) + } catch (_: OutOfMemoryError) { + return@withContext PrepareResult.Unreadable(filename) + } ?: return@withContext PrepareResult.Unreadable(filename) + + if (original.overflowed) { + return@withContext PrepareResult.TooLarge(filename, statedSize ?: readCap) + } + prepareBytes(filename, mimeType, original.bytes) + } + + private class CappedRead(val bytes: ByteArray, val overflowed: Boolean) + + /** Read the full stream, or stop with `overflowed` once [cap] bytes are exceeded. */ + private fun readUpTo(stream: InputStream, cap: Long): CappedRead { + val out = ByteArrayOutputStream() + val buffer = ByteArray(64 * 1024) + var total = 0L + while (true) { + val read = stream.read(buffer) + if (read < 0) break + total += read + if (total > cap) return CappedRead(ByteArray(0), overflowed = true) + out.write(buffer, 0, read) + } + return CappedRead(out.toByteArray(), overflowed = false) + } + + /** Policy application over in-memory bytes (shared by every pick source). */ + private fun prepareBytes(filename: String, mimeType: String, original: ByteArray): PrepareResult { + val id = "att-${UUID.randomUUID()}" + return when (AttachmentPolicy.planFor(mimeType, original.size.toLong())) { + AttachmentPolicy.Plan.Reject -> PrepareResult.TooLarge(filename, original.size.toLong()) + + AttachmentPolicy.Plan.KeepOriginal -> PrepareResult.Ready( + PreparedAttachment( + id = id, + filename = filename, + mimeType = mimeType, + bytes = original, + previewBytes = if (AttachmentPolicy.isImageMime(mimeType)) thumbnail(original) else null, + ), + ) + + AttachmentPolicy.Plan.CompressImage -> { + val compressed = recompress(original) + when { + compressed != null -> PrepareResult.Ready( + PreparedAttachment( + id = id, + filename = AttachmentPolicy.compressedFilename(filename), + mimeType = "image/jpeg", + bytes = compressed, + previewBytes = thumbnail(compressed), + ), + ) + // Undecodable (e.g. HEIC on API 26/27): fall back to the + // original when it fits the wire cap, reject otherwise. + original.size <= AttachmentPolicy.MAX_UPLOAD_BYTES -> PrepareResult.Ready( + PreparedAttachment( + id = id, + filename = filename, + mimeType = mimeType, + bytes = original, + previewBytes = thumbnail(original), + ), + ) + else -> PrepareResult.TooLarge(filename, original.size.toLong()) + } + } + } + } + + /** Downscale to ≤ [AttachmentPolicy.MAX_IMAGE_DIMENSION] px JPEG, or null when undecodable/still too big. */ + private fun recompress(original: ByteArray): ByteArray? { + val encoded = encodeScaledJpeg( + original, + AttachmentPolicy.MAX_IMAGE_DIMENSION, + AttachmentPolicy.COMPRESS_JPEG_QUALITY, + ) ?: return null + // Belt-and-braces: a 2048px JPEG is always far under 50 MB, but the + // wire cap is a hard contract. + return encoded.takeIf { it.size <= AttachmentPolicy.MAX_UPLOAD_BYTES } + } + + /** Chip/bubble thumbnail (also the wire `previewUrl` payload); null when undecodable. */ + private fun thumbnail(imageBytes: ByteArray): ByteArray? = encodeScaledJpeg( + imageBytes, + AttachmentPolicy.PREVIEW_MAX_DIMENSION, + AttachmentPolicy.PREVIEW_JPEG_QUALITY, + ) + + private fun encodeScaledJpeg(source: ByteArray, maxDimension: Int, quality: Int): ByteArray? { + try { + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(source, 0, source.size, bounds) + if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null + + val options = BitmapFactory.Options().apply { + inSampleSize = AttachmentPolicy.sampleSizeFor(bounds.outWidth, bounds.outHeight, maxDimension) + } + val decoded = BitmapFactory.decodeByteArray(source, 0, source.size, options) ?: return null + val (targetW, targetH) = AttachmentPolicy.scaledDimensions(decoded.width, decoded.height, maxDimension) + val scaled = if (targetW != decoded.width || targetH != decoded.height) { + Bitmap.createScaledBitmap(decoded, targetW, targetH, true).also { + if (it !== decoded) decoded.recycle() + } + } else { + decoded + } + val out = ByteArrayOutputStream() + val ok = scaled.compress(Bitmap.CompressFormat.JPEG, quality, out) + scaled.recycle() + return if (ok) out.toByteArray() else null + } catch (_: Exception) { + return null + } catch (_: OutOfMemoryError) { + return null + } + } + + // ------------------------------------------------------------- camera -- + + /** + * Scratch target for `ActivityResultContracts.TakePicture`: a cache file + * under `cache/attachments/` exposed through the app's FileProvider + * (authority `.attachments`, `attachment_file_paths.xml`). + * Call [CameraCapture.discard] after ingesting (or on cancel) — captures + * never persist past the pick. + */ + fun newCameraCapture(): CameraCapture { + val dir = File(appContext.cacheDir, "attachments").apply { mkdirs() } + val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date()) + val file = File(dir, "camera-$stamp.jpg") + val uri = FileProvider.getUriForFile(appContext, "${appContext.packageName}.attachments", file) + return CameraCapture(uri, file) + } + + private fun guessMimeFromName(name: String): String? { + val extension = name.substringAfterLast('.', "").lowercase(Locale.US) + if (extension.isEmpty()) return null + return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) + } + + private fun fallbackFilename(mimeType: String): String { + val extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType) + val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date()) + return if (extension != null) "attachment-$stamp.$extension" else "attachment-$stamp" + } +} diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/attachments/AttachmentThumbnails.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/attachments/AttachmentThumbnails.kt new file mode 100644 index 00000000..38e466cc --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/attachments/AttachmentThumbnails.kt @@ -0,0 +1,68 @@ +package app.hapi.companion.feature.chat.attachments + +import android.graphics.BitmapFactory +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.runtime.produceState +import androidx.compose.runtime.remember +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asImageBitmap +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** Async decode outcome for a wire `previewUrl` thumbnail. */ +sealed interface PreviewImage { + /** Decode still running — render a neutral placeholder. */ + data object Loading : PreviewImage + + data class Ready(val bitmap: ImageBitmap) : PreviewImage + + /** Not a data URL / undecodable — fall back to the filename chip. */ + data object Unavailable : PreviewImage +} + +/** + * Decode an `AttachmentMetadata.previewUrl` data URL into a bubble thumbnail. + * + * Android-authored previews are ≤ 512 px JPEGs, but web-authored ones embed + * the full original (up to 5 MB), so the decode downsamples to [maxDimension] + * and runs off the main thread. + */ +@Composable +fun rememberPreviewImage(previewUrl: String?, maxDimension: Int = 512): State = + produceState(initialValue = PreviewImage.Loading, previewUrl) { + if (previewUrl == null) { + value = PreviewImage.Unavailable + return@produceState + } + value = withContext(Dispatchers.Default) { + val bytes = AttachmentPolicy.bytesFromDataUrl(previewUrl) + val bitmap = bytes?.let { decodeDownsampled(it, maxDimension) } + if (bitmap != null) PreviewImage.Ready(bitmap) else PreviewImage.Unavailable + } + } + +/** + * Synchronous decode for composer chip thumbs — [ComposerAttachmentUi.previewBytes] + * are preparer-made ≤ 512 px JPEGs, cheap enough to decode inline. + */ +@Composable +fun rememberChipThumbnail(previewBytes: ByteArray?): ImageBitmap? = remember(previewBytes) { + previewBytes?.let { decodeDownsampled(it, AttachmentPolicy.PREVIEW_MAX_DIMENSION) } +} + +private fun decodeDownsampled(bytes: ByteArray, maxDimension: Int): ImageBitmap? { + return try { + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) + if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null + val options = BitmapFactory.Options().apply { + inSampleSize = AttachmentPolicy.sampleSizeFor(bounds.outWidth, bounds.outHeight, maxDimension) + } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)?.asImageBitmap() + } catch (_: Exception) { + null + } catch (_: OutOfMemoryError) { + null + } +} diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/attachments/ComposerAttachments.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/attachments/ComposerAttachments.kt new file mode 100644 index 00000000..69ee63fb --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/attachments/ComposerAttachments.kt @@ -0,0 +1,236 @@ +package app.hapi.companion.feature.chat.attachments + +import app.hapi.data.api.AttachmentUploadApi +import app.hapi.protocol.wire.AttachmentMetadata +import java.util.Base64 +import kotlin.coroutines.cancellation.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.DelicateCoroutinesApi +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * A picked file after platform preparation (ContentResolver read + optional + * image downscale): everything the upload flow needs, no Android types — + * JVM tests feed these directly. + */ +class PreparedAttachment( + val id: String, + /** Display/upload filename (extension rewritten to `.jpg` when compressed). */ + val filename: String, + val mimeType: String, + /** The exact bytes that will upload (post-compression when applicable). */ + val bytes: ByteArray, + /** Small JPEG thumbnail for the chip + wire `previewUrl`; null for non-images. */ + val previewBytes: ByteArray? = null, +) { + val sizeBytes: Long get() = bytes.size.toLong() +} + +/** Chip lifecycle: uploading → ready (or failed → retry/remove). */ +enum class ComposerAttachmentStatus { Uploading, Ready, Failed } + +/** One composer attachment chip. */ +@Suppress("ArrayInDataClass") +data class ComposerAttachmentUi( + val id: String, + val filename: String, + val mimeType: String, + val sizeBytes: Long, + /** JPEG thumbnail bytes for image picks; null renders a file glyph. */ + val previewBytes: ByteArray?, + val status: ComposerAttachmentStatus, +) + +/** + * Composer attachment tray (B-M3f): upload-on-pick state machine feeding + * `SendMessageRequest.attachments`. + * + * Mirrors the web `attachmentAdapter.ts` flow with mobile adjustments: + * + * - [add] uploads immediately (`POST upload`, JSON + base64) and tracks the + * chip through [ComposerAttachmentStatus]; failures keep the payload bytes + * for [retry], successes drop them (only the small preview stays resident). + * - [remove] deletes the uploaded file best-effort (`POST upload/delete`); + * removing a chip whose upload is still in flight lets the upload finish + * and then deletes the orphan (web `cancelledAttachmentIds` semantics). + * - [consume] converts every Ready chip into [AttachmentMetadata] for the + * send body — `previewUrl` is a small JPEG data URL + * ([AttachmentPolicy.PREVIEW_MAX_DIMENSION]) so user bubbles render + * thumbnails on every client. + * - **Drafts (v1 simplification)**: unlike the web (IndexedDB attachment + * drafts), attachments never persist. Leaving the chat for good discards + * un-sent chips via [discardAllDetached] after best-effort hub deletes; + * text drafts alone survive. + * - **Inactive sessions (v1 simplification)**: the hub's upload route + * requires an active session, and unlike the web this tray does not + * resume-then-upload — a pick on an inactive session settles Failed; + * sending any text auto-resumes (B-M3ab), after which the chip's retry + * succeeds. Uploaded paths are absolute on the agent machine, so they + * stay readable across a resume (even one that supersedes the id). + */ +class ComposerAttachments( + private val api: AttachmentUploadApi, + private val sessionId: String, + private val scope: CoroutineScope, + /** Base64 of up to 50 MB happens off the main thread. */ + private val encodeDispatcher: CoroutineDispatcher = Dispatchers.Default, + /** [discardAllDetached] launch target; null ⇒ GlobalScope (production). */ + private val detachedCleanupScope: CoroutineScope? = null, +) { + private class Entry( + val ui: ComposerAttachmentUi, + /** Hub upload path once Ready. */ + val path: String? = null, + /** Upload payload, retained only until the upload succeeds (retry source). */ + val bytes: ByteArray? = null, + ) + + private val entries = MutableStateFlow>(emptyList()) + + /** Chip states for the composer row. */ + val items: StateFlow> = entries + .map { list -> list.map { it.ui } } + .stateIn(scope, SharingStarted.Eagerly, emptyList()) + + /** Convenience for send gating: chips exist and every one settled Ready. */ + fun allReady(): Boolean = + entries.value.let { list -> list.isNotEmpty() && list.all { it.ui.status == ComposerAttachmentStatus.Ready } } + + /** True while any chip is Uploading or Failed — send must wait or resolve. */ + fun hasUnsettled(): Boolean = + entries.value.any { it.ui.status != ComposerAttachmentStatus.Ready } + + /** Add a prepared pick to the tray and start its upload. */ + fun add(prepared: PreparedAttachment) { + val ui = ComposerAttachmentUi( + id = prepared.id, + filename = prepared.filename, + mimeType = prepared.mimeType, + sizeBytes = prepared.sizeBytes, + previewBytes = prepared.previewBytes, + status = ComposerAttachmentStatus.Uploading, + ) + entries.update { it + Entry(ui, bytes = prepared.bytes) } + upload(prepared.id, prepared.filename, prepared.mimeType, prepared.bytes) + } + + /** Failed chip tap: re-fire the upload with the retained bytes. */ + fun retry(id: String) { + var payload: Entry? = null + entries.update { list -> + val entry = list.firstOrNull { + it.ui.id == id && it.ui.status == ComposerAttachmentStatus.Failed && it.bytes != null + } ?: return@update list + payload = entry + list.map { + if (it.ui.id == id) Entry(it.ui.copy(status = ComposerAttachmentStatus.Uploading), bytes = it.bytes) + else it + } + } + val entry = payload ?: return + upload(id, entry.ui.filename, entry.ui.mimeType, entry.bytes!!) + } + + /** + * Drop a chip. An already-uploaded file is deleted best-effort; an + * in-flight upload deletes its result on completion (see [upload]). + */ + fun remove(id: String) { + var removed: Entry? = null + entries.update { list -> + removed = list.firstOrNull { it.ui.id == id } + list.filterNot { it.ui.id == id } + } + removed?.path?.let { path -> + scope.launch { runCatching { api.deleteUpload(sessionId, path) } } + } + } + + /** + * Take every Ready chip as send metadata, clearing them from the tray + * (unsettled chips stay put — the ViewModel guards against calling with + * any pending, but a race can settle one to Failed in between). + * + * @return the metadata list, or null when nothing was ready. + */ + fun consume(): List? { + var taken: List = emptyList() + entries.update { list -> + taken = list.filter { it.ui.status == ComposerAttachmentStatus.Ready && it.path != null } + list - taken.toSet() + } + if (taken.isEmpty()) return null + return taken.map { entry -> + AttachmentMetadata( + id = entry.ui.id, + filename = entry.ui.filename, + mimeType = entry.ui.mimeType, + size = entry.ui.sizeBytes, + path = entry.path!!, + previewUrl = entry.ui.previewBytes?.let { AttachmentPolicy.dataUrl("image/jpeg", it) }, + ) + } + } + + /** + * Leaving the chat for good (ViewModel holder `onCleared`): un-sent + * uploads are orphans on the hub — delete them best-effort on a detached + * scope, because the owning scope is being cancelled right after (same + * pattern as the draft flush). Attachments are NOT part of drafts v1. + */ + @OptIn(DelicateCoroutinesApi::class) + fun discardAllDetached() { + var dropped: List = emptyList() + entries.update { list -> + dropped = list + emptyList() + } + val paths = dropped.mapNotNull { it.path } + if (paths.isEmpty()) return + (detachedCleanupScope ?: GlobalScope).launch(Dispatchers.IO) { + paths.forEach { path -> runCatching { api.deleteUpload(sessionId, path) } } + } + } + + private fun upload(id: String, filename: String, mimeType: String, bytes: ByteArray) { + scope.launch { + val base64 = withContext(encodeDispatcher) { Base64.getEncoder().encodeToString(bytes) } + val path = try { + val response = api.uploadFile(sessionId, filename, base64, mimeType) + if (response.success) response.path else null + } catch (cancellation: CancellationException) { + throw cancellation + } catch (_: Exception) { + null + } + + var applied = false + entries.update { list -> + applied = list.any { it.ui.id == id } + if (!applied) list + else list.map { entry -> + when { + entry.ui.id != id -> entry + // Success: drop the payload bytes — only the preview stays. + path != null -> Entry(entry.ui.copy(status = ComposerAttachmentStatus.Ready), path = path) + else -> Entry(entry.ui.copy(status = ComposerAttachmentStatus.Failed), bytes = entry.bytes) + } + } + } + // Removed while uploading: the hub file just became an orphan. + if (!applied && path != null) { + runCatching { api.deleteUpload(sessionId, path) } + } + } + } +} diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/UserTextBlockView.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/UserTextBlockView.kt index cbaacfd3..21a943c7 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/UserTextBlockView.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/UserTextBlockView.kt @@ -1,12 +1,15 @@ package app.hapi.companion.feature.chat.blocks +import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.shape.RoundedCornerShape @@ -14,14 +17,19 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import app.hapi.companion.feature.chat.LocalChatInteractions +import app.hapi.companion.feature.chat.attachments.PreviewImage +import app.hapi.companion.feature.chat.attachments.rememberPreviewImage import app.hapi.companion.ui.theme.HapiTheme import app.hapi.protocol.chat.ChatAttachment import app.hapi.protocol.chat.UserTextBlock @@ -29,7 +37,10 @@ import app.hapi.protocol.chat.UserTextBlock /** * Operator prompt: right-aligned bubble (whitespace preserved — prompts are * not rendered as markdown, matching the web user bubble), attachments as - * chips, failed-send hint when a snapshot restored a failed optimistic row. + * image thumbnails (decoded from the wire `previewUrl` data URL — both + * Android- and web-sent messages carry one, and optimistic rows do too, so + * thumbnails appear instantly on send) or filename chips, and a failed-send + * tap-to-retry hint (B-M3f upgrades the former chips-only rendering). */ @Composable fun UserTextBlockView(block: UserTextBlock, modifier: Modifier = Modifier) { @@ -52,8 +63,9 @@ fun UserTextBlockView(block: UserTextBlock, modifier: Modifier = Modifier) { Column( modifier = Modifier.padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp), + horizontalAlignment = Alignment.End, ) { - attachments.forEach { AttachmentChip(it) } + attachments.forEach { AttachmentView(it) } } } } @@ -81,6 +93,40 @@ fun UserTextBlockView(block: UserTextBlock, modifier: Modifier = Modifier) { } } +/** + * One bubble attachment: image mimes with a decodable `previewUrl` render a + * thumbnail (web `MessageAttachments` split); everything else — plus decode + * failures — falls back to the filename chip. + */ +@Composable +private fun AttachmentView(attachment: ChatAttachment) { + val isImage = attachment.mimeType.startsWith("image/") + if (!isImage || attachment.previewUrl == null) { + AttachmentChip(attachment) + return + } + val preview by rememberPreviewImage(attachment.previewUrl) + when (val state = preview) { + is PreviewImage.Ready -> Image( + bitmap = state.bitmap, + contentDescription = attachment.filename, + contentScale = ContentScale.Fit, + alignment = Alignment.CenterEnd, + modifier = Modifier + .heightIn(max = 180.dp) + .clip(RoundedCornerShape(10.dp)), + ) + // Sized placeholder while decoding keeps the bubble from jumping. + PreviewImage.Loading -> Surface( + color = MaterialTheme.colorScheme.surface.copy(alpha = 0.4f), + shape = RoundedCornerShape(10.dp), + ) { + Spacer(modifier = Modifier.size(width = 120.dp, height = 90.dp)) + } + PreviewImage.Unavailable -> AttachmentChip(attachment) + } +} + @Composable private fun AttachmentChip(attachment: ChatAttachment) { Surface( diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/composer/ChatComposer.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/composer/ChatComposer.kt index 4a0f2111..d70aace6 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/composer/ChatComposer.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/composer/ChatComposer.kt @@ -1,18 +1,20 @@ package app.hapi.companion.feature.chat.composer import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.Image +import androidx.compose.foundation.clickable import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape @@ -35,33 +37,31 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import app.hapi.companion.feature.chat.ComposerUiState +import app.hapi.companion.feature.chat.attachments.ComposerAttachmentStatus +import app.hapi.companion.feature.chat.attachments.ComposerAttachmentUi +import app.hapi.companion.feature.chat.attachments.rememberChipThumbnail import app.hapi.companion.ui.theme.HapiTheme import app.hapi.companion.ui.theme.hapi import app.hapi.protocol.wire.SlashCommand import kotlinx.coroutines.delay /** - * A pending (M4) attachment chip — the row renders only when non-empty, so - * the M4 upload flow can light it up without composer surgery. - */ -data class ComposerAttachment( - val filename: String, - val mimeType: String, -) - -/** - * The chat input bar (B-M3a, extended in B-M3ce): multiline text field + * The chat input bar (B-M3a, extended in B-M3ce/B-M3f): multiline text field * (Enter = newline, mobile default), a send button whose long-press offers * "Send & steer" while a turn is active, an abort button during thinking, * a mic button for press-to-toggle dictation (recording chip with elapsed - * time + cancel while capturing), and a slash-command dropdown that opens - * while the text is a lone `/token`. Attachments remain an M4 seam. + * time + cancel while capturing), a slash-command dropdown that opens while + * the text is a lone `/token`, and the attachment tray: a "+" button opening + * the picker sheet plus per-attachment chips (uploading spinner → thumbnail / + * failed tap-to-retry, ✕ removes). */ @OptIn(ExperimentalFoundationApi::class) @Composable @@ -72,7 +72,10 @@ fun ChatComposer( onSendSteer: () -> Unit, onAbort: () -> Unit, modifier: Modifier = Modifier, - attachments: List = emptyList(), + attachments: List = emptyList(), + onAddAttachment: (() -> Unit)? = null, + onAttachmentRetry: (String) -> Unit = {}, + onAttachmentRemove: (String) -> Unit = {}, slashSuggestions: List = emptyList(), onSlashCommandSelected: (SlashCommand) -> Unit = {}, /** null ⇒ dictation unavailable (no controller wired) — mic button hidden. */ @@ -90,25 +93,18 @@ fun ChatComposer( ) } if (attachments.isNotEmpty()) { - Row( + LazyRow( modifier = Modifier .fillMaxWidth() .padding(bottom = 6.dp), horizontalArrangement = Arrangement.spacedBy(6.dp), ) { - attachments.forEach { attachment -> - Surface( - color = MaterialTheme.colorScheme.surfaceContainerHigh, - shape = RoundedCornerShape(8.dp), - ) { - Text( - text = "📎 ${attachment.filename}", - style = MaterialTheme.typography.labelMedium, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), - ) - } + items(attachments, key = { it.id }) { attachment -> + ComposerAttachmentChip( + attachment = attachment, + onRetry = { onAttachmentRetry(attachment.id) }, + onRemove = { onAttachmentRemove(attachment.id) }, + ) } } } @@ -121,6 +117,9 @@ fun ChatComposer( ) } Row(verticalAlignment = Alignment.Bottom) { + if (onAddAttachment != null) { + AddAttachmentButton(onClick = onAddAttachment) + } OutlinedTextField( value = state.text, onValueChange = onTextChange, @@ -136,12 +135,133 @@ fun ChatComposer( if (state.canSteer) { AbortButton(onAbort) } - SendButton(state = state, onSend = onSend, onSendSteer = onSendSteer) + SendButton(state = state, attachments = attachments, onSend = onSend, onSendSteer = onSendSteer) } } } } +// ---------------------------------------------------------- attachments -- + +/** + * One tray chip: 36 dp thumb (image preview / MIME glyph, spinner while + * uploading), filename + status line, ✕ to remove. A failed chip tints error + * and taps to retry. + */ +@Composable +private fun ComposerAttachmentChip( + attachment: ComposerAttachmentUi, + onRetry: () -> Unit, + onRemove: () -> Unit, +) { + val failed = attachment.status == ComposerAttachmentStatus.Failed + Surface( + color = if (failed) { + MaterialTheme.colorScheme.errorContainer + } else { + MaterialTheme.colorScheme.surfaceContainerHigh + }, + contentColor = if (failed) { + MaterialTheme.colorScheme.onErrorContainer + } else { + MaterialTheme.colorScheme.onSurface + }, + shape = RoundedCornerShape(10.dp), + onClick = { if (failed) onRetry() }, + enabled = failed, + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(start = 6.dp, top = 6.dp, bottom = 6.dp), + ) { + ChipThumb(attachment) + Column(modifier = Modifier.padding(start = 8.dp).widthIn(max = 132.dp)) { + Text( + text = attachment.filename, + style = MaterialTheme.typography.labelMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + text = when (attachment.status) { + ComposerAttachmentStatus.Uploading -> "Uploading…" + ComposerAttachmentStatus.Failed -> "Failed — tap to retry" + ComposerAttachmentStatus.Ready -> formatChipSize(attachment.sizeBytes) + }, + style = MaterialTheme.typography.labelSmall, + color = if (failed) MaterialTheme.colorScheme.error else MaterialTheme.hapi.hint, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + Text( + text = "✕", + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.hapi.hint, + modifier = Modifier + .clip(CircleShape) + .clickable(onClick = onRemove) + .padding(horizontal = 10.dp, vertical = 8.dp), + ) + } + } +} + +@Composable +private fun ChipThumb(attachment: ComposerAttachmentUi) { + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .size(36.dp) + .clip(RoundedCornerShape(8.dp)), + ) { + val thumbnail = rememberChipThumbnail(attachment.previewBytes) + if (thumbnail != null) { + Image( + bitmap = thumbnail, + contentDescription = attachment.filename, + contentScale = ContentScale.Crop, + modifier = Modifier + .size(36.dp) + .graphicsLayer { + alpha = if (attachment.status == ComposerAttachmentStatus.Uploading) 0.4f else 1f + }, + ) + } else { + Surface(color = MaterialTheme.colorScheme.surfaceContainerHighest, modifier = Modifier.size(36.dp)) {} + Text(text = if (attachment.mimeType.startsWith("image/")) "🖼" else "📎", fontSize = 15.sp) + } + if (attachment.status == ComposerAttachmentStatus.Uploading) { + CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp) + } + } +} + +/** `12.3 MB` / `456 KB` / `789 B` chip size label. */ +internal fun formatChipSize(bytes: Long): String = when { + bytes >= 1024 * 1024 -> "%.1f MB".format(bytes / (1024.0 * 1024.0)) + bytes >= 1024 -> "%.0f KB".format(bytes / 1024.0) + else -> "$bytes B" +} + +/** The "+" button opening the attachment picker sheet. */ +@Composable +private fun AddAttachmentButton(onClick: () -> Unit) { + Surface( + color = MaterialTheme.colorScheme.surfaceContainerHigh, + contentColor = MaterialTheme.colorScheme.onSurfaceVariant, + shape = CircleShape, + onClick = onClick, + modifier = Modifier + .padding(end = 6.dp, bottom = 4.dp) + .size(44.dp), + ) { + Box(contentAlignment = Alignment.Center) { + Text(text = "+", fontSize = 22.sp) + } + } +} + // -------------------------------------------------------- slash dropdown -- /** @@ -301,12 +421,18 @@ private fun AbortButton(onAbort: () -> Unit) { @Composable private fun SendButton( state: ComposerUiState, + attachments: List, onSend: () -> Unit, onSendSteer: () -> Unit, ) { var steerMenuOpen by remember { mutableStateOf(false) } val hasText = state.text.isNotBlank() - val enabled = hasText && !state.isSending + // Attachments gate the send like the web: every chip must settle Ready + // (uploading waits, failed must be retried or removed); a ready tray + // allows an attachments-only send (wire: text or attachments required). + val attachmentsBusy = attachments.any { it.status != ComposerAttachmentStatus.Ready } + val attachmentsReady = attachments.isNotEmpty() && !attachmentsBusy + val enabled = (hasText || attachmentsReady) && !attachmentsBusy && !state.isSending Box( modifier = Modifier @@ -385,13 +511,63 @@ private fun ChatComposerPreview() { ChatComposer( state = ComposerUiState(text = "Sending…", isSending = true, canSteer = false), onTextChange = {}, onSend = {}, onSendSteer = {}, onAbort = {}, - attachments = listOf(ComposerAttachment("screenshot.png", "image/png")), + onAddAttachment = {}, + attachments = listOf( + ComposerAttachmentUi( + id = "a1", + filename = "screenshot.png", + mimeType = "image/png", + sizeBytes = 1_843_200, + previewBytes = null, + status = ComposerAttachmentStatus.Ready, + ), + ), ) } } } } +@Preview(showBackground = true) +@Composable +private fun AttachmentChipsComposerPreview() { + HapiTheme { + Surface { + ChatComposer( + state = ComposerUiState(text = "", isSending = false, canSteer = false), + onTextChange = {}, onSend = {}, onSendSteer = {}, onAbort = {}, + onAddAttachment = {}, + attachments = listOf( + ComposerAttachmentUi( + id = "up", + filename = "IMG_20260818_133702.jpg", + mimeType = "image/jpeg", + sizeBytes = 2_411_000, + previewBytes = null, + status = ComposerAttachmentStatus.Uploading, + ), + ComposerAttachmentUi( + id = "ok", + filename = "build-log.txt", + mimeType = "text/plain", + sizeBytes = 48_500, + previewBytes = null, + status = ComposerAttachmentStatus.Ready, + ), + ComposerAttachmentUi( + id = "bad", + filename = "trace.bin", + mimeType = "application/octet-stream", + sizeBytes = 9_000_000, + previewBytes = null, + status = ComposerAttachmentStatus.Failed, + ), + ), + ) + } + } +} + @Preview(showBackground = true) @Composable private fun RecordingComposerPreview() { diff --git a/android/app/src/main/res/xml/attachment_file_paths.xml b/android/app/src/main/res/xml/attachment_file_paths.xml new file mode 100644 index 00000000..054c8eb4 --- /dev/null +++ b/android/app/src/main/res/xml/attachment_file_paths.xml @@ -0,0 +1,9 @@ + + + + + diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelInteractionTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelInteractionTest.kt index 4d1f6ce2..ac6a4243 100644 --- a/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelInteractionTest.kt +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelInteractionTest.kt @@ -1,5 +1,7 @@ package app.hapi.companion.feature.chat +import app.hapi.companion.feature.chat.attachments.ComposerAttachmentStatus +import app.hapi.companion.feature.chat.attachments.PreparedAttachment import app.hapi.companion.feature.chat.composer.ChatDrafts import app.hapi.data.api.ApiError import app.hapi.data.api.ChatSessionApi @@ -19,8 +21,11 @@ import app.hapi.protocol.wire.AgentState import app.hapi.protocol.wire.AgentStateRequest import app.hapi.protocol.wire.ApprovePermissionRequest import app.hapi.protocol.wire.CancelMessageResponse +import app.hapi.protocol.chat.NormalizedMessage +import app.hapi.protocol.chat.normalizeDecryptedMessage import app.hapi.protocol.wire.CodexModelsResponse import app.hapi.protocol.wire.DecryptedMessage +import app.hapi.protocol.wire.DeleteUploadResponse import app.hapi.protocol.wire.HapiJson import app.hapi.protocol.wire.Machine import app.hapi.protocol.wire.MessagesPage @@ -37,11 +42,13 @@ import app.hapi.protocol.wire.SlashCommand import app.hapi.protocol.wire.SlashCommandsResponse import app.hapi.protocol.wire.SteerQueuedMessageResponse import app.hapi.protocol.wire.SyncEvent +import app.hapi.protocol.wire.UploadFileResponse import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.Flow @@ -242,6 +249,28 @@ private class RecordingChatApi : ChatSessionApi { slashCommandsCalls.value += 1 return slashCommandsResult } + + var uploadResult: UploadFileResponse = UploadFileResponse(success = true, path = "/uploads/ok") + + /** When set, uploads park here (in-flight chip tests). */ + var uploadGate: CompletableDeferred? = null + val uploadCalls = MutableStateFlow>(emptyList()) + override suspend fun uploadFile( + sessionId: String, + filename: String, + contentBase64: String, + mimeType: String, + ): UploadFileResponse { + uploadCalls.value = uploadCalls.value + filename + uploadGate?.await() + return uploadResult + } + + val deleteUploadCalls = MutableStateFlow>(emptyList()) + override suspend fun deleteUpload(sessionId: String, path: String): DeleteUploadResponse { + deleteUploadCalls.value = deleteUploadCalls.value + path + return DeleteUploadResponse(success = true) + } } private class FakeDrafts : ChatDrafts { @@ -466,6 +495,148 @@ class ChatViewModelInteractionTest { assertTrue(oldRows.isEmpty()) } + // --------------------------------------------------------- attachments -- + + private fun preparedShot(id: String = "att-1", filename: String = "shot.jpg") = PreparedAttachment( + id = id, + filename = filename, + mimeType = "image/jpeg", + bytes = byteArrayOf(1, 2, 3), + previewBytes = byteArrayOf(7, 7), + ) + + private suspend fun InteractionHarness.awaitAttachmentsReady() { + viewModel.attachments.items.first { list -> + list.isNotEmpty() && list.all { it.status == ComposerAttachmentStatus.Ready } + } + } + + @Test + fun `send rides ready attachments as wire metadata and the optimistic row carries them`() = runTest { + val harness = InteractionHarness(this) + harness.viewModel.start() + + harness.viewModel.attachments.add(preparedShot()) + harness.awaitAttachmentsReady() + harness.viewModel.setComposerText("see the screenshot") + harness.viewModel.sendMessage() + + val (_, request) = harness.api.sendCalls.first { it.isNotEmpty() }.single() + val metadata = request.attachments!!.single() + assertEquals("att-1", metadata.id) + assertEquals("shot.jpg", metadata.filename) + assertEquals("image/jpeg", metadata.mimeType) + assertEquals(3L, metadata.size) + assertEquals("/uploads/ok", metadata.path) + assertTrue(metadata.previewUrl!!.startsWith("data:image/jpeg;base64,")) + assertNull(request.scheduledAt) + + // The optimistic row carries the attachments — thumbnails render + // before the SSE echo replaces it. + val row = harness.window().state.first { state -> + state.messages.any { it.localId == "local-1" && it.status == MessageStatus.Sent } + }.messages.single() + val normalized = normalizeDecryptedMessage(row.wire) as NormalizedMessage.User + assertEquals(listOf("shot.jpg"), normalized.attachments?.map { it.filename }) + + // The tray was consumed by the send (items is derived — await it). + harness.viewModel.attachments.items.first { it.isEmpty() } + } + + @Test + fun `attachments-only send posts empty text (wire allows text OR attachments)`() = runTest { + val harness = InteractionHarness(this) + harness.viewModel.start() + + harness.viewModel.attachments.add(preparedShot()) + harness.awaitAttachmentsReady() + harness.viewModel.sendMessage() + + val (_, request) = harness.api.sendCalls.first { it.isNotEmpty() }.single() + assertEquals("", request.text) + assertEquals(1, request.attachments!!.size) + } + + @Test + fun `send refuses while an attachment upload is unsettled`() = runTest { + val harness = InteractionHarness(this) + harness.api.uploadGate = CompletableDeferred() + harness.viewModel.start() + + var notice: String? = null + val collector = launch(start = CoroutineStart.UNDISPATCHED) { + notice = harness.viewModel.events + .filterIsInstance() + .first() + .message + } + + harness.viewModel.attachments.add(preparedShot()) + harness.api.uploadCalls.first { it.isNotEmpty() } // parked on the gate + harness.viewModel.setComposerText("hold on") + harness.viewModel.sendMessage() + collector.join() + + assertTrue(notice!!.contains("uploading")) + assertTrue(harness.api.sendCalls.value.isEmpty()) + // The draft text and the chip both survive the refused send. + assertEquals("hold on", harness.viewModel.composer.first { it.text.isNotEmpty() }.text) + assertEquals(1, harness.viewModel.attachments.items.first { it.isNotEmpty() }.size) + + // Once the upload settles, the same send goes through with metadata. + harness.api.uploadGate!!.complete(Unit) + harness.awaitAttachmentsReady() + harness.viewModel.sendMessage() + val (_, request) = harness.api.sendCalls.first { it.isNotEmpty() }.single() + assertEquals("hold on", request.text) + assertEquals(1, request.attachments!!.size) + } + + @Test + fun `failed send retry re-sends the same attachments from the wire row`() = runTest { + val harness = InteractionHarness(this) + harness.api.sendFailures += RuntimeException("boom") + harness.viewModel.start() + + harness.viewModel.attachments.add(preparedShot()) + harness.awaitAttachmentsReady() + harness.viewModel.setComposerText("try again") + harness.viewModel.sendMessage() + harness.window().state.first { state -> + state.messages.any { it.localId == "local-1" && it.status == MessageStatus.Failed } + } + + harness.viewModel.retryFailedMessage("local-1") + harness.window().state.first { state -> + state.messages.any { it.localId == "local-1" && it.status == MessageStatus.Sent } + } + + val requests = harness.api.sendCalls.value.map { it.second } + assertEquals(2, requests.size) + // Attachments round-tripped through the optimistic row's wire JSON. + assertEquals(requests[0].attachments, requests[1].attachments) + assertEquals("/uploads/ok", requests[1].attachments!!.single().path) + } + + @Test + fun `removing a ready chip deletes the hub upload and discard drops the rest`() = runTest { + val harness = InteractionHarness(this) + harness.viewModel.start() + + harness.viewModel.attachments.add(preparedShot(id = "att-1", filename = "a.jpg")) + harness.awaitAttachmentsReady() + harness.viewModel.attachments.remove("att-1") + harness.api.deleteUploadCalls.first { it.size == 1 } + harness.viewModel.attachments.items.first { it.isEmpty() } + + // Un-sent leftovers are discarded when the screen goes away for good. + harness.viewModel.attachments.add(preparedShot(id = "att-2", filename = "b.jpg")) + harness.awaitAttachmentsReady() + harness.viewModel.discardAttachments() + harness.api.deleteUploadCalls.first { it.size == 2 } + harness.viewModel.attachments.items.first { it.isEmpty() } + } + // ---------------------------------------------------------- queued bar -- /** Server-echoed queued row (id != localId, explicit `invokedAt: null`). */ diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelTest.kt index cb5f9316..973afc30 100644 --- a/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelTest.kt +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelTest.kt @@ -159,6 +159,15 @@ private class FakeMessagesApi : ChatSessionApi { CodexModelsResponse(success = false, error = "not scripted") override suspend fun getSlashCommands(sessionId: String): app.hapi.protocol.wire.SlashCommandsResponse = app.hapi.protocol.wire.SlashCommandsResponse(success = false, error = "not scripted") + override suspend fun uploadFile( + sessionId: String, + filename: String, + contentBase64: String, + mimeType: String, + ): app.hapi.protocol.wire.UploadFileResponse = + app.hapi.protocol.wire.UploadFileResponse(success = true, path = "/uploads/$filename") + override suspend fun deleteUpload(sessionId: String, path: String): app.hapi.protocol.wire.DeleteUploadResponse = + app.hapi.protocol.wire.DeleteUploadResponse(success = true) } private fun page( diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/chat/attachments/AttachmentPolicyTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/attachments/AttachmentPolicyTest.kt new file mode 100644 index 00000000..accd6d74 --- /dev/null +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/attachments/AttachmentPolicyTest.kt @@ -0,0 +1,127 @@ +package app.hapi.companion.feature.chat.attachments + +import app.hapi.companion.feature.chat.attachments.AttachmentPolicy.Plan +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNull + +private const val MB = 1024L * 1024 + +/** Pure compression/sizing decisions (B-M3f) — the preparer defers to these. */ +class AttachmentPolicyTest { + + // ------------------------------------------------------------- planFor -- + + @Test + fun `small files of any type keep their original bytes`() { + assertEquals(Plan.KeepOriginal, AttachmentPolicy.planFor("image/jpeg", 3 * MB)) + assertEquals(Plan.KeepOriginal, AttachmentPolicy.planFor("application/pdf", 20 * MB)) + assertEquals(Plan.KeepOriginal, AttachmentPolicy.planFor("text/plain", 10)) + } + + @Test + fun `images over the 4MB threshold are compressed`() { + assertEquals(Plan.CompressImage, AttachmentPolicy.planFor("image/jpeg", 5 * MB)) + assertEquals(Plan.CompressImage, AttachmentPolicy.planFor("image/png", 12 * MB)) + assertEquals(Plan.CompressImage, AttachmentPolicy.planFor("image/webp", 4 * MB + 1)) + // Case-insensitive mime match. + assertEquals(Plan.CompressImage, AttachmentPolicy.planFor("image/JPEG", 5 * MB)) + } + + @Test + fun `images at exactly the threshold stay original`() { + assertEquals(Plan.KeepOriginal, AttachmentPolicy.planFor("image/jpeg", 4 * MB)) + } + + @Test + fun `oversized recompressible images are still compressed, not rejected`() { + // Downscaling brings any camera photo far under the cap; the preparer + // re-checks the compressed size against the 50 MB contract. + assertEquals(Plan.CompressImage, AttachmentPolicy.planFor("image/jpeg", 60 * MB)) + } + + @Test + fun `oversized non-recompressible files are rejected`() { + assertEquals(Plan.Reject, AttachmentPolicy.planFor("application/zip", 51 * MB)) + assertEquals(Plan.Reject, AttachmentPolicy.planFor("video/mp4", 200 * MB)) + // GIF recompression would drop animation — over-cap GIFs reject. + assertEquals(Plan.Reject, AttachmentPolicy.planFor("image/gif", 51 * MB)) + } + + @Test + fun `files at exactly 50MB pass`() { + assertEquals(Plan.KeepOriginal, AttachmentPolicy.planFor("application/zip", 50 * MB)) + } + + @Test + fun `gifs under the cap keep original bytes regardless of size`() { + assertEquals(Plan.KeepOriginal, AttachmentPolicy.planFor("image/gif", 30 * MB)) + } + + @Test + fun `read cap allows oversized sources only for recompressible images`() { + assertEquals(AttachmentPolicy.MAX_IMAGE_SOURCE_BYTES, AttachmentPolicy.readCapFor("image/jpeg")) + assertEquals(AttachmentPolicy.MAX_UPLOAD_BYTES, AttachmentPolicy.readCapFor("image/gif")) + assertEquals(AttachmentPolicy.MAX_UPLOAD_BYTES, AttachmentPolicy.readCapFor("video/mp4")) + assertEquals(AttachmentPolicy.MAX_UPLOAD_BYTES, AttachmentPolicy.readCapFor("application/pdf")) + } + + // ------------------------------------------------------- bitmap sizing -- + + @Test + fun `sampleSizeFor picks the largest power of two keeping the longest edge above target`() { + assertEquals(1, AttachmentPolicy.sampleSizeFor(1024, 768, 2048)) + assertEquals(1, AttachmentPolicy.sampleSizeFor(4000, 3000, 2048)) + // 8192/4 = 2048 — decoded edge lands exactly on target, never below it. + assertEquals(4, AttachmentPolicy.sampleSizeFor(8192, 6144, 2048)) + assertEquals(8, AttachmentPolicy.sampleSizeFor(16384, 100, 2048)) + assertEquals(1, AttachmentPolicy.sampleSizeFor(0, 0, 2048)) + } + + @Test + fun `scaledDimensions clamps the longest edge and preserves aspect`() { + assertEquals(2048 to 1536, AttachmentPolicy.scaledDimensions(4096, 3072, 2048)) + assertEquals(1024 to 2048, AttachmentPolicy.scaledDimensions(2048, 4096, 2048)) + // Under the cap: untouched. + assertEquals(640 to 480, AttachmentPolicy.scaledDimensions(640, 480, 2048)) + // Degenerate aspect never collapses to zero. + assertEquals(2048 to 1, AttachmentPolicy.scaledDimensions(100_000, 10, 2048)) + } + + // ---------------------------------------------------------- filenames -- + + @Test + fun `compressedFilename swaps the extension to jpg`() { + assertEquals("shot.jpg", AttachmentPolicy.compressedFilename("shot.png")) + assertEquals("IMG_0001.jpg", AttachmentPolicy.compressedFilename("IMG_0001.HEIC")) + assertEquals("photo.jpg", AttachmentPolicy.compressedFilename("photo.jpg")) + assertEquals("archive.tar.jpg", AttachmentPolicy.compressedFilename("archive.tar.png")) + assertEquals("noext.jpg", AttachmentPolicy.compressedFilename("noext")) + // A leading dot is a hidden-file name, not an extension. + assertEquals(".hidden.jpg", AttachmentPolicy.compressedFilename(".hidden")) + } + + // ----------------------------------------------------------- data URLs -- + + @Test + fun `dataUrl and bytesFromDataUrl round-trip`() { + val bytes = byteArrayOf(1, 2, 3, 4, 5) + val url = AttachmentPolicy.dataUrl("image/jpeg", bytes) + assertEquals("data:image/jpeg;base64,AQIDBAU=", url) + assertContentEquals(bytes, AttachmentPolicy.bytesFromDataUrl(url)) + } + + @Test + fun `web-authored data URLs parse regardless of mime`() { + assertEquals("iVBORw0K", AttachmentPolicy.base64FromDataUrl("data:image/png;base64,iVBORw0K")) + } + + @Test + fun `non data URLs and malformed payloads return null`() { + assertNull(AttachmentPolicy.base64FromDataUrl("https://example.com/a.png")) + assertNull(AttachmentPolicy.base64FromDataUrl("data:image/png,plain")) + assertNull(AttachmentPolicy.base64FromDataUrl("data:image/png;base64,")) + assertNull(AttachmentPolicy.bytesFromDataUrl("data:image/png;base64,!!!not-base64!!!")) + } +} diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/chat/attachments/ComposerAttachmentsTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/attachments/ComposerAttachmentsTest.kt new file mode 100644 index 00000000..8d83e02d --- /dev/null +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/attachments/ComposerAttachmentsTest.kt @@ -0,0 +1,196 @@ +package app.hapi.companion.feature.chat.attachments + +import app.hapi.data.api.AttachmentUploadApi +import app.hapi.protocol.wire.DeleteUploadResponse +import app.hapi.protocol.wire.UploadFileResponse +import java.util.Base64 +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.runTest + +private const val SESSION = "sess-att" + +/** Scriptable two-method fake for the upload seam. */ +private class FakeUploadApi : AttachmentUploadApi { + class UploadCall(val sessionId: String, val filename: String, val contentBase64: String, val mimeType: String) + + val uploads = MutableStateFlow>(emptyList()) + val deletes = MutableStateFlow>(emptyList()) + + /** Results consumed per call; empty ⇒ success with a derived path. */ + val results = ArrayDeque>() + + /** When set, uploads park here until completed (in-flight state tests). */ + var gate: CompletableDeferred? = null + + override suspend fun uploadFile( + sessionId: String, + filename: String, + contentBase64: String, + mimeType: String, + ): UploadFileResponse { + uploads.value = uploads.value + UploadCall(sessionId, filename, contentBase64, mimeType) + gate?.await() + val scripted = results.removeFirstOrNull() + ?: Result.success(UploadFileResponse(success = true, path = "/uploads/$filename")) + return scripted.getOrThrow() + } + + override suspend fun deleteUpload(sessionId: String, path: String): DeleteUploadResponse { + deletes.value = deletes.value + path + return DeleteUploadResponse(success = true) + } +} + +private fun prepared( + id: String = "att-1", + filename: String = "shot.jpg", + mimeType: String = "image/jpeg", + bytes: ByteArray = byteArrayOf(10, 20, 30), + previewBytes: ByteArray? = byteArrayOf(1, 2), +) = PreparedAttachment(id = id, filename = filename, mimeType = mimeType, bytes = bytes, previewBytes = previewBytes) + +class ComposerAttachmentsTest { + + private fun harness(scope: kotlinx.coroutines.CoroutineScope, api: FakeUploadApi) = + ComposerAttachments( + api = api, + sessionId = SESSION, + scope = scope, + detachedCleanupScope = scope, + ) + + @Test + fun `add uploads immediately with the exact base64 payload and settles Ready`() = runTest { + val api = FakeUploadApi() + val tray = harness(backgroundScope, api) + + tray.add(prepared(bytes = byteArrayOf(10, 20, 30))) + + val chip = tray.items.first { it.size == 1 && it[0].status == ComposerAttachmentStatus.Ready }[0] + assertEquals("shot.jpg", chip.filename) + assertEquals(3L, chip.sizeBytes) + + val call = api.uploads.value.single() + assertEquals(SESSION, call.sessionId) + assertEquals("shot.jpg", call.filename) + assertEquals("image/jpeg", call.mimeType) + assertEquals(Base64.getEncoder().encodeToString(byteArrayOf(10, 20, 30)), call.contentBase64) + assertTrue(tray.allReady()) + } + + @Test + fun `consume maps Ready chips to metadata with a preview data URL and clears the tray`() = runTest { + val api = FakeUploadApi() + val tray = harness(backgroundScope, api) + tray.add(prepared(previewBytes = byteArrayOf(9, 9))) + tray.items.first { it.size == 1 && it[0].status == ComposerAttachmentStatus.Ready } + + val metadata = tray.consume()!!.single() + + assertEquals("att-1", metadata.id) + assertEquals("shot.jpg", metadata.filename) + assertEquals("image/jpeg", metadata.mimeType) + assertEquals(3L, metadata.size) + assertEquals("/uploads/shot.jpg", metadata.path) + assertEquals(AttachmentPolicy.dataUrl("image/jpeg", byteArrayOf(9, 9)), metadata.previewUrl) + assertTrue(tray.items.first { it.isEmpty() }.isEmpty()) + assertNull(tray.consume()) + } + + @Test + fun `upload failure settles Failed and retry re-uploads to Ready`() = runTest { + val api = FakeUploadApi() + api.results += Result.failure(RuntimeException("boom")) + val tray = harness(backgroundScope, api) + + tray.add(prepared()) + tray.items.first { it.size == 1 && it[0].status == ComposerAttachmentStatus.Failed } + assertTrue(tray.hasUnsettled()) + + tray.retry("att-1") + tray.items.first { it.size == 1 && it[0].status == ComposerAttachmentStatus.Ready } + assertEquals(2, api.uploads.value.size) + assertEquals(api.uploads.value[0].contentBase64, api.uploads.value[1].contentBase64) + } + + @Test + fun `success=false responses settle Failed too`() = runTest { + val api = FakeUploadApi() + api.results += Result.success(UploadFileResponse(success = false, error = "disk full")) + val tray = harness(backgroundScope, api) + + tray.add(prepared()) + tray.items.first { it.size == 1 && it[0].status == ComposerAttachmentStatus.Failed } + } + + @Test + fun `removing a Ready chip deletes the hub upload best-effort`() = runTest { + val api = FakeUploadApi() + val tray = harness(backgroundScope, api) + tray.add(prepared()) + tray.items.first { it.size == 1 && it[0].status == ComposerAttachmentStatus.Ready } + + tray.remove("att-1") + + tray.items.first { it.isEmpty() } + assertEquals(listOf("/uploads/shot.jpg"), api.deletes.first { it.isNotEmpty() }) + } + + @Test + fun `removing a chip mid-upload deletes the orphan once the upload lands`() = runTest { + val api = FakeUploadApi() + val gate = CompletableDeferred() + api.gate = gate + val tray = harness(backgroundScope, api) + + tray.add(prepared()) + api.uploads.first { it.isNotEmpty() } // upload started, parked on the gate + tray.remove("att-1") + tray.items.first { it.isEmpty() } + gate.complete(Unit) + + // The late-arriving path is deleted, and the chip never reappears. + assertEquals(listOf("/uploads/shot.jpg"), api.deletes.first { it.isNotEmpty() }) + assertTrue(tray.items.value.isEmpty()) + } + + @Test + fun `consume takes only Ready chips and leaves unsettled ones in the tray`() = runTest { + val api = FakeUploadApi() + api.results += Result.failure(RuntimeException("boom")) + val tray = harness(backgroundScope, api) + tray.add(prepared(id = "bad", filename = "bad.bin", mimeType = "application/octet-stream", previewBytes = null)) + tray.items.first { list -> list.any { it.status == ComposerAttachmentStatus.Failed } } + tray.add(prepared(id = "good", filename = "good.jpg")) + tray.items.first { list -> list.any { it.id == "good" && it.status == ComposerAttachmentStatus.Ready } } + + val metadata = tray.consume()!! + + assertEquals(listOf("good"), metadata.map { it.id }) + assertEquals(listOf("bad"), tray.items.first { it.size == 1 }.map { it.id }) + } + + @Test + fun `discardAllDetached deletes every uploaded path and empties the tray`() = runTest { + val api = FakeUploadApi() + val tray = harness(backgroundScope, api) + tray.add(prepared(id = "a", filename = "a.jpg")) + tray.add(prepared(id = "b", filename = "b.jpg")) + tray.items.first { list -> list.size == 2 && list.all { it.status == ComposerAttachmentStatus.Ready } } + + tray.discardAllDetached() + + assertEquals( + setOf("/uploads/a.jpg", "/uploads/b.jpg"), + api.deletes.first { it.size == 2 }.toSet(), + ) + // `items` is derived from the entries flow — await the propagation. + assertTrue(tray.items.first { it.isEmpty() }.isEmpty()) + } +} diff --git a/android/core/data/src/main/kotlin/app/hapi/data/api/ChatSessionApi.kt b/android/core/data/src/main/kotlin/app/hapi/data/api/ChatSessionApi.kt index 0dcf48f1..0daff609 100644 --- a/android/core/data/src/main/kotlin/app/hapi/data/api/ChatSessionApi.kt +++ b/android/core/data/src/main/kotlin/app/hapi/data/api/ChatSessionApi.kt @@ -3,10 +3,33 @@ package app.hapi.data.api import app.hapi.protocol.wire.ApprovePermissionRequest import app.hapi.protocol.wire.CancelMessageResponse import app.hapi.protocol.wire.CodexModelsResponse +import app.hapi.protocol.wire.DeleteUploadResponse import app.hapi.protocol.wire.ResumeSessionResponse import app.hapi.protocol.wire.SendMessageRequest import app.hapi.protocol.wire.SlashCommandsResponse import app.hapi.protocol.wire.SteerQueuedMessageResponse +import app.hapi.protocol.wire.UploadFileResponse + +/** + * Message-attachment upload seam (B-M3f). Split from [ChatSessionApi] so the + * composer attachment controller can be tested against a two-method fake. + */ +interface AttachmentUploadApi { + /** + * `POST /api/sessions/:id/upload` — JSON + base64 (NOT multipart), + * ≤ 50 MB decoded → 413. The returned `path` becomes + * `AttachmentMetadata.path` in the send-message body. + */ + suspend fun uploadFile( + sessionId: String, + filename: String, + contentBase64: String, + mimeType: String, + ): UploadFileResponse + + /** `POST /api/sessions/:id/upload/delete` — best-effort orphan cleanup. */ + suspend fun deleteUpload(sessionId: String, path: String): DeleteUploadResponse +} /** * The endpoint seam the chat interaction layer (B-M3ab) drives — send / @@ -14,9 +37,10 @@ import app.hapi.protocol.wire.SteerQueuedMessageResponse * session config. [HapiApi] is the production implementation; ViewModel tests * substitute a scripted fake and assert the exact request bodies. * - * Extends [MessagesApi] so one fake covers the window store's transport too. + * Extends [MessagesApi] so one fake covers the window store's transport too, + * and [AttachmentUploadApi] for the composer attachment flow (B-M3f). */ -interface ChatSessionApi : MessagesApi { +interface ChatSessionApi : MessagesApi, AttachmentUploadApi { /** `POST /api/sessions/:id/messages` — `{ok:true}`; the row arrives via SSE. */ suspend fun sendMessage(sessionId: String, message: SendMessageRequest) diff --git a/android/core/data/src/main/kotlin/app/hapi/data/api/HapiApi.kt b/android/core/data/src/main/kotlin/app/hapi/data/api/HapiApi.kt index a7c85081..b9c6fcdf 100644 --- a/android/core/data/src/main/kotlin/app/hapi/data/api/HapiApi.kt +++ b/android/core/data/src/main/kotlin/app/hapi/data/api/HapiApi.kt @@ -520,7 +520,7 @@ class HapiApi( * multipart), ≤ 50 MB decoded → 413. The returned `path` feeds the * `attachments` of send-message. */ - suspend fun uploadFile( + override suspend fun uploadFile( sessionId: String, filename: String, contentBase64: String, @@ -533,7 +533,7 @@ class HapiApi( ) /** `POST /api/sessions/:id/upload/delete`. */ - suspend fun deleteUpload(sessionId: String, path: String): DeleteUploadResponse = + override suspend fun deleteUpload(sessionId: String, path: String): DeleteUploadResponse = request( "POST", url("api", "sessions", sessionId, "upload", "delete").build(), diff --git a/android/core/data/src/test/kotlin/app/hapi/data/api/HapiApiTest.kt b/android/core/data/src/test/kotlin/app/hapi/data/api/HapiApiTest.kt index 4e9907bf..e8d19029 100644 --- a/android/core/data/src/test/kotlin/app/hapi/data/api/HapiApiTest.kt +++ b/android/core/data/src/test/kotlin/app/hapi/data/api/HapiApiTest.kt @@ -166,6 +166,45 @@ class HapiApiTest { ) } + @Test + fun `upload posts json base64 (not multipart) and yields the hub path`() { + server.enqueue(ok("""{"success":true,"path":"/tmp/uploads/shot.jpg"}""")) + + val response = runBlocking { + session.api.uploadFile("s1", "shot.jpg", "QUJDRA==", "image/jpeg") + } + + assertTrue(response.success) + assertEquals("/tmp/uploads/shot.jpg", response.path) + val request = server.takeRequest() + assertEquals("/api/sessions/s1/upload", request.path) + assertEquals("POST", request.method) + assertTrue(request.getHeader("Content-Type")!!.startsWith("application/json")) + assertEquals( + buildJsonObject { + put("filename", "shot.jpg") + put("content", "QUJDRA==") + put("mimeType", "image/jpeg") + }, + Json.parseToJsonElement(request.body.readUtf8()).jsonObject, + ) + } + + @Test + fun `delete upload posts the path`() { + server.enqueue(ok("""{"success":true}""")) + + val response = runBlocking { session.api.deleteUpload("s1", "/tmp/uploads/shot.jpg") } + + assertTrue(response.success) + val request = server.takeRequest() + assertEquals("/api/sessions/s1/upload/delete", request.path) + assertEquals( + buildJsonObject { put("path", "/tmp/uploads/shot.jpg") }, + Json.parseToJsonElement(request.body.readUtf8()).jsonObject, + ) + } + @Test fun `approve body supports nested answers`() { server.enqueue(ok("""{"ok":true}"""))