From 01cdec11797fe511fb2e5632accb05c5e512f265 Mon Sep 17 00:00:00 2001 From: weishu Date: Thu, 29 Oct 2026 21:17:19 +0800 Subject: [PATCH] feat(android): share files and text to sessions --- android/README.md | 7 + .../feature/share/ShareActivityTest.kt | 60 ++++ .../feature/share/ShareIntakeTest.kt | 110 +++++++ .../feature/share/SharePickerTest.kt | 121 +++++++ android/app/src/main/AndroidManifest.xml | 10 + .../kotlin/app/hapi/companion/MainActivity.kt | 16 + .../kotlin/app/hapi/companion/Navigation.kt | 213 ++++++++++++- .../kotlin/app/hapi/companion/di/AppGraph.kt | 30 ++ .../hapi/companion/di/DataStoreChatDrafts.kt | 29 +- .../companion/feature/chat/ChatViewModel.kt | 86 ++++- .../chat/attachments/AttachmentPreparer.kt | 16 +- .../feature/chat/composer/ChatComposer.kt | 9 +- .../feature/chat/composer/ChatDrafts.kt | 9 + .../feature/share/AndroidShareIntake.kt | 67 ++++ .../companion/feature/share/ShareInbox.kt | 301 ++++++++++++++++++ .../companion/feature/share/ShareScreen.kt | 183 +++++++++++ .../feature/share/ShareTargetController.kt | 55 ++++ .../app/src/main/res/values-ru/strings.xml | 28 ++ .../src/main/res/values-zh-rCN/strings.xml | 28 ++ android/app/src/main/res/values/strings.xml | 28 ++ .../companion/di/DataStoreChatDraftsTest.kt | 54 ++++ .../chat/ChatViewModelInteractionTest.kt | 112 ++++++- .../companion/feature/share/ShareInboxTest.kt | 192 +++++++++++ .../share/ShareTargetControllerTest.kt | 83 +++++ docs/guide/native-apps.md | 15 + 25 files changed, 1846 insertions(+), 16 deletions(-) create mode 100644 android/app/src/androidTest/kotlin/app/hapi/companion/feature/share/ShareActivityTest.kt create mode 100644 android/app/src/androidTest/kotlin/app/hapi/companion/feature/share/ShareIntakeTest.kt create mode 100644 android/app/src/androidTest/kotlin/app/hapi/companion/feature/share/SharePickerTest.kt create mode 100644 android/app/src/main/kotlin/app/hapi/companion/feature/share/AndroidShareIntake.kt create mode 100644 android/app/src/main/kotlin/app/hapi/companion/feature/share/ShareInbox.kt create mode 100644 android/app/src/main/kotlin/app/hapi/companion/feature/share/ShareScreen.kt create mode 100644 android/app/src/main/kotlin/app/hapi/companion/feature/share/ShareTargetController.kt create mode 100644 android/app/src/test/kotlin/app/hapi/companion/di/DataStoreChatDraftsTest.kt create mode 100644 android/app/src/test/kotlin/app/hapi/companion/feature/share/ShareInboxTest.kt create mode 100644 android/app/src/test/kotlin/app/hapi/companion/feature/share/ShareTargetControllerTest.kt diff --git a/android/README.md b/android/README.md index 41f264af..e2474693 100644 --- a/android/README.md +++ b/android/README.md @@ -27,6 +27,13 @@ differences, pairing and features currently available through the web. - **Composer:** optimistic send, queue/steer where supported, drafts and attachments uploaded on selection. Slash suggestions combine session metadata and the slash-command RPC; the skills `$` picker has no UI. +- **Incoming shares:** Android Share → HAPI accepts single/multiple files, + captions, text and links. Choose a session on the current or another paired + hub; stopped sessions require explicit restore before upload. Content is + added to the existing composer for manual sending. Private, no-backup + staging survives pairing and process recreation until handoff, with a + 24-hour pending-content lifetime. Once imported, attachments follow the + ordinary composer lifecycle (they are not persisted as attachment drafts). - **Dictation:** provider discovery on chat entry picks the first `standard`-capable provider. The microphone stays hidden until one is available. First use requests `RECORD_AUDIO`; `MediaRecorder` records diff --git a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/share/ShareActivityTest.kt b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/share/ShareActivityTest.kt new file mode 100644 index 00000000..a80390b5 --- /dev/null +++ b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/share/ShareActivityTest.kt @@ -0,0 +1,60 @@ +package app.hapi.companion.feature.share + +import android.content.Intent +import androidx.test.core.app.ActivityScenario +import androidx.test.platform.app.InstrumentationRegistry +import app.hapi.companion.HapiApp +import app.hapi.companion.MainActivity +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test + +/** Uses an unpaired test install; no credentials or network server needed. */ +class ShareActivityTest { + private val context = InstrumentationRegistry.getInstrumentation().targetContext + private val graph get() = (context.applicationContext as HapiApp).appGraph + + @Before fun prepare() = runBlocking { + withTimeout(45_000) { graph.awaitReady() } + assertTrue("Run on an unpaired test install", graph.hubRegistry.state.value.hubs.isEmpty()) + graph.shareInbox.batches.value.forEach { graph.shareInbox.discard(it.id) } + } + + @After fun cleanup() = runBlocking { + graph.shareInbox.batches.value.forEach { graph.shareInbox.discard(it.id) } + } + + @Test fun coldAndWarmSharesSurviveRecreationWithoutReplayingTheLaunchingIntent() { + val initial = Intent(context, MainActivity::class.java).apply { + action = Intent.ACTION_SEND + type = "text/plain" + putExtra(Intent.EXTRA_TEXT, "cold share") + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } + ActivityScenario.launch(initial).use { scenario -> + val first = runBlocking { + withTimeout(45_000) { graph.shareInbox.batches.first { it.size == 1 }.single() } + } + assertEquals("cold share", first.text) + scenario.recreate() + assertEquals(listOf(first.id), graph.shareInbox.batches.value.map { it.id }) + scenario.onActivity { activity -> + activity.startActivity(Intent(activity, MainActivity::class.java).apply { + action = Intent.ACTION_SEND + type = "text/plain" + putExtra(Intent.EXTRA_TEXT, "warm share") + addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) + }) + } + runBlocking { withTimeout(45_000) { graph.shareInbox.batches.first { it.size == 2 } } } + scenario.recreate() + assertEquals(listOf("cold share", "warm share"), graph.shareInbox.batches.value.map { it.text }) + assertEquals(first.id, graph.shareInbox.batches.value.first().id) + assertTrue(graph.shareInbox.batches.value.all { it.target == null }) + } + } +} diff --git a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/share/ShareIntakeTest.kt b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/share/ShareIntakeTest.kt new file mode 100644 index 00000000..f2987dae --- /dev/null +++ b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/share/ShareIntakeTest.kt @@ -0,0 +1,110 @@ +package app.hapi.companion.feature.share + +import android.content.ClipData +import android.content.Intent +import android.net.Uri +import androidx.core.content.FileProvider +import androidx.test.platform.app.InstrumentationRegistry +import app.hapi.companion.feature.chat.attachments.AttachmentPreparer +import app.hapi.companion.feature.chat.attachments.PrepareResult +import java.io.File +import java.util.UUID +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.junit.Assert.* +import org.junit.Test + +class ShareIntakeTest { + private val context = InstrumentationRegistry.getInstrumentation().targetContext + + @Test fun streamAndClipUrisAreDeduplicatedWithoutDuplicatingTheCaption() { + val first = Uri.parse("content://source/first") + val second = Uri.parse("content://source/second") + val intent = Intent(Intent.ACTION_SEND_MULTIPLE).apply { + type = "*/*" + putParcelableArrayListExtra(Intent.EXTRA_STREAM, arrayListOf(first, second)) + putExtra(Intent.EXTRA_TEXT, "explain these files") + clipData = ClipData.newUri(context.contentResolver, "files", first).apply { + addItem(ClipData.Item(second)) + addItem(ClipData.Item("explain these files")) + } + } + assertEquals(SharedInput("explain these files", listOf(first.toString(), second.toString())), parseSharedIntent(intent)) + } + + @Test fun singleStreamClipOnlyAndTextOnlySharesUseTheSameParser() { + val uri = Uri.parse("content://source/first") + assertEquals(listOf(uri.toString()), parseSharedIntent(Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_STREAM, uri))!!.uris) + assertEquals(listOf(uri.toString()), parseSharedIntent(Intent(Intent.ACTION_SEND).apply { + clipData = ClipData.newUri(context.contentResolver, "files", uri) + })!!.uris) + assertEquals("https://example.com/page", parseSharedIntent(Intent(Intent.ACTION_SEND).apply { + clipData = ClipData.newPlainText("link", "https://example.com/page") + })!!.text) + assertNull(parseSharedIntent(Intent(Intent.ACTION_VIEW, uri))) + assertTrue(parseSharedIntent(Intent(Intent.ACTION_SEND))!!.isEmpty) + } + + @Test fun concreteIntentMimeTypeIsAvailableWhenAProviderHasNoMetadata() { + val uri = Uri.parse("content://missing.provider/file") + val parsed = parseSharedIntent(Intent(Intent.ACTION_SEND).apply { + type = "image/png" + putExtra(Intent.EXTRA_STREAM, uri) + })!! + assertEquals("image/png", parsed.mimeType) + assertEquals("image/png", ContentResolverShareReader(context.contentResolver).details(uri.toString(), parsed.mimeType).mimeType) + assertNull(parseSharedIntent(Intent(Intent.ACTION_SEND).setType("image/*"))!!.mimeType) + } + + @Test fun localStagingSurvivesSourceDeletionAndPreservesMetadataForThePreparer() = runBlocking { + val directory = File(context.cacheDir, "attachments").apply { mkdirs() } + val original = File(directory, "share-intake-${UUID.randomUUID()}.txt").apply { writeText("shared bytes") } + val root = File(context.noBackupFilesDir, "share-intake-test-${UUID.randomUUID()}") + val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + try { + val reader = ContentResolverShareReader(context.contentResolver) + val uri = FileProvider.getUriForFile(context, "${context.packageName}.attachments", original) + val inbox = ShareInbox(root, reader, scope) + val id = inbox.receive(SharedInput("caption", listOf(uri.toString()))) + val batch = withTimeout(45_000) { inbox.batches.first { it.singleOrNull()?.canImport == true }.single() } + val file = batch.files.single() + assertEquals(original.name, file.filename) + assertEquals("text/plain", file.mimeType) + assertTrue(original.delete()) + val restored = ShareInbox(root, reader, scope) + restored.load() + val prepared = AttachmentPreparer(context).prepare(restored.file(id, file.id), file.filename, file.mimeType, file.id) + assertTrue(prepared is PrepareResult.Ready) + val attachment = (prepared as PrepareResult.Ready).attachment + assertEquals(file.id, attachment.id) + assertEquals(original.name, attachment.filename) + assertArrayEquals("shared bytes".toByteArray(), attachment.bytes) + } finally { + scope.cancel() + original.delete() + root.deleteRecursively() + } + } + + @Test fun unsupportedFileUrisStayVisibleAsErrorsAndAreNeverOpened() = runBlocking { + val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + val root = File(context.noBackupFilesDir, "share-intake-test-${UUID.randomUUID()}") + try { + val uri = Uri.parse("file:///data/data/${context.packageName}/files/private.txt") + val parsed = parseSharedIntent(Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_STREAM, uri))!! + val inbox = ShareInbox(root, ContentResolverShareReader(context.contentResolver), scope) + inbox.receive(parsed) + val batch = withTimeout(45_000) { inbox.batches.first { it.firstOrNull()?.files?.singleOrNull()?.status == SharedFileStatus.Unreadable }.single() } + assertFalse(batch.canImport) + assertFalse(inbox.file(batch.id, batch.files.single().id).exists()) + } finally { + scope.cancel() + root.deleteRecursively() + } + } +} diff --git a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/share/SharePickerTest.kt b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/share/SharePickerTest.kt new file mode 100644 index 00000000..ad907284 --- /dev/null +++ b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/share/SharePickerTest.kt @@ -0,0 +1,121 @@ +package app.hapi.companion.feature.share + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsEnabled +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performTextInput +import androidx.test.platform.app.InstrumentationRegistry +import app.hapi.companion.R +import app.hapi.companion.feature.sessions.SessionListViewModel +import app.hapi.companion.ui.theme.HapiTheme +import app.hapi.data.sse.SseSubscriptionKey +import app.hapi.data.store.LastSeenStore +import app.hapi.data.store.MachineListStore +import app.hapi.data.store.SessionListStore +import app.hapi.protocol.wire.Machine +import app.hapi.protocol.wire.ReopenSessionResponse +import app.hapi.protocol.wire.SessionSummary +import app.hapi.protocol.wire.SessionSummaryMetadata +import app.hapi.protocol.wire.SyncEvent +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.MutableStateFlow +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test + +private class PickerSessions : SessionListStore { + override val sessions = MutableStateFlow(listOf( + SessionSummary("active", true, hasConversationContent = true, + metadata = SessionSummaryMetadata(name = "Active target", path = "/repo/active")), + SessionSummary("stopped", false, hasConversationContent = true, + metadata = SessionSummaryMetadata(name = "Stopped target", path = "/repo/stopped")), + )) + override suspend fun refresh() {} + override fun scheduleRefresh() {} + override suspend fun fullResync() {} + override fun applySessionEvent(scope: SseSubscriptionKey, event: SyncEvent) {} + override suspend fun setPinMode(sessionId: String, mode: String): Unit = error("not a picker action") + override suspend fun archiveSession(sessionId: String): Unit = error("not a picker action") + override suspend fun renameSession(sessionId: String, name: String): Unit = error("not a picker action") + override suspend fun deleteSession(sessionId: String): Unit = error("not a picker action") + override suspend fun reopenSession(sessionId: String): ReopenSessionResponse = error("use the gateway") +} + +private class PickerMachines : MachineListStore { + override val machines = MutableStateFlow>(emptyList()) + override suspend fun refresh() {} + override fun scheduleRefresh() {} + override fun applyMachineEvent(event: SyncEvent.MachineUpdated) {} +} + +class SharePickerTest { + @get:Rule val compose = createComposeRule() + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val context = InstrumentationRegistry.getInstrumentation().targetContext + private var reopens = 0 + private var switched: String? = null + private val controller = ShareTargetController(object : ShareSessionGateway { + override suspend fun isActive(sessionId: String) = sessionId == "active" + override suspend fun reopen(sessionId: String): String { reopens++; return "replacement" } + }, scope) + private val sessions = SessionListViewModel(PickerSessions(), PickerMachines(), LastSeenStore(scope), scope) + private var batch by mutableStateOf(PendingShare("batch", 1, "shared caption", emptyList())) + + private fun mount() { + compose.setContent { + HapiTheme { + ShareScreen(batch, "https://first.example", listOf("https://first.example", "https://second.example"), + sessions, controller, onSwitchHub = { switched = it }, onRetryFile = {}, + onRemoveFile = { id -> batch = batch.copy(files = batch.files.filterNot { it.id == id }) }, onCancel = {}) + } + } + compose.waitUntil(45_000) { sessions.uiState.value.rows.size == 2 } + } + + @After fun cleanup() { scope.cancel() } + + @Test fun stoppedTargetNeedsExplicitConfirmationAndUsesTheReturnedId() { + mount() + compose.onNodeWithTag("share-session-stopped").performClick() + compose.waitUntil(45_000) { controller.state.value.confirmSessionId != null } + compose.onNodeWithText(context.getString(R.string.share_restore_message)).assertIsDisplayed() + assertEquals(0, reopens) + compose.onNodeWithText(context.getString(R.string.share_restore_confirm)).performClick() + compose.waitUntil(45_000) { controller.state.value.resolvedSessionId != null } + assertEquals("replacement", controller.state.value.resolvedSessionId) + assertEquals(1, reopens) + } + + @Test fun failedFileBlocksSelectionUntilTheUserRemovesIt() { + batch = batch.copy(files = listOf(SharedFile("file", "content://source", "bad.pdf", status = SharedFileStatus.Unreadable))) + mount() + compose.onNodeWithTag("share-session-active").assertIsNotEnabled() + compose.onNodeWithText(context.getString(R.string.share_remove)).performClick() + compose.onNodeWithTag("share-session-active").assertIsEnabled().performClick() + compose.waitUntil(45_000) { controller.state.value.resolvedSessionId != null } + assertEquals("active", controller.state.value.resolvedSessionId) + assertEquals(0, reopens) + } + + @Test fun pickerOffersPairedHubsAndExistingSessionSearch() { + mount() + compose.onNodeWithTag("share-hub").performClick() + compose.onNodeWithText("second.example").performClick() + compose.runOnIdle { assertEquals("https://second.example", switched) } + compose.onNodeWithTag("share-search").performTextInput("Stopped") + compose.waitUntil(45_000) { sessions.uiState.value.rows.size == 1 } + compose.onNodeWithTag("share-session-stopped").assertIsDisplayed() + assertEquals("stopped", sessions.uiState.value.rows.single().id) + } +} diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 206b9f6a..2b93bc28 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -57,6 +57,16 @@ + + + + + + + + + + diff --git a/android/app/src/main/kotlin/app/hapi/companion/MainActivity.kt b/android/app/src/main/kotlin/app/hapi/companion/MainActivity.kt index cf4e5f46..baa811cb 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/MainActivity.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/MainActivity.kt @@ -20,6 +20,7 @@ import app.hapi.companion.di.LocalAppGraph import app.hapi.companion.fcm.PushNotifications import app.hapi.companion.feature.settings.ThemeMode import app.hapi.companion.feature.settings.ThemeSettings +import app.hapi.companion.feature.share.parseSharedIntent import app.hapi.companion.push.PushBinding import app.hapi.companion.ui.theme.HapiTheme import app.hapi.protocol.pairing.BindLink @@ -72,6 +73,7 @@ class MainActivity : AppCompatActivity() { // (or re-trigger a notification navigation). handleBindIntent(intent) handleOpenSessionIntent(intent) + handleShareIntent(intent) } setContent { // Follow-system default renders for the first frames while the @@ -98,6 +100,20 @@ class MainActivity : AppCompatActivity() { super.onNewIntent(intent) handleBindIntent(intent) handleOpenSessionIntent(intent) + handleShareIntent(intent) + } + + private fun handleShareIntent(intent: Intent?) { + val input = intent?.let(::parseSharedIntent) ?: return + appGraph.receiveShare(input) + // The inbox owns the handoff now. Do not replay external extras if + // Android later recreates this activity from its current Intent. + setIntent(Intent(intent).apply { + removeExtra(Intent.EXTRA_STREAM) + removeExtra(Intent.EXTRA_TEXT) + removeExtra(Intent.EXTRA_HTML_TEXT) + clipData = null + }) } private fun handleBindIntent(intent: Intent?) { 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 1199c15b..c46dd522 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/Navigation.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/Navigation.kt @@ -1,8 +1,12 @@ package app.hapi.companion import android.content.Context +import androidx.activity.compose.BackHandler import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Surface +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect @@ -10,8 +14,10 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.collectAsState import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource import androidx.lifecycle.ViewModel import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavBackStackEntry @@ -22,6 +28,7 @@ import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.navigation import androidx.navigation.compose.rememberNavController +import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.navArgument import app.hapi.companion.di.AppGraph import app.hapi.companion.di.HubGraph @@ -30,6 +37,7 @@ import app.hapi.companion.di.viewModelFactory import app.hapi.companion.feature.chat.ChatMedia import app.hapi.companion.feature.chat.ChatHost import app.hapi.companion.feature.chat.ChatViewModel +import app.hapi.companion.feature.chat.attachments.AttachmentPreparer import app.hapi.companion.feature.chat.composer.DictationController import app.hapi.companion.feature.chat.composer.HapiDictationApi import app.hapi.companion.feature.chat.composer.MediaRecorderDictation @@ -57,6 +65,10 @@ import app.hapi.companion.feature.scratchlist.ScratchlistMedia import app.hapi.companion.feature.scratchlist.ScratchlistScreen import app.hapi.companion.feature.scratchlist.ScratchlistViewModel import app.hapi.companion.feature.sessions.SessionListViewModel +import app.hapi.companion.feature.share.ShareScreen +import app.hapi.companion.feature.share.ShareSessionGateway +import app.hapi.companion.feature.share.ShareTarget +import app.hapi.companion.feature.share.ShareTargetController import app.hapi.companion.feature.settings.SettingsGeneralScreen import app.hapi.companion.feature.settings.SettingsHubScreen import app.hapi.companion.feature.settings.SettingsViewModel @@ -72,9 +84,12 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import kotlin.coroutines.cancellation.CancellationException object Routes { const val HOME = "home" + const val SHARE = "share/{requestId}" + fun share(requestId: String) = "share/$requestId" /** Read-only chat (B-M2d2). */ const val CHAT = "chat/{sessionId}" @@ -165,6 +180,12 @@ fun HapiNavigation() { val navController = rememberNavController() val registryState by graph.hubRegistry.state.collectAsState() val activeHubGraph by graph.activeHubGraph.collectAsState() + val shares by graph.shareInbox.batches.collectAsState() + val pendingShare = shares.firstOrNull() + val shareIntakeFailed by graph.shareIntakeFailed.collectAsState() + val currentEntry by navController.currentBackStackEntryAsState() + val navigationScope = rememberCoroutineScope() + val composedChat = remember { mutableStateOf(null) } val startDestination = remember { if (graph.hubRegistry.activeHubUrl == null) Routes.PAIRING else Routes.HOME } @@ -225,7 +246,109 @@ fun HapiNavigation() { } } + // Pending payloads outlive pairing and HubGraph replacement. A target is + // persisted before navigation, so process restoration follows the same path. + LaunchedEffect(pendingShare?.id, pendingShare?.target, shares.size, currentEntry, activeHubGraph, registryState.activeHubUrl) { + val share = pendingShare ?: return@LaunchedEffect + if (shares.size > 1 || currentEntry == null) return@LaunchedEffect + if (currentEntry?.destination?.hierarchy?.any { it.route == Routes.PAIRING } == true) return@LaunchedEffect + val hubUrl = registryState.activeHubUrl + if (hubUrl == null) { + navController.navigateClearingBackStack(Routes.PAIRING) + return@LaunchedEffect + } + val target = share.target + if (target != null) { + if (target.hubUrl !in registryState.hubs) { + graph.runShareAction { graph.shareInbox.clearTarget(share.id) } + return@LaunchedEffect + } + if (hubUrl != target.hubUrl) { + graph.hubRegistry.setActiveHub(target.hubUrl) + return@LaunchedEffect + } + if (activeHubGraph?.hubUrl != hubUrl) return@LaunchedEffect + if (currentEntry?.arguments?.getString("sessionId") == target.sessionId) return@LaunchedEffect + // In particular, return to the very same chat holder when sharing + // to the chat that was already open: preserve its attachment tray. + if (!navController.popBackStack(Routes.chat(target.sessionId), inclusive = false)) { + navController.navigate(Routes.chat(target.sessionId)) { + popUpTo(Routes.HOME) + launchSingleTop = true + } + } + } else if (currentEntry?.destination?.route != Routes.SHARE || + currentEntry?.arguments?.getString("requestId") != share.id) { + graph.runShareAction { + composedChat.value?.takeIf { it.hubUrl == hubUrl }?.viewModel?.persistComposerDraft() + } + navController.navigate(Routes.share(share.id)) { + if (currentEntry?.destination?.route == Routes.SHARE) popUpTo(Routes.SHARE) { inclusive = true } + launchSingleTop = true + } + } + } + + if (shareIntakeFailed) { + AlertDialog( + onDismissRequest = { graph.shareIntakeFailed.value = false }, + title = { Text(stringResource(R.string.share_error_title)) }, + text = { Text(stringResource(R.string.share_receive_failed)) }, + confirmButton = { TextButton(onClick = { graph.shareIntakeFailed.value = false }) { + Text(stringResource(R.string.share_ok)) + } }, + ) + } else if (shares.size > 1) { + AlertDialog( + onDismissRequest = { navigationScope.launch { graph.runShareAction { + shares.firstOrNull()?.let { graph.shareInbox.keepOnly(it.id) } + } } }, + title = { Text(stringResource(R.string.share_replace_title)) }, + text = { Text(stringResource(R.string.share_replace_message)) }, + confirmButton = { TextButton(onClick = { + navigationScope.launch { graph.runShareAction { + shares.lastOrNull()?.let { graph.shareInbox.keepOnly(it.id) } + } } + }) { Text(stringResource(R.string.share_replace_current)) } }, + dismissButton = { TextButton(onClick = { + navigationScope.launch { graph.runShareAction { + shares.firstOrNull()?.let { graph.shareInbox.keepOnly(it.id) } + } } + }) { Text(stringResource(R.string.share_keep_current)) } }, + ) + } + NavHost(navController = navController, startDestination = startDestination) { + composable(Routes.SHARE, arguments = listOf(navArgument("requestId") { type = NavType.StringType })) { entry -> + val batch = shares.find { it.id == entry.arguments?.getString("requestId") } ?: return@composable + val hubGraph = activeHubGraph?.takeIf { it.hubUrl == registryState.activeHubUrl } ?: return@composable + val holder = viewModel(factory = viewModelFactory { ShareViewModelHolder() }) + val models = holder.forHub(hubGraph) + val selection by models.target.state.collectAsState() + LaunchedEffect(selection.resolvedSessionId, batch.id, hubGraph) { + val sessionId = selection.resolvedSessionId ?: return@LaunchedEffect + if (graph.hubRegistry.activeHubUrl != hubGraph.hubUrl || graph.activeHubGraph.value !== hubGraph) return@LaunchedEffect + try { + graph.shareInbox.setTarget(batch.id, ShareTarget(hubGraph.hubUrl, sessionId)) + models.target.consumed() + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + graph.shareIntakeFailed.value = true + } + } + ShareScreen( + batch = batch, hubUrl = hubGraph.hubUrl, pairedHubs = registryState.hubs, + sessions = models.sessions, target = models.target, + onSwitchHub = { hub -> navigationScope.launch { graph.hubRegistry.setActiveHub(hub) } }, + onRetryFile = { id -> navigationScope.launch { graph.runShareAction { graph.shareInbox.retry(batch.id, id) } } }, + onRemoveFile = { id -> navigationScope.launch { graph.runShareAction { graph.shareInbox.removeFile(batch.id, id) } } }, + onCancel = { navigationScope.launch { graph.runShareAction { + graph.shareInbox.discard(batch.id) + navController.popBackStack() + } } }, + ) + } composable(Routes.HOME) { val activeHubUrl = registryState.activeHubUrl ?: return@composable val hubGraph = activeHubGraph ?: return@composable @@ -301,7 +424,7 @@ fun HapiNavigation() { arguments = listOf(navArgument("sessionId") { type = NavType.StringType }), ) { entry -> val sessionId = entry.arguments?.getString("sessionId") ?: return@composable - val hubGraph = activeHubGraph ?: return@composable + val hubGraph = activeHubGraph?.takeIf { it.hubUrl == registryState.activeHubUrl } ?: return@composable val appContext = LocalContext.current.applicationContext // Feed the FCM suppress-when-open rule: while this chat is on @@ -320,6 +443,36 @@ fun HapiNavigation() { key = "chat:${hubGraph.hubUrl}:$sessionId", factory = viewModelFactory { ChatViewModelHolder(hubGraph, sessionId, appContext) }, ) + DisposableEffect(holder) { + composedChat.value = ComposedChat(hubGraph.hubUrl, holder.viewModel) + onDispose { + if (composedChat.value?.viewModel === holder.viewModel) composedChat.value = null + } + } + val assignedShare = pendingShare?.takeIf { it.target == ShareTarget(hubGraph.hubUrl, sessionId) } + val preparer = remember(appContext) { AttachmentPreparer(appContext) } + LaunchedEffect(holder, assignedShare?.id, shares.size) { + val batch = assignedShare ?: return@LaunchedEffect + if (shares.size > 1) return@LaunchedEffect + try { + holder.viewModel.importShare(batch, complete = { failure -> + if (failure == null) graph.shareInbox.discard(batch.id) + else graph.shareInbox.importFailed(batch.id, failure.fileId, failure.status) + }) { file -> + preparer.prepare(graph.shareInbox.file(batch.id, file.id), file.filename, file.mimeType, file.id) + } + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + graph.shareIntakeFailed.value = true + graph.runShareAction { graph.shareInbox.clearTarget(batch.id) } + } + } + val closeChat: () -> Unit = { navigationScope.launch { graph.runShareAction { + assignedShare?.let { graph.shareInbox.discard(it.id) } + navController.popBackStack() + } } } + BackHandler(enabled = assignedShare != null, onBack = closeChat) ChatHost( viewModel = holder.viewModel, media = remember(hubGraph, sessionId) { @@ -327,7 +480,7 @@ fun HapiNavigation() { hubGraph.generatedImageUrl(sessionId, imageId) } }, - onBack = { navController.popBackStack() }, + onBack = closeChat, onNavigateToSession = { supersededId -> // Resume/reopen handed the conversation to a different id: // replace this chat entry with the superseding session. @@ -518,8 +671,11 @@ fun HapiNavigation() { PairingScreen( state = state, prefill = prefill, - notice = notice, - onDismissNotice = { graph.pairingNotice.value = null }, + notice = notice ?: pendingShare?.let { stringResource(R.string.share_pair_first) }, + onDismissNotice = { + if (notice != null) graph.pairingNotice.value = null + else pendingShare?.let { batch -> navigationScope.launch { graph.runShareAction { graph.shareInbox.discard(batch.id) } } } + }, onScanQr = { navController.navigate(Routes.PAIRING_SCAN) }, onManualEntry = { navController.navigate(Routes.PAIRING_MANUAL) }, onPairPrefill = viewModel::pairFromPrefill, @@ -559,6 +715,55 @@ fun HapiNavigation() { } } +private data class ComposedChat(val hubUrl: String, val viewModel: ChatViewModel) + +private suspend fun AppGraph.runShareAction(action: suspend () -> Unit) { + try { + action() + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + shareIntakeFailed.value = true + } +} + +private data class ShareModels(val sessions: SessionListViewModel, val target: ShareTargetController) + +private class ShareViewModelHolder : ViewModel() { + private var graph: HubGraph? = null + private var scope: CoroutineScope? = null + private var models: ShareModels? = null + + fun forHub(hub: HubGraph): ShareModels { + models?.takeIf { graph === hub }?.let { return it } + models?.sessions?.stop() + scope?.cancel() + val nextScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + scope = nextScope + graph = hub + val gateway = object : ShareSessionGateway { + override suspend fun isActive(sessionId: String) = hub.sessionStore.loadSessionDetail(sessionId).active + override suspend fun reopen(sessionId: String): String { + val response = hub.sessionStore.reopenSession(sessionId) + if (response.sessionId != sessionId) { + hub.messageWindows.seed(sessionId, response.sessionId) + hub.chatDrafts.move(sessionId, response.sessionId) + } + return response.sessionId + } + } + return ShareModels( + SessionListViewModel(hub.sessionStore, hub.machineStore, hub.lastSeenStore, nextScope, hub.hubUrl), + ShareTargetController(gateway, nextScope), + ).also { models = it } + } + + override fun onCleared() { + models?.sessions?.stop() + scope?.cancel() + } +} + // ------------------------------------------------------ ViewModel holders -- /** diff --git a/android/app/src/main/kotlin/app/hapi/companion/di/AppGraph.kt b/android/app/src/main/kotlin/app/hapi/companion/di/AppGraph.kt index 95a99e75..a695bd9e 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/di/AppGraph.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/di/AppGraph.kt @@ -10,6 +10,10 @@ import app.hapi.companion.feature.pairing.PairingClientFactory import app.hapi.companion.feature.settings.AppLanguage import app.hapi.companion.feature.settings.LanguagePrefs import app.hapi.companion.feature.settings.ThemePrefs +import app.hapi.companion.feature.share.ContentResolverShareReader +import app.hapi.companion.feature.share.ShareInbox +import app.hapi.companion.feature.share.SharedInput +import java.io.File import app.hapi.data.push.EncryptedPrefsPushIdentityStore import app.hapi.data.push.PushIdentityManager import app.hapi.data.push.PushMessageDecoder @@ -79,6 +83,27 @@ class AppGraph(context: Context) { /** The protocol-configured Json (lenient, ignores unknown keys). */ val json: Json = HapiJson + val shareIntakeFailed = MutableStateFlow(false) + val shareInbox = ShareInbox(File(appContext.noBackupFilesDir, "share-inbox"), + ContentResolverShareReader(appContext.contentResolver), scope, + onFailure = { shareIntakeFailed.value = true }) + + fun receiveShare(input: SharedInput) { + if (input.isEmpty) { + shareIntakeFailed.value = true + return + } + scope.launch { + try { + shareInbox.receive(input) + } catch (cancelled: kotlinx.coroutines.CancellationException) { + throw cancelled + } catch (_: Exception) { + shareIntakeFailed.value = true + } + } + } + val hubRegistryStorage: HubRegistryStorage = DataStoreHubRegistryStorage(appContext.hapiDataStore) @@ -222,6 +247,11 @@ class AppGraph(context: Context) { /** Idempotent-enough for the single Application.onCreate call site. */ fun start() { scope.launch { + try { + shareInbox.load() + } catch (_: Exception) { + shareIntakeFailed.value = true + } hubRegistry.load() mutableReady.value = true // Roster is loaded: the registrar's first emission re-registers diff --git a/android/app/src/main/kotlin/app/hapi/companion/di/DataStoreChatDrafts.kt b/android/app/src/main/kotlin/app/hapi/companion/di/DataStoreChatDrafts.kt index 222d4324..f9e4e4b0 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/di/DataStoreChatDrafts.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/di/DataStoreChatDrafts.kt @@ -5,8 +5,11 @@ import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.stringPreferencesKey +import androidx.datastore.preferences.core.longPreferencesKey import androidx.datastore.preferences.preferencesDataStore import app.hapi.companion.feature.chat.composer.ChatDrafts +import app.hapi.companion.feature.chat.composer.appendSharedText +import app.hapi.companion.feature.share.ShareInbox import kotlinx.coroutines.flow.first /** @@ -46,7 +49,31 @@ class DataStoreChatDrafts( val draft = prefs[key(fromSessionId)] ?: return@edit prefs.remove(key(fromSessionId)) // Never clobber a draft already typed in the target session. - if (prefs[key(toSessionId)].isNullOrEmpty()) prefs[key(toSessionId)] = draft + if (prefs[key(toSessionId)].isNullOrEmpty()) { + prefs[key(toSessionId)] = draft + val prefix = "draftShare:$hubKey:$fromSessionId:" + prefs.asMap().filter { it.key.name.startsWith(prefix) }.forEach { (receipt, timestamp) -> + prefs[longPreferencesKey("draftShare:$hubKey:$toSessionId:${receipt.name.removePrefix(prefix)}")] = timestamp as Long + prefs.remove(receipt) + } + } } } + + override suspend fun appendSharedText(sessionId: String, requestId: String, currentText: String, text: String): String { + var result = currentText + dataStore.edit { prefs -> + val now = System.currentTimeMillis() + prefs.asMap().filter { + it.key.name.startsWith("draftShare:$hubKey:") && (it.value as? Long ?: Long.MAX_VALUE) < now - ShareInbox.RETENTION_MS + }.keys.forEach { prefs.remove(it) } + val receipt = longPreferencesKey("draftShare:$hubKey:$sessionId:$requestId") + if (prefs[receipt] == null) { + result = appendSharedText(currentText, text) + prefs[key(sessionId)] = result + prefs[receipt] = now + } + } + return result + } } 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 ae23c456..a07b9f13 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 @@ -2,6 +2,11 @@ package app.hapi.companion.feature.chat import androidx.annotation.MainThread import app.hapi.companion.feature.chat.attachments.ComposerAttachments +import app.hapi.companion.feature.chat.attachments.PrepareResult +import app.hapi.companion.feature.chat.composer.appendSharedText +import app.hapi.companion.feature.share.PendingShare +import app.hapi.companion.feature.share.SharedFile +import app.hapi.companion.feature.share.SharedFileStatus import app.hapi.companion.feature.chat.blocks.planProposalMarkdown import app.hapi.companion.feature.chat.composer.ChatDrafts import app.hapi.companion.feature.chat.composer.SlashCommands @@ -62,6 +67,8 @@ import java.util.UUID import java.util.concurrent.atomic.AtomicBoolean import kotlin.coroutines.cancellation.CancellationException import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -88,6 +95,8 @@ import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.transform import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.coroutines.yield import kotlinx.coroutines.flow.asStateFlow @@ -157,8 +166,11 @@ data class ComposerUiState( val canSteer: Boolean, /** Local focus intent; does not replace or send the draft. */ val focusRequest: Long = 0, + val isImportingShare: Boolean = false, ) +data class ShareImportFailure(val fileId: String, val status: SharedFileStatus) + /** One row of the queued-messages bar (uninvoked sends). */ data class QueuedRowUi( val id: String, @@ -402,6 +414,12 @@ class ChatViewModel( private val composerText = MutableStateFlow("") private val sendInFlight = MutableStateFlow(false) + private val importingShare = MutableStateFlow(false) + private val draftReady = CompletableDeferred() + private val importedShares = mutableSetOf() + private val importedShareTexts = mutableSetOf() + private val importedSharedFiles = mutableSetOf() + private val shareImportMutex = Mutex() /** * Composer attachment tray (B-M3f). The screen feeds prepared picks in @@ -491,12 +509,14 @@ class ChatViewModel( sendInFlight, sessionStateFlow(), composerFocusRequest, - ) { text, sending, session, focusRequest -> + importingShare, + ) { text, sending, session, focusRequest, importing -> ComposerUiState( text = text, isSending = sending, canSteer = session.thinking && session.active, focusRequest = focusRequest, + isImportingShare = importing, ) }.stateIn(scope, SharingStarted.Eagerly, ComposerUiState(text = "", isSending = false, canSteer = false)) @@ -828,6 +848,7 @@ class ChatViewModel( // ------------------------------------------------------------- composer -- fun setComposerText(text: String) { + if (importingShare.value) return // Fetch the RPC command list on the transition INTO slash mode (the // web refetches when the menu opens) — not on every keystroke, so a // wedged CLI cannot be hammered while the user types a command. @@ -843,6 +864,53 @@ class ChatViewModel( } } + /** Commit the latest keystrokes before a share picker can reopen this session under a new ID. */ + suspend fun persistComposerDraft() { + draftReady.await() + draftJob?.cancelAndJoin() + drafts?.save(sessionId, composerText.value) + } + + /** Caller is the chat entry's Main-thread effect; cancellation preserves the inbox batch. */ + suspend fun importShare( + share: PendingShare, + complete: suspend (ShareImportFailure?) -> Unit = {}, + prepare: suspend (SharedFile) -> PrepareResult, + ): ShareImportFailure? = shareImportMutex.withLock { + check(share.canImport) + importingShare.value = true + try { + if (share.id in importedShares) { + complete(null) + return@withLock null + } + draftReady.await() + draftJob?.cancelAndJoin() + if (share.text.isNotBlank() && share.id !in importedShareTexts) { + composerText.value = drafts?.appendSharedText(sessionId, share.id, composerText.value, share.text) + ?: appendSharedText(composerText.value, share.text) + importedShareTexts += share.id + } + for (file in share.files) { + if (file.id in importedSharedFiles) continue + when (val result = prepare(file)) { + is PrepareResult.Ready -> { + attachments.add(result.attachment) + importedSharedFiles += file.id + } + is PrepareResult.TooLarge -> return@withLock ShareImportFailure(file.id, SharedFileStatus.TooLarge).also { complete(it) } + is PrepareResult.Unreadable -> return@withLock ShareImportFailure(file.id, SharedFileStatus.Unreadable).also { complete(it) } + } + } + importedShares += share.id + complete(null) + composerFocusRequest.value += 1 + null + } finally { + importingShare.value = false + } + } + /** Dictation transcript arrived: append with a space separator (web `appendTranscript`). */ fun appendDictatedText(transcript: String) { setComposerText(appendTranscript(composerText.value, transcript)) @@ -923,7 +991,7 @@ class ChatViewModel( * Text may be empty when attachments exist (wire: text OR attachments). */ fun sendMessage(steer: Boolean = false) { - if (sendInFlight.value) return + if (sendInFlight.value || importingShare.value) return if (attachments.hasUnsettled()) { _events.tryEmit(ChatEvent.Notice(ChatNotice.AttachmentsUploading)) return @@ -1716,10 +1784,16 @@ class ChatViewModel( .distinctUntilChanged() private suspend fun restoreDraft() { - val store = drafts ?: return - val draft = runCatching { store.load(sessionId) }.getOrNull() ?: return - if (composerText.value.isEmpty()) { - composerText.value = draft + if (draftReady.isCompleted) return + try { + val draft = drafts?.load(sessionId) + if (composerText.value.isEmpty() && draft != null) composerText.value = draft + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + // Ordinary chat remains usable when local draft storage fails. + } finally { + draftReady.complete(Unit) } } 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 index 6d31e296..acc442f2 100644 --- 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 @@ -60,6 +60,19 @@ class AttachmentPreparer( ) { private val appContext = context.applicationContext + /** Trusted, app-private shared payload. Preserve provider metadata, not the random disk name. */ + suspend fun prepare(file: File, filename: String, mimeType: String, id: String): PrepareResult = withContext(ioDispatcher) { + try { + val read = file.inputStream().use { readUpTo(it, AttachmentPolicy.readCapFor(mimeType)) } + if (read.overflowed) PrepareResult.TooLarge(filename, file.length()) + else prepareBytes(filename, mimeType, read.bytes, id) + } catch (_: Exception) { + PrepareResult.Unreadable(filename) + } catch (_: OutOfMemoryError) { + PrepareResult.Unreadable(filename) + } + } + suspend fun prepare(uri: Uri): PrepareResult = withContext(ioDispatcher) { val resolver = appContext.contentResolver @@ -123,8 +136,7 @@ class AttachmentPreparer( } /** 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()}" + private fun prepareBytes(filename: String, mimeType: String, original: ByteArray, id: String = "att-${UUID.randomUUID()}"): PrepareResult { return when (AttachmentPolicy.planFor(mimeType, original.size.toLong())) { AttachmentPolicy.Plan.Reject -> PrepareResult.TooLarge(filename, original.size.toLong()) 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 99a0a853..f5e0a75d 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 @@ -125,6 +125,10 @@ fun ChatComposer( modifier = Modifier.fillMaxWidth(), ) { Column { + if (state.isImportingShare) { + Text(stringResource(R.string.share_importing), style = MaterialTheme.typography.labelMedium, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)) + } if (attachments.isNotEmpty()) { LazyRow( modifier = Modifier @@ -151,6 +155,7 @@ fun ChatComposer( } BasicTextField( value = state.text, + enabled = !state.isImportingShare, onValueChange = onTextChange, textStyle = app.hapi.companion.ui.theme.HapiTypography.body.copy( color = MaterialTheme.colorScheme.onSurface, @@ -505,9 +510,9 @@ private fun PrimaryActionButton( // allows an attachments-only send (wire: text or attachments required). val attachmentsBusy = attachments.any { it.status != ComposerAttachmentStatus.Ready } val attachmentsReady = attachments.isNotEmpty() && !attachmentsBusy - val canSubmit = (hasText || attachmentsReady) && !attachmentsBusy && !state.isSending + val canSubmit = (hasText || attachmentsReady) && !attachmentsBusy && !state.isSending && !state.isImportingShare val action = when { - state.isSending -> ComposerPrimaryAction.Sending + state.isSending || state.isImportingShare -> ComposerPrimaryAction.Sending state.canSteer && !hasDraft -> ComposerPrimaryAction.Stop else -> ComposerPrimaryAction.Send } diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/composer/ChatDrafts.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/composer/ChatDrafts.kt index 9325427e..ba7d8d3e 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/composer/ChatDrafts.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/composer/ChatDrafts.kt @@ -16,4 +16,13 @@ interface ChatDrafts { /** Resume/reopen returned a different id: carry the draft across. */ suspend fun move(fromSessionId: String, toSessionId: String) + + /** Append once, atomically persisting both the draft and the handoff receipt. */ + suspend fun appendSharedText(sessionId: String, requestId: String, currentText: String, text: String): String +} + +fun appendSharedText(current: String, shared: String): String = when { + shared.isBlank() -> current + current.isBlank() -> shared + else -> "${current.trimEnd()}\n$shared" } diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/share/AndroidShareIntake.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/share/AndroidShareIntake.kt new file mode 100644 index 00000000..d3f56e15 --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/share/AndroidShareIntake.kt @@ -0,0 +1,67 @@ +package app.hapi.companion.feature.share + +import android.content.ContentResolver +import android.content.Intent +import android.net.Uri +import android.provider.OpenableColumns +import android.webkit.MimeTypeMap +import androidx.core.content.IntentCompat +import java.io.InputStream +import java.util.Locale + +/** Never coerce a URI clip to text: that can read the entire provider file. */ +fun parseSharedIntent(intent: Intent): SharedInput? { + if (intent.action != Intent.ACTION_SEND && intent.action != Intent.ACTION_SEND_MULTIPLE) return null + return try { + val uris = mutableListOf() + if (intent.action == Intent.ACTION_SEND_MULTIPLE) { + IntentCompat.getParcelableArrayListExtra(intent, Intent.EXTRA_STREAM, Uri::class.java)?.let(uris::addAll) + } else { + IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java)?.let(uris::add) + } + val clip = intent.clipData + val texts = mutableListOf() + if (clip != null) repeat(clip.itemCount) { index -> + val item = clip.getItemAt(index) + item.uri?.let(uris::add) + item.text?.toString()?.takeIf { it.isNotBlank() }?.let(texts::add) + } + val text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString() ?: texts.distinct().joinToString("\n") + // Retain unsupported schemes as failed file rows rather than silently + // omitting them from a mixed share. The reader rejects them before I/O. + SharedInput(text, uris.map(Uri::toString).distinct(), intent.type?.takeIf { '/' in it && '*' !in it }) + } catch (_: RuntimeException) { + // Malformed/incorrectly typed parcelables from another application. + SharedInput("", emptyList()) + } +} + +class ContentResolverShareReader(private val resolver: ContentResolver) : ShareFileReader { + private fun contentUri(value: String): Uri = Uri.parse(value).also { + require(it.scheme == ContentResolver.SCHEME_CONTENT) + } + + override fun details(uri: String, mimeTypeHint: String?): ShareFileDetails { + val parsed = contentUri(uri) + var name: String? = null + var size: Long? = null + runCatching { + resolver.query(parsed, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { cursor -> + if (cursor.moveToFirst()) { + val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) + if (nameIndex >= 0 && !cursor.isNull(nameIndex)) name = cursor.getString(nameIndex) + val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE) + if (sizeIndex >= 0 && !cursor.isNull(sizeIndex)) size = cursor.getLong(sizeIndex).takeIf { it >= 0 } + } + } + } + val filename = name?.takeIf { it.isNotBlank() } ?: "attachment" + val mime = runCatching { resolver.getType(parsed) }.getOrNull()?.takeIf { '/' in it && '*' !in it } + ?: MimeTypeMap.getSingleton().getMimeTypeFromExtension(filename.substringAfterLast('.', "").lowercase(Locale.ROOT)) + ?: mimeTypeHint?.takeIf { '/' in it && '*' !in it } + ?: "application/octet-stream" + return ShareFileDetails(filename, mime, size) + } + + override fun open(uri: String): InputStream? = resolver.openInputStream(contentUri(uri)) +} diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/share/ShareInbox.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/share/ShareInbox.kt new file mode 100644 index 00000000..b11b1b26 --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/share/ShareInbox.kt @@ -0,0 +1,301 @@ +package app.hapi.companion.feature.share + +import app.hapi.companion.feature.chat.attachments.AttachmentPolicy +import app.hapi.protocol.wire.HapiJson +import java.io.File +import java.io.InputStream +import java.nio.file.Files +import java.nio.file.StandardCopyOption +import java.util.UUID +import kotlin.coroutines.cancellation.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import kotlinx.serialization.Serializable +import kotlinx.serialization.builtins.ListSerializer + +data class SharedInput(val text: String, val uris: List, val mimeType: String? = null) { + val isEmpty: Boolean get() = text.isBlank() && uris.isEmpty() +} + +data class ShareFileDetails(val filename: String, val mimeType: String, val size: Long? = null) + +/** Platform boundary. The inbox itself is testable with ordinary JVM streams. */ +interface ShareFileReader { + fun details(uri: String, mimeTypeHint: String? = null): ShareFileDetails + fun open(uri: String): InputStream? +} + +@Serializable +enum class SharedFileStatus { Copying, Ready, Unreadable, TooLarge, Interrupted } + +@Serializable +data class SharedFile( + val id: String, + val sourceUri: String, + val filename: String, + val mimeType: String = "application/octet-stream", + val size: Long = 0, + val status: SharedFileStatus = SharedFileStatus.Copying, +) + +@Serializable +data class ShareTarget(val hubUrl: String, val sessionId: String) + +@Serializable +data class PendingShare( + val id: String, + val createdAt: Long, + val text: String, + val files: List, + val target: ShareTarget? = null, +) { + val canImport: Boolean get() = (text.isNotBlank() || files.isNotEmpty()) && + files.all { it.status == SharedFileStatus.Ready } +} + +/** + * Durable handoff, not an attachment draft store. Payloads live in no-backup + * storage until the chat accepts them. Only generated IDs form disk paths; + * provider filenames are display metadata, never filesystem components. + */ +class ShareInbox( + private val root: File, + private val reader: ShareFileReader, + private val scope: CoroutineScope, + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, + private val now: () -> Long = System::currentTimeMillis, + private val onFailure: () -> Unit = {}, +) { + private val mutex = Mutex() + private var loaded = false + private val mutableBatches = MutableStateFlow>(emptyList()) + val batches = mutableBatches.asStateFlow() + private val copies = mutableMapOf() + private val serializer = ListSerializer(PendingShare.serializer()) + + suspend fun load() = withContext(ioDispatcher) { + mutex.withLock { loadLocked() } + } + + private fun loadLocked() { + if (loaded) return + root.mkdirs() + val manifest = File(root, "inbox.json") + val restored = if (manifest.exists()) { + try { + HapiJson.decodeFromString(serializer, manifest.readText()) + } catch (error: Exception) { + // A damaged journal must not permanently prevent new shares. + onFailure() + if (!manifest.renameTo(File(root, "inbox.invalid"))) throw error + emptyList() + } + } else emptyList() + val cutoff = now() - RETENTION_MS + val batches = restored.filter { batch -> + validId(batch.id) && batch.createdAt > cutoff && batch.files.all { validId(it.id) } + }.map { batch -> + val files = batch.files.map { file -> + when { + file.status == SharedFileStatus.Copying -> file.copy(status = SharedFileStatus.Interrupted) + file.status == SharedFileStatus.Ready && !payload(batch.id, file.id).isFile -> + file.copy(status = SharedFileStatus.Unreadable) + else -> file + } + } + batch.copy(files = files, target = batch.target.takeIf { files.all { it.status == SharedFileStatus.Ready } }) + } + writeLocked(batches) + // Includes abandoned .part files and records expired while the app was closed. + root.listFiles()?.filter { it.isDirectory && it.lastModified() <= cutoff && batches.none { batch -> batch.id == it.name } } + ?.forEach { it.deleteRecursively() } + loaded = true + } + + suspend fun receive(input: SharedInput): String = withContext(ioDispatcher) { + require(!input.isEmpty) + val batch = PendingShare( + id = UUID.randomUUID().toString(), + createdAt = now(), + text = input.text, + files = input.uris.distinct().mapIndexed { index, uri -> + SharedFile(UUID.randomUUID().toString(), uri, "attachment-${index + 1}", + mimeType = input.mimeType ?: "application/octet-stream") + }, + ) + mutex.withLock { + loadLocked() + // Never expire a batch currently being handed to a chat. + val expired = batches.value.filter { it.target == null && it.createdAt <= now() - RETENTION_MS } + writeLocked(batches.value - expired.toSet() + batch) + expired.forEach { cancelCopies(it); File(root, it.id).deleteRecursively() } + batch.files.forEach { startCopyLocked(batch.id, it.id) } + } + batch.id + } + + suspend fun retry(batchId: String, fileId: String) = withContext(ioDispatcher) { + mutex.withLock { + val batch = batches.value.find { it.id == batchId } ?: return@withLock + val file = batch.files.find { it.id == fileId } ?: return@withLock + if (file.status == SharedFileStatus.Copying || file.status == SharedFileStatus.Ready) return@withLock + updateLocked(batch.copy(target = null, files = batch.files.map { + if (it.id == fileId) it.copy(status = SharedFileStatus.Copying) else it + })) + startCopyLocked(batchId, fileId) + } + } + + suspend fun removeFile(batchId: String, fileId: String) = withContext(ioDispatcher) { + mutex.withLock { + val batch = batches.value.find { it.id == batchId } ?: return@withLock + updateLocked(batch.copy(files = batch.files.filterNot { it.id == fileId })) + copies.remove(fileId)?.cancel() + payload(batchId, fileId).delete() + File(root, "$batchId/$fileId.part").delete() + } + } + + suspend fun setTarget(batchId: String, target: ShareTarget) = withContext(ioDispatcher) { + mutex.withLock { + val batch = batches.value.find { it.id == batchId } ?: return@withLock + check(batch.canImport) + updateLocked(batch.copy(target = target)) + } + } + + suspend fun clearTarget(batchId: String) = withContext(ioDispatcher) { + mutex.withLock { + batches.value.find { it.id == batchId }?.let { updateLocked(it.copy(target = null)) } + } + } + + suspend fun importFailed(batchId: String, fileId: String, status: SharedFileStatus) = withContext(ioDispatcher) { + mutex.withLock { + val batch = batches.value.find { it.id == batchId } ?: return@withLock + updateLocked(batch.copy(target = null, files = batch.files.map { + if (it.id == fileId) it.copy(status = status) else it + })) + } + } + + /** Explicit discard and successful handoff have the same local cleanup. */ + suspend fun discard(batchId: String) = withContext(ioDispatcher) { + mutex.withLock { + val batch = batches.value.find { it.id == batchId } ?: return@withLock + writeLocked(batches.value.filterNot { it.id == batchId }) + cancelCopies(batch) + File(root, batchId).deleteRecursively() + } + } + + /** Resolves the replacement dialog; unselected batches are explicitly discarded. */ + suspend fun keepOnly(batchId: String) = withContext(ioDispatcher) { + mutex.withLock { + val kept = batches.value.find { it.id == batchId } ?: return@withLock + val removed = batches.value.filterNot { it.id == batchId } + writeLocked(listOf(kept)) + removed.forEach { cancelCopies(it); File(root, it.id).deleteRecursively() } + } + } + + fun file(batchId: String, fileId: String): File { + require(validId(batchId) && validId(fileId)) + return payload(batchId, fileId) + } + + private fun cancelCopies(batch: PendingShare) { + batch.files.forEach { copies.remove(it.id)?.cancel() } + } + + private fun startCopyLocked(batchId: String, fileId: String) { + val job = scope.launch(ioDispatcher, start = CoroutineStart.LAZY) { copy(batchId, fileId) } + copies[fileId] = job + job.start() + } + + private suspend fun copy(batchId: String, fileId: String) { + val initial = batches.value.find { it.id == batchId }?.files?.find { it.id == fileId } ?: return + val temporary = File(root, "$batchId/$fileId.part") + var updated = initial + try { + val details = reader.details(initial.sourceUri, initial.mimeType) + updated = initial.copy(filename = details.filename, mimeType = details.mimeType) + val cap = AttachmentPolicy.readCapFor(details.mimeType) + if (details.size != null && details.size > cap) throw Oversize() + temporary.parentFile?.mkdirs() + var size = 0L + val input = reader.open(initial.sourceUri) ?: error("Unreadable content") + input.use { stream -> + temporary.outputStream().use { output -> + val buffer = ByteArray(64 * 1024) + while (true) { + currentCoroutineContext().ensureActive() + val count = stream.read(buffer) + if (count < 0) break + size += count + if (size > cap) throw Oversize() + output.write(buffer, 0, count) + } + } + } + updated = updated.copy(size = size, status = SharedFileStatus.Ready) + mutex.withLock { + val batch = batches.value.find { it.id == batchId } ?: return@withLock + if (batch.files.none { it.id == fileId }) return@withLock + Files.move(temporary.toPath(), payload(batchId, fileId).toPath(), StandardCopyOption.REPLACE_EXISTING) + updateLocked(batch.copy(files = batch.files.map { if (it.id == fileId) updated else it })) + } + } catch (cancelled: CancellationException) { + throw cancelled + } catch (error: Exception) { + updated = updated.copy(status = if (error is Oversize) SharedFileStatus.TooLarge else SharedFileStatus.Unreadable) + mutex.withLock { + batches.value.find { it.id == batchId }?.let { batch -> + val failedBatch = batch.copy(files = batch.files.map { if (it.id == fileId) updated else it }) + try { + updateLocked(failedBatch) + } catch (_: Exception) { + // For example, a full disk. Keep an actionable error in + // memory; the last journal restores as Interrupted. + mutableBatches.value = batches.value.map { if (it.id == batchId) failedBatch else it } + onFailure() + } + } + } + } finally { + temporary.delete() + } + } + + private fun updateLocked(batch: PendingShare) = writeLocked(batches.value.map { if (it.id == batch.id) batch else it }) + + private fun writeLocked(value: List) { + root.mkdirs() + val temporary = File(root, "inbox.json.tmp") + temporary.writeText(HapiJson.encodeToString(serializer, value)) + Files.move(temporary.toPath(), File(root, "inbox.json").toPath(), + StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) + mutableBatches.value = value + } + + private fun payload(batchId: String, fileId: String) = File(root, "$batchId/$fileId") + private class Oversize : Exception() + + companion object { + const val RETENTION_MS = 24L * 60 * 60 * 1000 + private val ID_PATTERN = Regex("[a-f0-9-]{36}") + private fun validId(id: String): Boolean = ID_PATTERN.matches(id) + } +} diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/share/ShareScreen.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/share/ShareScreen.kt new file mode 100644 index 00000000..99b4dbdc --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/share/ShareScreen.kt @@ -0,0 +1,183 @@ +package app.hapi.companion.feature.share + +import android.net.Uri +import androidx.activity.compose.BackHandler +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.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import app.hapi.companion.R +import app.hapi.companion.feature.sessions.SessionListViewModel +import app.hapi.companion.ui.components.AgentFlavorIcon + +/** A destination picker; list management actions deliberately stay on Home. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ShareScreen( + batch: PendingShare, + hubUrl: String, + pairedHubs: List, + sessions: SessionListViewModel, + target: ShareTargetController, + onSwitchHub: (String) -> Unit, + onRetryFile: (String) -> Unit, + onRemoveFile: (String) -> Unit, + onCancel: () -> Unit, +) { + val list by sessions.uiState.collectAsState() + val selection by target.state.collectAsState() + var hubMenu by remember { mutableStateOf(false) } + BackHandler(onBack = onCancel) + DisposableEffect(sessions) { + sessions.start() + onDispose { sessions.stop() } + } + Scaffold( + topBar = { + TopAppBar( + title = { Text(stringResource(R.string.share_title)) }, + navigationIcon = { IconButton(onClick = onCancel) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.share_cancel)) + } }, + actions = { + Column { + TextButton(onClick = { hubMenu = true }, enabled = !selection.busy, + modifier = Modifier.testTag("share-hub")) { + Text(Uri.parse(hubUrl).authority ?: hubUrl, maxLines = 1, overflow = TextOverflow.Ellipsis, + modifier = Modifier.widthIn(max = 160.dp)) + } + DropdownMenu(expanded = hubMenu, onDismissRequest = { hubMenu = false }) { + pairedHubs.forEach { hub -> + DropdownMenuItem( + text = { Text(Uri.parse(hub).authority ?: hub) }, + trailingIcon = { if (hub == hubUrl) Icon(Icons.Default.Check, null) }, + onClick = { hubMenu = false; onSwitchHub(hub) }, + ) + } + } + } + }, + ) + }, + ) { padding -> + LazyColumn(Modifier.fillMaxSize().padding(padding).testTag("share-picker")) { + if (batch.text.isNotBlank()) item { + Text(batch.text.take(600), maxLines = 4, overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(16.dp)) + } + items(batch.files, key = { it.id }) { file -> + ListItem( + headlineContent = { Text(file.filename, maxLines = 2, overflow = TextOverflow.Ellipsis) }, + supportingContent = { Text(when (file.status) { + SharedFileStatus.Copying -> stringResource(R.string.share_copying) + SharedFileStatus.Ready -> "${file.size / 1024} KiB" + SharedFileStatus.TooLarge -> stringResource(R.string.share_too_large) + SharedFileStatus.Unreadable -> stringResource(R.string.share_unreadable) + SharedFileStatus.Interrupted -> stringResource(R.string.share_interrupted) + }) }, + trailingContent = { + Row { + if (file.status !in setOf(SharedFileStatus.Ready, SharedFileStatus.Copying)) { + TextButton(onClick = { onRetryFile(file.id) }, enabled = !selection.busy) { + Text(stringResource(R.string.share_retry)) + } + } + TextButton(onClick = { onRemoveFile(file.id) }, enabled = !selection.busy) { + Text(stringResource(R.string.share_remove)) + } + } + }, + ) + } + item { + if (batch.files.any { it.status == SharedFileStatus.Copying } || selection.busy) { + LinearProgressIndicator(Modifier.fillMaxWidth()) + } + HorizontalDivider() + Row(Modifier.fillMaxWidth().padding(start = 16.dp), horizontalArrangement = Arrangement.SpaceBetween) { + Text(stringResource(R.string.share_choose_session), modifier = Modifier.padding(vertical = 14.dp)) + IconButton(onClick = sessions::refresh) { Icon(Icons.Default.Refresh, stringResource(R.string.share_refresh)) } + } + OutlinedTextField( + value = list.searchQuery, onValueChange = sessions::setSearchQuery, + placeholder = { Text(stringResource(R.string.share_search_hint)) }, singleLine = true, + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp).testTag("share-search"), + ) + if (list.isOffline) Text(stringResource(R.string.share_offline), + color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp)) + if (selection.failedSessionId != null) { + Text(selection.error ?: stringResource(R.string.share_target_failed), + color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp)) + TextButton(onClick = { target.select(selection.failedSessionId!!) }) { + Text(stringResource(R.string.share_retry)) + } + } + if (list.isRefreshing && !list.hasLoaded) CircularProgressIndicator(Modifier.padding(16.dp)) + else if (list.rows.isEmpty()) Text(stringResource(R.string.share_no_sessions), modifier = Modifier.padding(16.dp)) + } + items(list.rows, key = { "session:${it.id}" }) { row -> + ListItem( + headlineContent = { Text(row.title, maxLines = 2, overflow = TextOverflow.Ellipsis) }, + supportingContent = { Column { + listOfNotNull(row.meta, row.machine?.label).joinToString(" · ").takeIf { it.isNotBlank() }?.let { + Text(it, maxLines = 2, overflow = TextOverflow.Ellipsis) + } + if (!row.summary.active) Text(stringResource(R.string.share_restore_label)) + } }, + leadingContent = { AgentFlavorIcon(row.flavor) }, + modifier = Modifier.clickable(enabled = batch.canImport && !selection.busy) { target.select(row.id) } + .testTag("share-session-${row.id}"), + ) + } + } + } + selection.confirmSessionId?.let { sessionId -> + AlertDialog( + onDismissRequest = target::dismissConfirmation, + title = { Text(stringResource(R.string.share_restore_title)) }, + text = { Text(stringResource(R.string.share_restore_message)) }, + confirmButton = { TextButton(onClick = { target.select(sessionId, confirmReopen = true) }) { + Text(stringResource(R.string.share_restore_confirm)) + } }, + dismissButton = { TextButton(onClick = target::dismissConfirmation) { Text(stringResource(R.string.share_cancel)) } }, + ) + } +} diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/share/ShareTargetController.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/share/ShareTargetController.kt new file mode 100644 index 00000000..acf2a912 --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/share/ShareTargetController.kt @@ -0,0 +1,55 @@ +package app.hapi.companion.feature.share + +import app.hapi.companion.feature.sessions.formatReopenError +import java.util.concurrent.atomic.AtomicBoolean +import kotlin.coroutines.cancellation.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +interface ShareSessionGateway { + suspend fun isActive(sessionId: String): Boolean + /** Includes history seeding and draft migration when the returned ID changes. */ + suspend fun reopen(sessionId: String): String +} + +data class ShareTargetState( + val busy: Boolean = false, + val confirmSessionId: String? = null, + val resolvedSessionId: String? = null, + val failedSessionId: String? = null, + val error: String? = null, +) + +/** One instance per hub connection: switching hubs cancels its owning scope. */ +class ShareTargetController(private val gateway: ShareSessionGateway, private val scope: CoroutineScope) { + private val pending = AtomicBoolean(false) + private val mutableState = MutableStateFlow(ShareTargetState()) + val state = mutableState.asStateFlow() + + fun select(sessionId: String, confirmReopen: Boolean = false) { + if (state.value.resolvedSessionId != null) return + if (!pending.compareAndSet(false, true)) return + mutableState.value = ShareTargetState(busy = true) + scope.launch { + try { + val active = gateway.isActive(sessionId) + mutableState.value = if (!active && !confirmReopen) { + ShareTargetState(confirmSessionId = sessionId) + } else { + ShareTargetState(resolvedSessionId = if (active) sessionId else gateway.reopen(sessionId)) + } + } catch (cancelled: CancellationException) { + throw cancelled + } catch (error: Exception) { + mutableState.value = ShareTargetState(failedSessionId = sessionId, error = formatReopenError(error)) + } finally { + pending.set(false) + } + } + } + + fun dismissConfirmation() { mutableState.value = ShareTargetState() } + fun consumed() { mutableState.value = ShareTargetState() } +} diff --git a/android/app/src/main/res/values-ru/strings.xml b/android/app/src/main/res/values-ru/strings.xml index 50d896b4..e155cb09 100644 --- a/android/app/src/main/res/values-ru/strings.xml +++ b/android/app/src/main/res/values-ru/strings.xml @@ -594,4 +594,32 @@ Недавняя активность Политика конфиденциальности Нет приложения, способного открыть эту ссылку. + + Поделиться с сессией + Выберите сессию + Поиск сессий + Подготовка файла… + Добавление содержимого… + Не удалось прочитать файл. Повторите или удалите его. + Размер файла превышает лимит вложения. + Подготовка прервана. Повторите или удалите файл. + Повторить + Убрать + Отмена + Не удалось получить содержимое. Поделитесь им ещё раз. + Восстановить сессию? + Сессия остановлена. Восстановить её перед добавлением содержимого? + Восстановить и добавить + Остановлена · требуется восстановление + Не удалось открыть сессию. Проверьте подключение и повторите. + Обновить сессии + Подходящих сессий нет + Не удалось обновить сессии. Проверьте подключение или смените хаб. + Получена новая отправка + Содержимое предыдущей отправки ещё не добавлено. Продолжить с ним и отбросить новое или заменить его новым? + Оставить текущее + Использовать новое + Не удалось поделиться + ОК + Подключите хаб, чтобы выбрать сессию для отправки. diff --git a/android/app/src/main/res/values-zh-rCN/strings.xml b/android/app/src/main/res/values-zh-rCN/strings.xml index edfb9064..58fa9f49 100644 --- a/android/app/src/main/res/values-zh-rCN/strings.xml +++ b/android/app/src/main/res/values-zh-rCN/strings.xml @@ -601,4 +601,32 @@ 近期活动 隐私政策 没有可打开此链接的应用。 + + 分享到会话 + 选择会话 + 搜索会话 + 正在准备分享文件… + 正在添加分享内容… + 无法读取此文件,请重试或移除。 + 文件超过附件大小限制。 + 文件准备已中断,请重试或移除。 + 重试 + 移除 + 取消 + 无法接收分享内容,请重新分享。 + 恢复会话? + 此会话已停止。恢复后再添加分享内容? + 恢复并添加 + 已停止 · 添加前需恢复 + 无法打开此会话,请检查连接后重试。 + 刷新会话 + 没有匹配的会话 + 无法刷新会话,请检查连接或切换 Hub。 + 收到新的分享 + 已有尚未导入的分享内容。继续处理当前内容并放弃新分享,还是替换为新分享? + 继续当前 + 替换为新分享 + 分享暂不可用 + 确定 + 请先配对 Hub,再选择接收分享内容的会话。 diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 5402e5c6..ee84153b 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -594,4 +594,32 @@ Recent activity Privacy Policy No app can open this link. + + Share to session + Choose a session + Search sessions + Preparing shared file… + Adding shared content… + Cannot read this file. Retry or remove it. + File exceeds the attachment size limit. + Preparation was interrupted. Retry or remove this file. + Retry + Remove + Cancel + Cannot receive this share. Please share the content again. + Restore session? + This session is stopped. Restore it before adding the shared content? + Restore and add + Stopped · restore before adding + Cannot open this session. Check the connection and try again. + Refresh sessions + No matching sessions + Cannot refresh sessions. Check the connection or switch hubs. + Another share received + There is already shared content waiting to be added. Keep it and discard the new share, or replace it with the new share? + Keep current + Use new share + Share unavailable + OK + Pair a hub to choose a session for the shared content. diff --git a/android/app/src/test/kotlin/app/hapi/companion/di/DataStoreChatDraftsTest.kt b/android/app/src/test/kotlin/app/hapi/companion/di/DataStoreChatDraftsTest.kt new file mode 100644 index 00000000..96db79db --- /dev/null +++ b/android/app/src/test/kotlin/app/hapi/companion/di/DataStoreChatDraftsTest.kt @@ -0,0 +1,54 @@ +package app.hapi.companion.di + +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.test.runTest +import org.junit.Rule +import org.junit.rules.TemporaryFolder + +class DataStoreChatDraftsTest { + @get:Rule val tmp = TemporaryFolder() + + @Test fun `share append and receipt persist together across holder recreation and later edits`() = runTest { + val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) + try { + val store = PreferenceDataStoreFactory.create(scope = scope) { File(tmp.root, "drafts.preferences_pb") } + val first = DataStoreChatDrafts(store, "https://a.example") + assertEquals("original\nshared", first.appendSharedText("session", "request", "original", "shared")) + val restored = DataStoreChatDrafts(store, "https://a.example") + assertEquals("original\nshared", restored.load("session")) + restored.save("session", "edited") + assertEquals("edited", restored.appendSharedText("session", "request", "edited", "shared")) + assertEquals("edited", restored.load("session")) + val anotherHub = DataStoreChatDrafts(store, "https://b.example") + assertEquals("shared", anotherHub.appendSharedText("session", "request", "", "shared")) + } finally { + scope.coroutineContext[Job]?.cancelAndJoin() + } + } + + @Test fun `superseding session migration carries receipts with its draft without replacing a target draft`() = runTest { + val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) + try { + val store = PreferenceDataStoreFactory.create(scope = scope) { File(tmp.root, "drafts.preferences_pb") } + val drafts = DataStoreChatDrafts(store, "https://a.example") + drafts.appendSharedText("old", "request", "draft", "shared") + drafts.move("old", "new") + assertEquals("draft\nshared", drafts.load("new")) + assertEquals("draft\nshared", drafts.appendSharedText("new", "request", "draft\nshared", "shared")) + drafts.save("existing", "keep me") + drafts.move("new", "existing") + assertEquals("keep me", drafts.load("existing")) + assertEquals("keep me\nshared", drafts.appendSharedText("existing", "request", "keep me", "shared")) + } finally { + scope.coroutineContext[Job]?.cancelAndJoin() + } + } +} 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 c3a87784..61c47eb1 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 @@ -2,7 +2,11 @@ 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.attachments.PrepareResult import app.hapi.companion.feature.chat.composer.ChatDrafts +import app.hapi.companion.feature.share.PendingShare +import app.hapi.companion.feature.share.SharedFile +import app.hapi.companion.feature.share.SharedFileStatus import app.hapi.data.api.ApiError import app.hapi.data.api.ChatSessionApi import app.hapi.data.api.MessagesQuery @@ -301,7 +305,16 @@ private class RecordingChatApi : ChatSessionApi { private class FakeDrafts : ChatDrafts { val map = mutableMapOf() - override suspend fun load(sessionId: String): String? = map[sessionId] + val sharedReceipts = mutableSetOf>() + var loadGate: CompletableDeferred? = null + override suspend fun load(sessionId: String): String? { + loadGate?.await() + return map[sessionId] + } + override suspend fun appendSharedText(sessionId: String, requestId: String, currentText: String, text: String): String { + if (!sharedReceipts.add(sessionId to requestId)) return currentText + return app.hapi.companion.feature.chat.composer.appendSharedText(currentText, text).also { save(sessionId, it) } + } override suspend fun save(sessionId: String, text: String) { if (text.isBlank()) map.remove(sessionId) else map[sessionId] = text } @@ -712,6 +725,103 @@ class ChatViewModelInteractionTest { } } + private fun sharedBatch() = PendingShare("share-1", 1_000, "shared text", listOf( + SharedFile("shared-1", "content://one", "one.jpg", status = SharedFileStatus.Ready), + SharedFile("shared-2", "content://two", "two.jpg", status = SharedFileStatus.Ready), + )) + + @Test fun `entering the share picker commits unsaved text before a superseding session migration`() = runTest { + val harness = InteractionHarness(this) + val vm = harness.viewModel + vm.start() + testScheduler.runCurrent() + vm.setComposerText("latest keystrokes") + assertNull(harness.drafts.map[IX_SESSION]) + vm.persistComposerDraft() + harness.drafts.move(IX_SESSION, "replacement") + assertEquals("latest keystrokes", harness.drafts.map["replacement"]) + } + + @Test fun `share waits for draft restore and handoff before allowing an explicit send`() = runTest { + val harness = InteractionHarness(this) + val vm = harness.viewModel + val loadGate = CompletableDeferred() + val handoffGate = CompletableDeferred() + harness.drafts.map[IX_SESSION] = "existing draft" + harness.drafts.loadGate = loadGate + vm.start() + vm.attachments.add(preparedShot("existing")) + val prepared = mutableListOf() + val importing = async { + vm.importShare(sharedBatch(), complete = { handoffGate.await() }) { file -> + prepared += file.id + PrepareResult.Ready(preparedShot(file.id, file.filename)) + } + } + testScheduler.runCurrent() + assertTrue(vm.composer.value.isImportingShare) + assertTrue(prepared.isEmpty()) + vm.sendMessage() + assertTrue(harness.api.sendCalls.value.isEmpty()) + loadGate.complete(Unit) + testScheduler.runCurrent() + assertEquals("existing draft\nshared text", vm.composer.value.text) + vm.sendMessage() + assertTrue(harness.api.sendCalls.value.isEmpty(), "the inbox handoff has not committed yet") + handoffGate.complete(Unit) + assertNull(importing.await()) + vm.attachments.items.first { it.size == 3 && it.all { chip -> chip.status == ComposerAttachmentStatus.Ready } } + assertTrue(harness.api.sendCalls.value.isEmpty(), "import never sends automatically") + vm.sendMessage() + val request = harness.api.sendCalls.first { it.isNotEmpty() }.single().second + assertEquals("existing draft\nshared text", request.text) + assertEquals(setOf("existing", "shared-1", "shared-2"), request.attachments!!.map { it.id }.toSet()) + vm.importShare(sharedBatch()) { error("already accepted share must not prepare again") } + assertEquals(1, harness.api.sendCalls.value.size) + } + + @Test fun `partial share failure and retry do not duplicate text or successful attachments`() = runTest { + val harness = InteractionHarness(this) + val vm = harness.viewModel + harness.drafts.map[IX_SESSION] = "existing" + vm.start() + val prepared = mutableListOf() + val failure = vm.importShare(sharedBatch()) { file -> + prepared += file.id + if (file.id == "shared-2") PrepareResult.Unreadable(file.filename) + else PrepareResult.Ready(preparedShot(file.id, file.filename)) + } + assertEquals(ShareImportFailure("shared-2", SharedFileStatus.Unreadable), failure) + vm.importShare(sharedBatch()) { file -> + prepared += file.id + PrepareResult.Ready(preparedShot(file.id, file.filename)) + } + assertEquals(listOf("shared-1", "shared-2", "shared-2"), prepared) + assertEquals("existing\nshared text", vm.composer.first { !it.isImportingShare }.text) + assertEquals(setOf("shared-1", "shared-2"), vm.attachments.items.first { it.size == 2 }.map { it.id }.toSet()) + assertTrue(harness.api.sendCalls.value.isEmpty()) + } + + @Test fun `canceled import can resume on the same holder without replaying its text`() = runTest { + val harness = InteractionHarness(this) + val vm = harness.viewModel + vm.start() + val gate = CompletableDeferred() + val importing = launch { + vm.importShare(sharedBatch()) { file -> + gate.await() + PrepareResult.Ready(preparedShot(file.id, file.filename)) + } + } + testScheduler.runCurrent() + assertEquals("shared text", vm.composer.value.text) + importing.cancel() + importing.join() + vm.importShare(sharedBatch()) { file -> PrepareResult.Ready(preparedShot(file.id, file.filename)) } + assertEquals("shared text", vm.composer.first { !it.isImportingShare }.text) + assertTrue(harness.api.sendCalls.value.isEmpty()) + } + @Test fun `send rides ready attachments as wire metadata and the optimistic row carries them`() = runTest { val harness = InteractionHarness(this) diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/share/ShareInboxTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/share/ShareInboxTest.kt new file mode 100644 index 00000000..55026399 --- /dev/null +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/share/ShareInboxTest.kt @@ -0,0 +1,192 @@ +package app.hapi.companion.feature.share + +import app.hapi.companion.feature.chat.attachments.AttachmentPolicy +import app.hapi.protocol.wire.HapiJson +import java.io.ByteArrayInputStream +import java.io.File +import java.io.InputStream +import java.util.UUID +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.builtins.ListSerializer +import org.junit.Rule +import org.junit.rules.TemporaryFolder + +private class TestShareReader : ShareFileReader { + var metadata = ShareFileDetails("../../private.txt", "text/plain") + var fail = false + var openCount = 0 + var input: () -> InputStream = { ByteArrayInputStream(byteArrayOf(1, 2, 3)) } + override fun details(uri: String, mimeTypeHint: String?): ShareFileDetails = metadata + override fun open(uri: String): InputStream { + openCount++ + if (fail) throw SecurityException("permission expired") + return input() + } +} + +class ShareInboxTest { + @get:Rule val tmp = TemporaryFolder() + + @Test fun `streams deduplicated payloads to generated paths and restores the selected target`() = runTest { + val reader = TestShareReader() + val dispatcher = StandardTestDispatcher(testScheduler) + val root = tmp.newFolder() + val inbox = ShareInbox(root, reader, backgroundScope, dispatcher) + val id = inbox.receive(SharedInput("explain", listOf("content://one", "content://one", "content://two"))) + testScheduler.runCurrent() + val batch = inbox.batches.value.single() + assertEquals(2, batch.files.size) + assertTrue(batch.canImport) + assertEquals(2, reader.openCount) + assertContentEquals(byteArrayOf(1, 2, 3), inbox.file(id, batch.files.first().id).readBytes()) + assertFalse(File(root.parentFile, "private.txt").exists()) + val target = ShareTarget("https://b.example", "new-session") + inbox.setTarget(id, target) + val restored = ShareInbox(root, reader, backgroundScope, dispatcher) + restored.load() + assertEquals(target, restored.batches.value.single().target) + assertEquals("explain", restored.batches.value.single().text) + restored.discard(id) + assertTrue(restored.batches.value.isEmpty()) + assertFalse(inbox.file(id, batch.files.first().id).exists()) + } + + @Test fun `failed content remains visible and can be retried or removed`() = runTest { + val reader = TestShareReader().apply { fail = true } + val inbox = ShareInbox(tmp.newFolder(), reader, backgroundScope, StandardTestDispatcher(testScheduler)) + val id = inbox.receive(SharedInput("", listOf("content://one"))) + testScheduler.runCurrent() + val fileId = inbox.batches.value.single().files.single().id + assertEquals(SharedFileStatus.Unreadable, inbox.batches.value.single().files.single().status) + assertFalse(inbox.batches.value.single().canImport) + reader.fail = false + inbox.retry(id, fileId) + testScheduler.runCurrent() + assertTrue(inbox.batches.value.single().canImport) + inbox.removeFile(id, fileId) + assertFalse(inbox.batches.value.single().canImport) + assertFalse(inbox.file(id, fileId).exists()) + } + + @Test fun `declared oversize rejects before opening but large compressible images may be staged`() = runTest { + val reader = TestShareReader().apply { + metadata = ShareFileDetails("huge.bin", "application/octet-stream", AttachmentPolicy.MAX_UPLOAD_BYTES + 1) + } + val inbox = ShareInbox(tmp.newFolder(), reader, backgroundScope, StandardTestDispatcher(testScheduler)) + inbox.receive(SharedInput("", listOf("content://one"))) + testScheduler.runCurrent() + assertEquals(SharedFileStatus.TooLarge, inbox.batches.value.single().files.single().status) + assertEquals(0, reader.openCount) + reader.metadata = ShareFileDetails("photo.jpg", "image/jpeg", AttachmentPolicy.MAX_UPLOAD_BYTES + 1) + val batch = inbox.batches.value.single() + inbox.retry(batch.id, batch.files.single().id) + testScheduler.runCurrent() + assertTrue(inbox.batches.value.single().canImport) + } + + @Test fun `actual bytes enforce the cap even when the provider lies about size`() = runTest { + val reader = TestShareReader().apply { + metadata = ShareFileDetails("huge.bin", "application/octet-stream", 1) + input = { object : InputStream() { + var remaining = AttachmentPolicy.MAX_UPLOAD_BYTES + 1 + override fun read(): Int = if (remaining-- > 0) 0 else -1 + override fun read(buffer: ByteArray, offset: Int, length: Int): Int { + if (remaining <= 0) return -1 + val count = minOf(remaining, length.toLong()).toInt() + remaining -= count + return count + } + } } + } + val root = tmp.newFolder() + val inbox = ShareInbox(root, reader, backgroundScope, StandardTestDispatcher(testScheduler)) + inbox.receive(SharedInput("", listOf("content://one"))) + testScheduler.runCurrent() + val batch = inbox.batches.value.single() + assertEquals(SharedFileStatus.TooLarge, batch.files.single().status) + assertFalse(inbox.file(batch.id, batch.files.single().id).exists()) + assertTrue(File(root, batch.id).listFiles().orEmpty().isEmpty()) + } + + @Test fun `interrupted copies restore as errors and missing ready payloads are not silently imported`() = runTest { + val root = tmp.newFolder() + val batchId = UUID.randomUUID().toString() + val pending = PendingShare(batchId, 1_000, "", listOf( + SharedFile(UUID.randomUUID().toString(), "content://one", "one"), + SharedFile(UUID.randomUUID().toString(), "content://two", "two", status = SharedFileStatus.Ready), + )) + File(root, "inbox.json").writeText(HapiJson.encodeToString(ListSerializer(PendingShare.serializer()), listOf(pending))) + val inbox = ShareInbox(root, TestShareReader(), backgroundScope, StandardTestDispatcher(testScheduler), now = { 2_000 }) + inbox.load() + assertEquals(listOf(SharedFileStatus.Interrupted, SharedFileStatus.Unreadable), inbox.batches.value.single().files.map { it.status }) + assertFalse(inbox.batches.value.single().canImport) + } + + @Test fun `new shares do not overwrite pending content and replacement cleans unselected payloads`() = runTest { + val inbox = ShareInbox(tmp.newFolder(), TestShareReader(), backgroundScope, StandardTestDispatcher(testScheduler)) + val first = inbox.receive(SharedInput("first", listOf("content://one"))) + val second = inbox.receive(SharedInput("second", emptyList())) + testScheduler.runCurrent() + val fileId = inbox.batches.value.first().files.single().id + assertEquals(listOf(first, second), inbox.batches.value.map { it.id }) + inbox.keepOnly(second) + assertEquals(listOf(second), inbox.batches.value.map { it.id }) + assertFalse(inbox.file(first, fileId).exists()) + } + + @Test fun `old unprocessed batches expire on receive and on process restore`() = runTest { + val root = tmp.newFolder() + var now = 1_000L + val dispatcher = StandardTestDispatcher(testScheduler) + val inbox = ShareInbox(root, TestShareReader(), backgroundScope, dispatcher, now = { now }) + inbox.receive(SharedInput("old", emptyList())) + now += ShareInbox.RETENTION_MS + 1 + val current = inbox.receive(SharedInput("new", emptyList())) + assertEquals(listOf(current), inbox.batches.value.map { it.id }) + now += ShareInbox.RETENTION_MS + 1 + val restored = ShareInbox(root, TestShareReader(), backgroundScope, dispatcher, now = { now }) + restored.load() + assertTrue(restored.batches.value.isEmpty()) + } + + @Test fun `corrupt journals are reported without preventing a new share`() = runTest { + val root = tmp.newFolder() + File(root, "inbox.json").writeText("{broken") + var failures = 0 + val inbox = ShareInbox(root, TestShareReader(), backgroundScope, StandardTestDispatcher(testScheduler), + onFailure = { failures++ }) + inbox.load() + assertEquals(1, failures) + inbox.receive(SharedInput("new share", emptyList())) + assertEquals("new share", inbox.batches.value.single().text) + } + + @Test fun `journal failure during a copy leaves an actionable in-memory error and a recoverable record`() = runTest { + val root = tmp.newFolder() + var failures = 0 + val reader = TestShareReader().apply { + input = { + // Simulate storage becoming unwritable after initial intake. + File(root, "inbox.json.tmp").mkdir() + ByteArrayInputStream(byteArrayOf(1)) + } + } + val dispatcher = StandardTestDispatcher(testScheduler) + val inbox = ShareInbox(root, reader, backgroundScope, dispatcher, onFailure = { failures++ }) + inbox.receive(SharedInput("", listOf("content://one"))) + testScheduler.runCurrent() + assertEquals(1, failures) + assertEquals(SharedFileStatus.Unreadable, inbox.batches.value.single().files.single().status) + assertFalse(inbox.batches.value.single().canImport) + File(root, "inbox.json.tmp").delete() + val restored = ShareInbox(root, reader, backgroundScope, dispatcher) + restored.load() + assertEquals(SharedFileStatus.Interrupted, restored.batches.value.single().files.single().status) + } +} diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/share/ShareTargetControllerTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/share/ShareTargetControllerTest.kt new file mode 100644 index 00000000..a9ad0045 --- /dev/null +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/share/ShareTargetControllerTest.kt @@ -0,0 +1,83 @@ +package app.hapi.companion.feature.share + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancel +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.runTest + +private class TestShareGateway : ShareSessionGateway { + var active = true + var fail = false + var reopens = 0 + var gate: CompletableDeferred? = null + override suspend fun isActive(sessionId: String): Boolean { + gate?.await() + if (fail) error("machine offline") + return active + } + override suspend fun reopen(sessionId: String): String { + reopens++ + return "replacement-id" + } +} + +class ShareTargetControllerTest { + @Test fun `active targets resolve without resuming or sending`() = runTest { + val gateway = TestShareGateway() + val controller = ShareTargetController(gateway, backgroundScope) + controller.select("original-id") + testScheduler.runCurrent() + assertEquals("original-id", controller.state.value.resolvedSessionId) + assertEquals(0, gateway.reopens) + } + + @Test fun `inactive targets require confirmation and resolve to returned session id`() = runTest { + val gateway = TestShareGateway().apply { active = false } + val controller = ShareTargetController(gateway, backgroundScope) + controller.select("original-id") + testScheduler.runCurrent() + assertEquals("original-id", controller.state.value.confirmSessionId) + assertNull(controller.state.value.resolvedSessionId) + assertEquals(0, gateway.reopens) + controller.select("original-id", confirmReopen = true) + testScheduler.runCurrent() + assertEquals("replacement-id", controller.state.value.resolvedSessionId) + assertEquals(1, gateway.reopens) + } + + @Test fun `failed resolution retains the selected id for retry`() = runTest { + val gateway = TestShareGateway().apply { fail = true } + val controller = ShareTargetController(gateway, backgroundScope) + controller.select("id") + testScheduler.runCurrent() + assertEquals("id", controller.state.value.failedSessionId) + assertFalse(controller.state.value.busy) + assertNull(controller.state.value.resolvedSessionId) + gateway.fail = false + controller.select("id") + testScheduler.runCurrent() + assertEquals("id", controller.state.value.resolvedSessionId) + } + + @Test fun `duplicate taps coalesce and canceled hub operations never resolve a target`() = runTest { + val gateway = TestShareGateway().apply { active = false; gate = CompletableDeferred() } + val scope = CoroutineScope(Job() + StandardTestDispatcher(testScheduler)) + val controller = ShareTargetController(gateway, scope) + controller.select("id", confirmReopen = true) + controller.select("id", confirmReopen = true) + testScheduler.runCurrent() + assertTrue(controller.state.value.busy) + scope.cancel() + gateway.gate!!.complete(Unit) + testScheduler.runCurrent() + assertNull(controller.state.value.resolvedSessionId) + assertEquals(0, gateway.reopens) + } +} diff --git a/docs/guide/native-apps.md b/docs/guide/native-apps.md index 712bd51f..97991d60 100644 --- a/docs/guide/native-apps.md +++ b/docs/guide/native-apps.md @@ -89,6 +89,7 @@ directory browsing and session creation. |---|---| | Chat and permissions | Streaming messages, history, tool inspection, approvals and question answering on both platforms. | | Composer | Text, photos/camera/files, drafts, queued-message actions, `/` command suggestions and steering when supported by the session. | +| Android incoming shares | Share files, photos, text or links to HAPI, choose a session and confirm sending from its composer. The picker can switch paired hubs and explicitly restore stopped sessions. | | Session controls | Both support pin, rename, stopping a turn and sending to resume an inactive session. Active sessions can be archived; inactive sessions can be reopened explicitly or deleted. | | Files and Git | Open **Session files** from the chat menu to browse/search files, inspect Git status and read diffs. | | Scratchlist | On iOS, tap the tray beside the composer attachment button to enter **Save draft** mode; Android uses the chat menu. Text and attachments sync within the session. | @@ -96,6 +97,20 @@ directory browsing and session creation. | Usage and storage | Available only to the hub owner (`default` namespace). | | Display | English/Simplified Chinese, theme preferences, system text scaling and machine filtering on the session list. | +### Share to an Android session + +In another app, choose **Share → HAPI**, then select a session. Use the hub +menu to choose another paired hub, or search the session list. A stopped +session asks for restoration before files can upload. HAPI adds the files and +any accompanying text to the session composer, preserving its existing draft; +review the content and tap **Send**. + +Files use the existing attachment limits and image compression policy. Failed +files must be retried or removed before continuing. Before import, pending +content stays in private local storage for up to 24 hours, including while +pairing or recovering from process recreation. After import, ordinary Android +attachment behavior applies: leaving the chat discards unsent attachments. + ### Session-list parity Android and iOS use the shared base session-list order: global-pinned sessions,