diff --git a/src/apps/mobile/android/AGENTS.md b/src/apps/mobile/android/AGENTS.md index efd72c7a4d..d770017431 100644 --- a/src/apps/mobile/android/AGENTS.md +++ b/src/apps/mobile/android/AGENTS.md @@ -52,6 +52,9 @@ JAVA_HOME='/Applications/Android Studio.app/Contents/jbr/Contents/Home' ./gradle # Verify running-input, plan gating, offline tools, and attachment retention. ./gradlew :app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.openbitfun.mobile.app.MobileParityTest +# Verify unavailable media handlers, photo decoding/sending, and dictation lifecycle. +JAVA_HOME='/Applications/Android Studio.app/Contents/jbr/Contents/Home' ./gradlew :app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.openbitfun.mobile.app.ComposerMediaInputTest + # Verify terminal WebView focus and native keyboard routing inside the dialog. ./gradlew :app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.openbitfun.mobile.app.RuntimeTerminalViewTest diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ComposerMediaInputTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ComposerMediaInputTest.kt new file mode 100644 index 0000000000..d8f827393b --- /dev/null +++ b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ComposerMediaInputTest.kt @@ -0,0 +1,239 @@ +package com.openbitfun.mobile.app + +import android.app.Activity +import android.content.ActivityNotFoundException +import android.content.Intent +import android.graphics.Bitmap +import android.net.Uri +import android.speech.RecognizerIntent +import android.util.Base64 +import androidx.activity.compose.LocalActivityResultRegistryOwner +import androidx.activity.result.ActivityResultRegistry +import androidx.activity.result.ActivityResultRegistryOwner +import androidx.activity.result.contract.ActivityResultContract +import androidx.compose.material3.Button +import androidx.compose.material3.Text +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.onAllNodesWithContentDescription +import androidx.compose.runtime.Composable +import androidx.compose.ui.test.assertIsEnabled +import androidx.compose.ui.test.junit4.v2.createComposeRule +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.junit4.StateRestorationTester +import androidx.core.app.ActivityOptionsCompat +import androidx.test.platform.app.InstrumentationRegistry +import com.openbitfun.mobile.app.platform.launchComposerActivity +import com.openbitfun.mobile.app.platform.prepareComposerImage +import com.openbitfun.mobile.app.ui.chat.COMPOSER_INPUT_TEST_TAG +import com.openbitfun.mobile.app.ui.chat.ConversationView +import com.openbitfun.mobile.app.ui.chat.decodeInlineImage +import com.openbitfun.mobile.app.ui.chat.rememberComposerVoiceInput +import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme +import com.openbitfun.mobile.core.feature.connection.ConnectionPhase +import com.openbitfun.mobile.core.feature.layout.SettingsPlacement +import com.openbitfun.mobile.core.feature.layout.SettingsPlacementMode +import com.openbitfun.mobile.core.feature.session.RemoteSessionIntent +import com.openbitfun.mobile.core.feature.session.RemoteSessionUiState +import com.openbitfun.mobile.core.feature.session.SessionAgentFilter +import com.openbitfun.mobile.core.feature.workspace.RemoteFileDownloadUiState +import java.io.File +import java.util.UUID +import kotlinx.coroutines.runBlocking +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test + +class ComposerMediaInputTest { + @get:Rule val rule = createComposeRule() + private val context get() = InstrumentationRegistry.getInstrumentation().targetContext + + @Test fun unavailableSystemActivitiesKeepRemoteDraftEditable() { + val registry = MediaRegistry { throw ActivityNotFoundException("No system handler") } + val intents = mutableListOf() + val sessionId = "media-${UUID.randomUUID()}" + rule.setContent { RemoteComposer(registry, sessionId, intents::add) } + rule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertIsEnabled() + rule.onNodeWithContentDescription(context.getString(R.string.message_attach_image)).performClick() + rule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).performClick() + rule.onNodeWithTag("composer-voice").performClick() + rule.onNodeWithText("Keep this draft").assertIsDisplayed() + rule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertIsEnabled() + rule.runOnIdle { + assertEquals(2, registry.launches) + assertTrue(intents.isEmpty()) + } + } + + @Test fun deniedSystemActivityIsRecoverable() { + rule.runOnIdle { + assertFalse(launchComposerActivity(context, R.string.chat_photo_picker_unavailable) { + throw SecurityException("Handler is not exported") + }) + } + } + + @Test fun dictationUsesCurrentDraftCallbackAndSurvivesRecreation() { + val registry = MediaRegistry() + val owner = mutableStateOf("device-a/session") + val draft = mutableStateOf("old draft") + val received = mutableListOf() + val restoration = StateRestorationTester(rule) + restoration.setContent { + CompositionLocalProvider(LocalActivityResultRegistryOwner provides registry) { + val before = draft.value + val launch = rememberComposerVoiceInput(owner.value) { received += "$before/$it" } + Button(onClick = launch) { Text("Dictate") } + } + } + rule.onNodeWithText("Dictate").performClick() + restoration.emulateSavedInstanceStateRestore() + rule.runOnIdle { draft.value = "new draft" } + rule.waitForIdle() + rule.runOnIdle { registry.replySpeech("recognized") } + rule.runOnIdle { assertEquals(listOf("new draft/recognized"), received) } + } + + @Test fun dictationDoesNotCrossDeviceOrSessionBoundaries() { + val registry = MediaRegistry() + val owner = mutableStateOf("device-a/session") + val received = mutableListOf() + rule.setContent { + CompositionLocalProvider(LocalActivityResultRegistryOwner provides registry) { + val launch = rememberComposerVoiceInput(owner.value, received::add) + Button(onClick = launch) { Text("Dictate") } + } + } + rule.onNodeWithText("Dictate").performClick() + rule.runOnIdle { owner.value = "device-b/session" } + rule.waitForIdle() + rule.runOnIdle { registry.replySpeech("another device's text") } + rule.runOnIdle { assertTrue(received.isEmpty()) } + rule.onNodeWithText("Dictate").performClick() + rule.runOnIdle { registry.dispatchResult(registry.requestCode, Activity.RESULT_CANCELED, null) } + rule.runOnIdle { assertTrue(received.isEmpty()) } + rule.onNodeWithText("Dictate").performClick() + rule.runOnIdle { registry.replySpeech("current device") } + rule.runOnIdle { assertEquals(listOf("current device"), received) } + } + + @Test fun cameraPhotoIsResizedForUploadAndInlinePreview() = runBlocking { + val file = File(context.cacheDir, "media-${UUID.randomUUID()}.jpg") + val bitmap = Bitmap.createBitmap(4000, 3000, Bitmap.Config.ARGB_8888) + try { + file.outputStream().use { assertTrue(bitmap.compress(Bitmap.CompressFormat.JPEG, 95, it)) } + } finally { bitmap.recycle() } + try { + val image = prepareComposerImage(context.contentResolver, Uri.fromFile(file)) + assertEquals("image/jpeg", image.mimeType) + val bytes = Base64.decode(image.dataUrl.substringAfter(','), Base64.DEFAULT) + assertTrue(bytes.size <= 1024 * 1024) + val bounds = android.graphics.BitmapFactory.Options().apply { inJustDecodeBounds = true } + android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) + assertEquals(1920, maxOf(bounds.outWidth, bounds.outHeight)) + val preview = requireNotNull(decodeInlineImage(image.dataUrl)) + try { assertTrue(maxOf(preview.width, preview.height) <= 512) } + finally { preview.recycle() } + // History from older clients can still carry the original full-size photo. + val original = "data:image/jpeg;base64," + Base64.encodeToString(file.readBytes(), Base64.NO_WRAP) + val legacyPreview = requireNotNull(decodeInlineImage(original)) + try { assertTrue(maxOf(legacyPreview.width, legacyPreview.height) <= 512) } + finally { legacyPreview.recycle() } + } finally { file.delete() } + } + + @Test fun invalidInlineImagesRemainCaptionOnly() { + assertNull(decodeInlineImage("https://example.com/image.jpg")) + assertNull(decodeInlineImage("data:image/png;base64,not-base64")) + assertNull(decodeInlineImage("data:image/png;base64," + Base64.encodeToString(byteArrayOf(1, 2, 3), Base64.NO_WRAP))) + } + + @Test fun selectedPhotoCanBeSentAndRetainedWithoutAcknowledgement() { + val registry = MediaRegistry() + val intents = mutableListOf() + val sessionId = "media-${UUID.randomUUID()}" + val file = File(context.cacheDir, "$sessionId.png") + val bitmap = Bitmap.createBitmap(32, 24, Bitmap.Config.ARGB_8888) + try { file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) } } + finally { bitmap.recycle() } + try { + rule.setContent { RemoteComposer(registry, sessionId, intents::add) } + rule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertIsEnabled() + rule.onNodeWithContentDescription(context.getString(R.string.message_attach_image)).performClick() + rule.runOnIdle { + registry.dispatchResult(registry.requestCode, Activity.RESULT_OK, Intent().setData(Uri.fromFile(file))) + } + rule.waitUntil(5_000) { + rule.onAllNodesWithContentDescription(context.getString(R.string.message_remove_image)) + .fetchSemanticsNodes().size == 1 + } + rule.onNodeWithContentDescription(context.getString(R.string.message_remove_image)).assertIsEnabled() + rule.onNodeWithTag(com.openbitfun.mobile.app.ui.chat.COMPOSER_SEND_TEST_TAG).performClick() + rule.runOnIdle { + val image = intents.filterIsInstance().single().images!!.single() + assertEquals("image/jpeg", image.mimeType) + assertTrue(image.dataUrl.startsWith("data:image/jpeg;base64,")) + } + // The controlled host has not acknowledged this send. Keep its attachment. + rule.onNodeWithContentDescription(context.getString(R.string.message_remove_image)).assertIsDisplayed() + } finally { file.delete() } + } + + @Test fun unreadableSelectedPhotoDoesNotCrashOrEraseDraft() { + val registry = MediaRegistry() + val sessionId = "media-${UUID.randomUUID()}" + rule.setContent { RemoteComposer(registry, sessionId) {} } + rule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertIsEnabled() + rule.onNodeWithContentDescription(context.getString(R.string.message_attach_image)).performClick() + rule.runOnIdle { + registry.dispatchResult(registry.requestCode, Activity.RESULT_OK, + Intent().setData(Uri.parse("content://com.openbitfun.missing-provider/photo"))) + } + rule.waitForIdle() + rule.onNodeWithText("Keep this draft").assertIsDisplayed() + rule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertIsEnabled() + } + + @Composable + private fun RemoteComposer(registry: MediaRegistry, sessionId: String, onIntent: (RemoteSessionIntent) -> Unit) { + CompositionLocalProvider(LocalActivityResultRegistryOwner provides registry) { + OpenBitFunTheme(dark = false) { + ConversationView( + state = RemoteSessionUiState.Ready( + sessions = emptyList(), selectedSessionId = sessionId, + timeline = null, busy = false, permissionMode = null, permissionModeFailure = null, + query = "", agentFilter = SessionAgentFilter.ALL, hasMore = false, + hasMoreMessages = false, modelCatalog = null, modelCatalogFailure = null, + draft = "Keep this draft", + ), + phase = ConnectionPhase.CONNECTED, + settingsPlacement = SettingsPlacement(SettingsPlacementMode.BOTTOM, 0, 0, 0), + onBack = {}, onIntent = onIntent, contextTitle = "Test desktop", + onOpenFile = { _, _ -> }, previewingRemotePath = "", previewLoading = false, + download = RemoteFileDownloadUiState.None, onDownloadFile = { _, _ -> }, + modifier = Modifier, + ) + } + } + } + + private class MediaRegistry(private val fail: (() -> Unit)? = null) : ActivityResultRegistry(), ActivityResultRegistryOwner { + override val activityResultRegistry: ActivityResultRegistry get() = this + var launches = 0 + var requestCode = 0 + override fun onLaunch(requestCode: Int, contract: ActivityResultContract, input: I, options: ActivityOptionsCompat?) { + launches++ + this.requestCode = requestCode + fail?.invoke() + } + fun replySpeech(text: String) { + dispatchResult(requestCode, Activity.RESULT_OK, + Intent().putStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS, arrayListOf(text))) + } + } +} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/ComposerActivityLauncher.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/ComposerActivityLauncher.kt new file mode 100644 index 0000000000..85b520d3ad --- /dev/null +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/ComposerActivityLauncher.kt @@ -0,0 +1,25 @@ +package com.openbitfun.mobile.app.platform + +import android.content.ActivityNotFoundException +import android.content.Context +import android.util.Log +import android.widget.Toast +import androidx.annotation.StringRes + +/** System media activities are optional, and OEMs may deny access to them. */ +internal fun launchComposerActivity( + context: Context, + @StringRes failureMessage: Int, + launch: () -> Unit, +): Boolean = try { + launch() + true +} catch (_: ActivityNotFoundException) { + Log.w("ComposerActivity", "System media activity is unavailable") + Toast.makeText(context, failureMessage, Toast.LENGTH_LONG).show() + false +} catch (_: SecurityException) { + Log.w("ComposerActivity", "System media activity access was denied") + Toast.makeText(context, failureMessage, Toast.LENGTH_LONG).show() + false +} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/state/AppShellState.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/state/AppShellState.kt index 66f5182eb5..e75d6d8c1f 100644 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/state/AppShellState.kt +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/state/AppShellState.kt @@ -41,6 +41,7 @@ internal class AppShellState( remoteSessionId: String? = null, remoteCreating: Boolean = false, remoteConnectOpen: Boolean = false, + pendingRemoteSessionId: String? = null, ) { internal var surface: MobileSurface by mutableStateOf(surface) private set @@ -63,6 +64,11 @@ internal class AppShellState( internal var remoteSessionId: String? by mutableStateOf(remoteSessionId) private set + internal var pendingRemoteSessionId: String? by mutableStateOf(pendingRemoteSessionId) + private set + + private var pendingRemoteSessionObservedBusy = false + internal var remoteCreating: Boolean by mutableStateOf(remoteCreating) private set @@ -82,6 +88,23 @@ internal class AppShellState( surface = MobileSurface.REMOTE remoteCreating = false remoteSessionId = sessionId + pendingRemoteSessionId = sessionId + pendingRemoteSessionObservedBusy = false + } + + internal fun observeRemoteSessionOpen(sessionId: String, selectedSessionId: String?, busy: Boolean) { + if (pendingRemoteSessionId != sessionId) return + when { + selectedSessionId == sessionId -> completeRemoteSessionOpen(sessionId) + busy -> pendingRemoteSessionObservedBusy = true + pendingRemoteSessionObservedBusy -> completeRemoteSessionOpen(sessionId) + } + } + + private fun completeRemoteSessionOpen(sessionId: String) { + if (pendingRemoteSessionId != sessionId) return + pendingRemoteSessionId = null + pendingRemoteSessionObservedBusy = false } internal fun createRemoteSession() { @@ -89,12 +112,16 @@ internal class AppShellState( surface = MobileSurface.REMOTE remoteCreating = true remoteSessionId = null + pendingRemoteSessionId = null + pendingRemoteSessionObservedBusy = false } internal fun closeRemoteSession() { closeRemoteConnect() remoteCreating = false remoteSessionId = null + pendingRemoteSessionId = null + pendingRemoteSessionObservedBusy = false } /** @@ -109,6 +136,8 @@ internal class AppShellState( surface = MobileSurface.REMOTE remoteCreating = false remoteSessionId = null + pendingRemoteSessionId = null + pendingRemoteSessionObservedBusy = false } /** @@ -191,11 +220,12 @@ internal class AppShellState( it.sidebarQuery, it.remoteSessionId, it.remoteCreating, - // Index 9 held the retired scanner request. It stays a - // placeholder so the positions older builds wrote still - // line up with what [restore] reads. + // Index 9 held a retired connection-overlay request. It + // stays a placeholder so the positions older builds wrote + // still line up with what [restore] reads. false, it.remoteConnectOpen, + it.pendingRemoteSessionId, ) }, restore = { @@ -211,15 +241,26 @@ internal class AppShellState( remoteSessionId = it.getOrNull(7) as String?, remoteCreating = it.getOrNull(8) as? Boolean ?: false, // A state saved before index 10 existed only knew the - // scanner request, which opened the connect sheet. + // retired connection-overlay request, which opened the + // account device sheet. remoteConnectOpen = it.getOrNull(10) as? Boolean ?: (it.getOrNull(9) as? Boolean ?: false), + pendingRemoteSessionId = it.getOrNull(11) as? String?, ) }, ) } } +internal fun resolveRoutedRemoteSessionId( + pendingSessionId: String?, + requestedSessionId: String?, + committedSessionIds: Set, + selectedSessionId: String?, +): String? = pendingSessionId + ?: requestedSessionId?.takeIf { it in committedSessionIds || it == selectedSessionId } + ?: selectedSessionId + @Composable internal fun rememberAppShellState(): AppShellState = rememberSaveable(saver = AppShellState.Saver) { AppShellState( diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ComposerVoiceInput.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ComposerVoiceInput.kt new file mode 100644 index 0000000000..4bb2062a83 --- /dev/null +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ComposerVoiceInput.kt @@ -0,0 +1,43 @@ +package com.openbitfun.mobile.app.ui.chat + +import android.app.Activity +import android.content.Intent +import android.speech.RecognizerIntent +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.platform.LocalContext +import com.openbitfun.mobile.app.R +import com.openbitfun.mobile.app.platform.launchComposerActivity + +/** Dictation belongs to the session that launched it, including across recreation. */ +@Composable +internal fun rememberComposerVoiceInput(owner: String, onText: (String) -> Unit): () -> Unit { + val context = LocalContext.current + var pendingOwner by rememberSaveable { mutableStateOf(null) } + val currentOwner by rememberUpdatedState(owner) + val receiveText by rememberUpdatedState(onText) + val launcher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> + val target = pendingOwner + pendingOwner = null + if (target == currentOwner && result.resultCode == Activity.RESULT_OK) { + val text = result.data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)?.firstOrNull().orEmpty() + if (text.isNotBlank()) receiveText(text) + } + } + return { + pendingOwner = owner + if (!launchComposerActivity(context, R.string.chat_voice_input_unavailable) { + launcher.launch(Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply { + putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) + }) + }) { + pendingOwner = null + } + } +} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationView.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationView.kt index 943914c348..3190c9ff2d 100644 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationView.kt +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationView.kt @@ -21,9 +21,6 @@ import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontFamily import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignTypography -import android.app.Activity -import android.content.Intent -import android.speech.RecognizerIntent import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.PickVisualMediaRequest @@ -55,6 +52,7 @@ import androidx.compose.runtime.key import androidx.compose.runtime.rememberUpdatedState import kotlinx.coroutines.launch import com.openbitfun.mobile.app.platform.prepareComposerImage +import com.openbitfun.mobile.app.platform.launchComposerActivity import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier @@ -139,8 +137,8 @@ internal fun ConversationView( /** * Where this transcript is running — a desktop name, or the brand and the * branch. Built by `ConversationHeaderPresenter` at the call site, because - * only the screen knows whether it reached this session through a pairing - * or through an account device. + * only the screen knows whether it reached this session through the + * selected account device. */ contextTitle: String, /** A file the agent named, taken from a markdown link. Path, then label. */ @@ -228,6 +226,8 @@ internal fun ConversationView( images = images + prepared } } + } catch (cancelled: kotlinx.coroutines.CancellationException) { + throw cancelled } catch (_: Exception) { if (currentAttachmentKey == targetSession) { Toast.makeText(context, R.string.chat_image_prepare_failed, Toast.LENGTH_LONG).show() @@ -244,13 +244,8 @@ internal fun ConversationView( if (uri != null) importPhotos(listOf(uri)) } - val voiceInput = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> - if (result.resultCode == Activity.RESULT_OK) { - val text = result.data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)?.firstOrNull().orEmpty() - if (text.isNotBlank()) { - onIntent(RemoteSessionIntent.UpdateDraft(mergeComposerDraft(state.draft, text))) - } - } + val voiceInput = rememberComposerVoiceInput(attachmentKey) { text -> + onIntent(RemoteSessionIntent.UpdateDraft(mergeComposerDraft(state.draft, text))) } androidx.compose.runtime.CompositionLocalProvider( @@ -388,21 +383,14 @@ internal fun ConversationView( onAttach = { pickerOwner = attachmentKey val remaining = MAX_COMPOSER_IMAGES - images.size - if (remaining == 1) singlePhotoPicker.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) - else if (remaining > 1) photoPicker.launch( - PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly, maxItems = remaining), - ) - }, - onVoice = { - voiceInput.launch( - Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply { - putExtra( - RecognizerIntent.EXTRA_LANGUAGE_MODEL, - RecognizerIntent.LANGUAGE_MODEL_FREE_FORM, + if (!launchComposerActivity(context, R.string.chat_photo_picker_unavailable) { + if (remaining == 1) singlePhotoPicker.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) + else if (remaining > 1) photoPicker.launch( + PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly, maxItems = remaining), ) - }, - ) + }) pickerOwner = null }, + onVoice = voiceInput, onSend = { submittedDraft = draft keyboard?.hide() diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/GeneralChatScreen.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/GeneralChatScreen.kt index 131b0f8b97..807de15be5 100644 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/GeneralChatScreen.kt +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/GeneralChatScreen.kt @@ -1,11 +1,8 @@ package com.openbitfun.mobile.app.ui.chat -import android.app.Activity import android.content.Context import android.content.Intent import android.net.Uri -import android.speech.RecognizerIntent -import android.util.Base64 import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.PickVisualMediaRequest @@ -35,6 +32,8 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment @@ -49,6 +48,8 @@ import androidx.compose.ui.unit.sp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import com.openbitfun.mobile.app.R +import com.openbitfun.mobile.app.platform.launchComposerActivity +import com.openbitfun.mobile.app.platform.prepareComposerImage import com.openbitfun.mobile.app.ui.common.CircleControl import com.openbitfun.mobile.app.ui.common.AdaptiveModalSurface import com.openbitfun.mobile.app.ui.settings.ModelServiceScreen @@ -58,11 +59,11 @@ import com.openbitfun.mobile.core.feature.layout.SettingsPlacement import com.openbitfun.mobile.core.feature.generalchat.GeneralChatFailureReason import com.openbitfun.mobile.core.feature.generalchat.GeneralChatIntent import com.openbitfun.mobile.core.feature.session.ChatComposerCapabilities -import com.openbitfun.mobile.core.feature.session.ComposerImage import com.openbitfun.mobile.core.feature.session.ConversationRowKind import com.openbitfun.mobile.core.feature.session.ModelOption import com.openbitfun.mobile.core.feature.session.conversationRows -import java.util.UUID +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.launch internal const val GENERAL_CHAT_TEST_TAG: String = "general-chat" // Keep the shell-level automation id while the control is now owned by the @@ -71,9 +72,6 @@ internal const val GENERAL_CHAT_SIDEBAR_TEST_TAG: String = "shell-menu" internal const val GENERAL_CHAT_MENU_TEST_TAG: String = "general-chat-menu" internal const val GENERAL_CHAT_MODEL_TEST_TAG: String = "general-chat-model" -/** Matches the remote composer and HarmonyOS image picker. */ -private const val MAX_GENERAL_CHAT_IMAGE_BYTES = 8 * 1024 * 1024 - /** * The general-chat surface, the counterpart of `ConversationView` for a * conversation that has no desktop behind it. @@ -139,42 +137,34 @@ internal fun GeneralChatScreen( } } - val voiceInput = rememberLauncherForActivityResult( - ActivityResultContracts.StartActivityForResult(), - ) { result -> - if (result.resultCode == Activity.RESULT_OK) { - val text = result.data - ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS) - ?.firstOrNull() - .orEmpty() - if (text.isNotBlank()) { - val merged = listOf(state.draft.trim(), text.trim()) - .filter(String::isNotEmpty) - .joinToString(" ") - viewModel.dispatch(GeneralChatIntent.UpdateDraft(merged)) - } - } + val voiceInput = rememberComposerVoiceInput(state.sessionId) { text -> + viewModel.dispatch(GeneralChatIntent.UpdateDraft(listOf(state.draft.trim(), text.trim()).filter(String::isNotEmpty).joinToString(" "))) } - + val pickerScope = rememberCoroutineScope() + val currentState by rememberUpdatedState(state) + var pickerOwner by rememberSaveable { mutableStateOf(null) } + var preparingImage by remember(state.sessionId) { mutableStateOf(false) } val photoPicker = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> - if (uri != null) { - val bytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() } - val mime = context.contentResolver.getType(uri) ?: "image/jpeg" - if ( - bytes != null && - bytes.size <= MAX_GENERAL_CHAT_IMAGE_BYTES && - state.images.size < MAX_COMPOSER_IMAGES - ) { - viewModel.dispatch( - GeneralChatIntent.SetImages( - state.images + ComposerImage( - id = "android-" + UUID.randomUUID(), - dataUrl = "data:" + mime + ";base64," + - Base64.encodeToString(bytes, Base64.NO_WRAP), - mimeType = mime, - ), - ), - ) + val target = pickerOwner + pickerOwner = null + if (uri != null && target == state.sessionId && state.images.size < MAX_COMPOSER_IMAGES) { + preparingImage = true + pickerScope.launch { + try { + val prepared = prepareComposerImage(context.contentResolver, uri) + val latest = currentState + if (latest.sessionId == target && latest.images.size < MAX_COMPOSER_IMAGES) { + viewModel.dispatch(GeneralChatIntent.SetImages(latest.images + prepared)) + } + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + if (currentState.sessionId == target) { + Toast.makeText(context, R.string.chat_image_prepare_failed, Toast.LENGTH_LONG).show() + } + } finally { + if (currentState.sessionId == target) preparingImage = false + } } } } @@ -379,7 +369,8 @@ internal fun GeneralChatScreen( ComposerBar( draft = state.draft, images = state.images, - busy = state.busy, + busy = state.busy || preparingImage, + inputEnabled = !state.busy && !preparingImage, streaming = state.timeline.activeTurn != null, // Never consulted: general chat's capabilities do not require a // desktop, so the phase cannot gate the send. @@ -393,25 +384,17 @@ internal fun GeneralChatScreen( viewModel.dispatch(GeneralChatIntent.SetImages(state.images.filterNot { it.id == id })) }, onAttach = { - photoPicker.launch( - PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly), - ) + pickerOwner = state.sessionId + if (!launchComposerActivity(context, R.string.chat_photo_picker_unavailable) { + photoPicker.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) + }) pickerOwner = null }, onOpenModels = { showModelService = true }, onSelectModel = { viewModel.dispatch(GeneralChatIntent.SelectModel(it)) }, onSend = { viewModel.dispatch(GeneralChatIntent.Send) }, onStop = { viewModel.dispatch(GeneralChatIntent.Cancel) }, modifier = Modifier, - onVoice = { - voiceInput.launch( - Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply { - putExtra( - RecognizerIntent.EXTRA_LANGUAGE_MODEL, - RecognizerIntent.LANGUAGE_MODEL_FREE_FORM, - ) - }, - ) - }, + onVoice = voiceInput, ) } diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/InlineImage.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/InlineImage.kt index 666ac94932..bf1b70a435 100644 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/InlineImage.kt +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/InlineImage.kt @@ -19,7 +19,17 @@ internal fun decodeInlineImage(dataUrl: String): Bitmap? { if (payload.isEmpty()) return null return runCatching { val bytes = Base64.decode(payload, Base64.DEFAULT) - BitmapFactory.decodeByteArray(bytes, 0, bytes.size) + // The encoded size says nothing about decoded pixel memory. History may + // contain full-resolution photos from another client; these are thumbnails. + val options = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) + if (options.outWidth <= 0 || options.outHeight <= 0) return null + options.inSampleSize = 1 + while (maxOf(options.outWidth, options.outHeight) / options.inSampleSize > 512) { + options.inSampleSize *= 2 + } + options.inJustDecodeBounds = false + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) }.getOrNull() } diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/CreateSessionScreen.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/CreateSessionScreen.kt index 03e0cdbe00..96b982e0f5 100644 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/CreateSessionScreen.kt +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/CreateSessionScreen.kt @@ -1,10 +1,5 @@ package com.openbitfun.mobile.app.ui.remote -import android.app.Activity -import android.content.Intent -import android.speech.RecognizerIntent -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.contract.ActivityResultContracts import androidx.annotation.DrawableRes import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource @@ -47,6 +42,7 @@ import com.openbitfun.mobile.core.feature.session.HarnessProfilePolicy import com.openbitfun.mobile.core.feature.session.HarnessProfile import com.openbitfun.mobile.app.R import com.openbitfun.mobile.app.ui.chat.ComposerBar +import com.openbitfun.mobile.app.ui.chat.rememberComposerVoiceInput import com.openbitfun.mobile.app.ui.common.CircleControl import com.openbitfun.mobile.core.feature.connection.ConnectionPhase import com.openbitfun.mobile.core.feature.session.ChatComposerCapabilities @@ -185,13 +181,10 @@ internal fun CreateSessionScreen( } val selectedChoice = WorkspaceChoice(workspacePath, "", workspaceConnectionId, workspaceSshHost, workspaceId) - val voiceInput = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> - if (result.resultCode == Activity.RESULT_OK) { - val text = result.data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)?.firstOrNull().orEmpty() - if (text.isNotBlank()) { - draft = listOf(draft.trim(), text.trim()).filter(String::isNotEmpty).joinToString(" ") - } - } + val voiceInput = rememberComposerVoiceInput( + org.json.JSONArray(listOf(deviceId, workspaceConnectionId, workspacePath)).toString(), + ) { text -> + draft = listOf(draft.trim(), text.trim()).filter(String::isNotEmpty).joinToString(" ") } Column(modifier = modifier.fillMaxSize().testTag(CREATE_SESSION_TEST_TAG)) { @@ -338,16 +331,7 @@ internal fun CreateSessionScreen( onAttach = {}, onOpenModels = {}, onSelectModel = { selectedModelId = it }, - onVoice = { - voiceInput.launch( - Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply { - putExtra( - RecognizerIntent.EXTRA_LANGUAGE_MODEL, - RecognizerIntent.LANGUAGE_MODEL_FREE_FORM, - ) - }, - ) - }, + onVoice = voiceInput, onSend = { if (CreateSessionPresenter.canSubmit(draft, deviceId, busy)) { onIntent( diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/MobileScreen.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/MobileScreen.kt index 4cdde6ed04..9577f44e38 100644 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/MobileScreen.kt +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/MobileScreen.kt @@ -47,6 +47,7 @@ import androidx.lifecycle.viewmodel.compose.viewModel import com.openbitfun.mobile.app.R import com.openbitfun.mobile.app.platform.rememberWindowMetrics import com.openbitfun.mobile.app.state.MobileSurface +import com.openbitfun.mobile.app.state.resolveRoutedRemoteSessionId import com.openbitfun.mobile.app.state.rememberAppShellState import com.openbitfun.mobile.app.ui.account.AccountLoginScreen import com.openbitfun.mobile.app.ui.common.AdaptiveModalSurface @@ -183,12 +184,21 @@ internal fun MobileScreen(onAccountRestored: (Boolean) -> Unit = {}) { RemoteControlSource.NONE -> RemoteSessionUiState.Idle } val committedRemoteSessions = (activeRemoteState as? RemoteSessionUiState.Ready)?.sessions.orEmpty() - // Shell navigation is only a transient request while the shared store - // catches up. Once a delete succeeds the row disappears, which invalidates - // a stale shell request and lets the store's selection take over. - val routedSessionId = shell.remoteSessionId - ?.takeIf { requested -> committedRemoteSessions.any { it.id == requested } } - ?: (activeRemoteState as? RemoteSessionUiState.Ready)?.selectedSessionId + val pendingRemoteSessionId = shell.pendingRemoteSessionId + LaunchedEffect(pendingRemoteSessionId, activeRemoteState) { + val pending = pendingRemoteSessionId ?: return@LaunchedEffect + val ready = activeRemoteState as? RemoteSessionUiState.Ready ?: return@LaunchedEffect + shell.observeRemoteSessionOpen(pending, ready.selectedSessionId, ready.busy) + } + // A pending open routes before the current session page knows about the ID. + // Once it settles, valid shell requests and the store selection take over; + // a deleted row no longer routes because neither contains its ID. + val routedSessionId = resolveRoutedRemoteSessionId( + pendingSessionId = pendingRemoteSessionId, + requestedSessionId = shell.remoteSessionId, + committedSessionIds = committedRemoteSessions.mapTo(mutableSetOf()) { it.id }, + selectedSessionId = (activeRemoteState as? RemoteSessionUiState.Ready)?.selectedSessionId, + ) val activeWorkspaceDirectory = when (controlSummary.source) { RemoteControlSource.ACCOUNT_DEVICE -> accountWorkspaceDirectory RemoteControlSource.NONE -> WorkspaceSessionDirectoryUiState(emptyList()) diff --git a/src/apps/mobile/android/app/src/main/res/values-zh/strings.xml b/src/apps/mobile/android/app/src/main/res/values-zh/strings.xml index 23e3b6a6c8..f381448984 100644 --- a/src/apps/mobile/android/app/src/main/res/values-zh/strings.xml +++ b/src/apps/mobile/android/app/src/main/res/values-zh/strings.xml @@ -497,4 +497,6 @@ 消息操作 从队列移除 升级执行端后可调整消息顺序。 + 此设备暂时无法使用语音输入,请使用文字输入。 + 暂时无法打开照片选择器,请重试或使用其他照片应用。 diff --git a/src/apps/mobile/android/app/src/main/res/values/strings.xml b/src/apps/mobile/android/app/src/main/res/values/strings.xml index 59e00b52ed..4456541efe 100644 --- a/src/apps/mobile/android/app/src/main/res/values/strings.xml +++ b/src/apps/mobile/android/app/src/main/res/values/strings.xml @@ -512,4 +512,6 @@ Message actions Remove from queue Update the execution host to reorder messages. + Voice input is unavailable on this device. You can continue by typing. + The photo picker is unavailable. Try again or choose a different photo app. diff --git a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/state/AppShellStateTest.kt b/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/state/AppShellStateTest.kt index 988edfc6ca..14cebc9ebb 100644 --- a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/state/AppShellStateTest.kt +++ b/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/state/AppShellStateTest.kt @@ -30,26 +30,79 @@ class AppShellStateTest { shell.openRemoteConnect() shell.openRemoteSession("session") assertEquals("session", shell.remoteSessionId) + assertEquals("session", shell.pendingRemoteSessionId) assertFalse(shell.remoteConnectOpen) } + @Test fun pendingSessionRoutesBeforeItAppearsInTheCommittedList() { + val shell = state() + shell.openRemoteSession("workspace-session") + + assertEquals( + "workspace-session", + resolveRoutedRemoteSessionId( + pendingSessionId = shell.pendingRemoteSessionId, + requestedSessionId = shell.remoteSessionId, + committedSessionIds = emptySet(), + selectedSessionId = "previous-session", + ), + ) + + shell.observeRemoteSessionOpen("workspace-session", "previous-session", busy = false) + assertEquals("workspace-session", shell.pendingRemoteSessionId) + shell.observeRemoteSessionOpen("workspace-session", "previous-session", busy = true) + shell.observeRemoteSessionOpen("workspace-session", "previous-session", busy = false) + assertEquals(null, shell.pendingRemoteSessionId) + assertEquals( + "previous-session", + resolveRoutedRemoteSessionId( + pendingSessionId = shell.pendingRemoteSessionId, + requestedSessionId = shell.remoteSessionId, + committedSessionIds = emptySet(), + selectedSessionId = "previous-session", + ), + ) + } + + @Test fun successfulPendingOpenFallsBackToTheStoreSelection() { + val shell = state() + shell.openRemoteSession("workspace-session") + shell.observeRemoteSessionOpen("workspace-session", "workspace-session", busy = false) + + assertEquals(null, shell.pendingRemoteSessionId) + assertEquals( + "workspace-session", + resolveRoutedRemoteSessionId( + pendingSessionId = shell.pendingRemoteSessionId, + requestedSessionId = shell.remoteSessionId, + committedSessionIds = emptySet(), + selectedSessionId = "workspace-session", + ), + ) + } + @Test fun restoreAcceptsOldSavedStateAndRetainsNewConnectionRoute() { val legacy = listOf("REMOTE", false, "GENERAL", false, false, false, "", null, false, false) assertFalse(AppShellState.Saver.restore(legacy)!!.remoteConnectOpen) - // Older builds saved a scanner request at index 9 and nothing after it; - // that request meant the connect sheet was open. - val legacyScanner = legacy.dropLast(1) + true - assertTrue(AppShellState.Saver.restore(legacyScanner)!!.remoteConnectOpen) + // Older builds saved a retired connection-overlay request at index 9 + // and nothing after it; the request meant the account device sheet was + // open. + val legacyConnectionOverlay = legacy.dropLast(1) + true + assertTrue(AppShellState.Saver.restore(legacyConnectionOverlay)!!.remoteConnectOpen) // A build that also wrote index 10 is read from index 10. val legacyBoth = legacy + false - val closedWithScanFlag = legacyBoth.toMutableList().also { it[9] = true } - assertFalse(AppShellState.Saver.restore(closedWithScanFlag)!!.remoteConnectOpen) + val closedWithLegacyOverlay = legacyBoth.toMutableList().also { it[9] = true } + assertFalse(AppShellState.Saver.restore(closedWithLegacyOverlay)!!.remoteConnectOpen) val shell = state().apply { openRemoteConnect() } val saved = with(AppShellState.Saver) { scope.save(shell) }!! - assertEquals(11, (saved as List<*>).size) + assertEquals(12, (saved as List<*>).size) assertEquals(false, saved[9]) assertTrue(AppShellState.Saver.restore(saved)!!.remoteConnectOpen) + + val pending = state().apply { openRemoteSession("workspace-session") } + val savedPending = with(AppShellState.Saver) { scope.save(pending) }!! + assertEquals("workspace-session", AppShellState.Saver.restore(savedPending)!!.pendingRemoteSessionId) } @Test fun restoreMapsTheRetiredRemoteSettingsPageToTheOneSettingsPage() { diff --git a/src/apps/mobile/ios/OpenBitFun.xcodeproj/project.pbxproj b/src/apps/mobile/ios/OpenBitFun.xcodeproj/project.pbxproj index c0cbb293bb..c81e6be183 100644 --- a/src/apps/mobile/ios/OpenBitFun.xcodeproj/project.pbxproj +++ b/src/apps/mobile/ios/OpenBitFun.xcodeproj/project.pbxproj @@ -58,6 +58,8 @@ A90000000000000000000003 /* StreamingTextState.swift in Sources */ = {isa = PBXBuildFile; fileRef = B90000000000000000000003 /* StreamingTextState.swift */; }; A90000000000000000000005 /* ComposerDismissGesture.swift in Sources */ = {isa = PBXBuildFile; fileRef = B90000000000000000000005 /* ComposerDismissGesture.swift */; }; A90000000000000000000006 /* HistoryPageArrivalTracker.swift in Sources */ = {isa = PBXBuildFile; fileRef = B90000000000000000000006 /* HistoryPageArrivalTracker.swift */; }; + A90000000000000000000007 /* DictationDraftSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = B90000000000000000000007 /* DictationDraftSession.swift */; }; + A90000000000000000000008 /* ChatImageThumbnail.swift in Sources */ = {isa = PBXBuildFile; fileRef = B90000000000000000000008 /* ChatImageThumbnail.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -119,6 +121,8 @@ B90000000000000000000003 /* StreamingTextState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StreamingTextState.swift; sourceTree = ""; }; B90000000000000000000005 /* ComposerDismissGesture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComposerDismissGesture.swift; sourceTree = ""; }; B90000000000000000000006 /* HistoryPageArrivalTracker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HistoryPageArrivalTracker.swift; sourceTree = ""; }; + B90000000000000000000007 /* DictationDraftSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DictationDraftSession.swift; sourceTree = ""; }; + B90000000000000000000008 /* ChatImageThumbnail.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatImageThumbnail.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -143,7 +147,7 @@ D10000000000000000000009 /* Products */ = {isa = PBXGroup; children = (B10000000000000000000000 /* OpenBitFun.app */, B20000000000000000000000 /* OpenBitFunUITests.xctest */); name = Products; sourceTree = ""; }; D20000000000000000000001 /* OpenBitFunUITests */ = {isa = PBXGroup; children = (B20000000000000000000001 /* RemoteCodeSessionSendUITests.swift */, B20000000000000000000011 /* PromptSuggestionUITests.swift */); path = OpenBitFunUITests; sourceTree = ""; }; D10000000000000000000010 /* DesignSystem */ = {isa = PBXGroup; children = (B10000000000000000000013 /* GeneratedMobileDesignTokens.swift */, B10000000000000000000014 /* GeneratedMobilePreviewScenarios.swift */, B10000000000000000000015 /* MobileDesignGallery.swift */, B10000000000000000000018 /* AdaptiveModalComponents.swift */); path = DesignSystem; sourceTree = ""; }; - D10000000000000000000008 /* Infrastructure */ = {isa = PBXGroup; children = (B90000000000000000000003 /* StreamingTextState.swift */, B90000000000000000000005 /* ComposerDismissGesture.swift */, B90000000000000000000002, B10000000000000000000002 /* MobileAppModel.swift */, B10000000000000000000010 /* MobileCoreAdapter.swift */, B10000000000000000000017 /* MobileLocalization.swift */, B10000000000000000000024 /* MobileAppModel+FilePreview.swift */, B10000000000000000000025 /* MobileAppModel+Account.swift */, B10000000000000000000026 /* MobileAppModel+RemoteSession.swift */, B10000000000000000000027 /* MobileAppModel+GeneralChat.swift */, B10000000000000000000028 /* RemoteAuthorityGate.swift */, B10000000000000000000029 /* AccountFailureCopy.swift */, D10000000000000000000017 /* Platform */); path = Infrastructure; sourceTree = ""; }; + D10000000000000000000008 /* Infrastructure */ = {isa = PBXGroup; children = (B90000000000000000000008 /* ChatImageThumbnail.swift */, B90000000000000000000007 /* DictationDraftSession.swift */, B90000000000000000000003 /* StreamingTextState.swift */, B90000000000000000000005 /* ComposerDismissGesture.swift */, B90000000000000000000002, B10000000000000000000002 /* MobileAppModel.swift */, B10000000000000000000010 /* MobileCoreAdapter.swift */, B10000000000000000000017 /* MobileLocalization.swift */, B10000000000000000000024 /* MobileAppModel+FilePreview.swift */, B10000000000000000000025 /* MobileAppModel+Account.swift */, B10000000000000000000026 /* MobileAppModel+RemoteSession.swift */, B10000000000000000000027 /* MobileAppModel+GeneralChat.swift */, B10000000000000000000028 /* RemoteAuthorityGate.swift */, B10000000000000000000029 /* AccountFailureCopy.swift */, D10000000000000000000017 /* Platform */); path = Infrastructure; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -159,7 +163,7 @@ C91000000000000000000001 = {isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = (); inputPaths = (); outputPaths = ("$(TARGET_BUILD_DIR)/$(UNLOCALIZED_RESOURCES_FOLDER_PATH)/MiniApps"); alwaysOutOfDate = 1; runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "export PATH=\"/opt/homebrew/bin:/usr/local/bin:$PATH\"\nnode \"$SRCROOT/../miniapps/generate.cjs\" ios \"$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/MiniApps\"\n"; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ - C10000000000000000000002 /* Sources */ = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (A91000000000000000000008, A9F000000000000000000003, A9F000000000000000000002, A9F000000000000000000001, A91000000000000000000001, A90000000000000000000003, A90000000000000000000004, A90000000000000000000002, A90000000000000000000001, A10000000000000000000041, A10000000000000000000040, A10000000000000000000001, A10000000000000000000002, A10000000000000000000003, A10000000000000000000004, A10000000000000000000005, A10000000000000000000006, A10000000000000000000007, A10000000000000000000008, A10000000000000000000010, A10000000000000000000013, A10000000000000000000014, A10000000000000000000015, A10000000000000000000017, A10000000000000000000018, A10000000000000000000019, A10000000000000000000020, A10000000000000000000021, A10000000000000000000022, A10000000000000000000024, A10000000000000000000025, A10000000000000000000026, A10000000000000000000027, A10000000000000000000028, A10000000000000000000029, A10000000000000000000030, A10000000000000000000031, A10000000000000000000032, A10000000000000000000033, A10000000000000000000035, A10000000000000000000036, A10000000000000000000037, A10000000000000000000038, A90000000000000000000005, A90000000000000000000006); runOnlyForDeploymentPostprocessing = 0; }; + C10000000000000000000002 /* Sources */ = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (A91000000000000000000008, A90000000000000000000008, A90000000000000000000007, A9F000000000000000000003, A9F000000000000000000002, A9F000000000000000000001, A91000000000000000000001, A90000000000000000000003, A90000000000000000000004, A90000000000000000000002, A90000000000000000000001, A10000000000000000000041, A10000000000000000000040, A10000000000000000000001, A10000000000000000000002, A10000000000000000000003, A10000000000000000000004, A10000000000000000000005, A10000000000000000000006, A10000000000000000000007, A10000000000000000000008, A10000000000000000000010, A10000000000000000000013, A10000000000000000000014, A10000000000000000000015, A10000000000000000000017, A10000000000000000000018, A10000000000000000000019, A10000000000000000000020, A10000000000000000000021, A10000000000000000000022, A10000000000000000000024, A10000000000000000000025, A10000000000000000000026, A10000000000000000000027, A10000000000000000000028, A10000000000000000000029, A10000000000000000000030, A10000000000000000000031, A10000000000000000000032, A10000000000000000000033, A10000000000000000000035, A10000000000000000000036, A10000000000000000000037, A10000000000000000000038, A90000000000000000000005, A90000000000000000000006); runOnlyForDeploymentPostprocessing = 0; }; C20000000000000000000002 /* Sources */ = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (A20000000000000000000001 /* RemoteCodeSessionSendUITests.swift in Sources */, A20000000000000000000011 /* PromptSuggestionUITests.swift in Sources */); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ diff --git a/src/apps/mobile/ios/OpenBitFun/Features/Chat/ChatTimelineView.swift b/src/apps/mobile/ios/OpenBitFun/Features/Chat/ChatTimelineView.swift index 4ec91807fc..8fffd0ad97 100644 --- a/src/apps/mobile/ios/OpenBitFun/Features/Chat/ChatTimelineView.swift +++ b/src/apps/mobile/ios/OpenBitFun/Features/Chat/ChatTimelineView.swift @@ -1128,7 +1128,8 @@ private struct FullScreenTimelineImage: View { var body: some View { ZStack(alignment: .topTrailing) { OpenBitFunTheme.mediaBackground.ignoresSafeArea() - AsyncDecodedImage(dataURL: image.dataURL).ignoresSafeArea() + AsyncDecodedImage(dataURL: image.dataURL, maximumPixelSize: ChatImageThumbnail.fullScreenMaximumPixelSize) + .ignoresSafeArea() Button { dismiss() } label: { Image(systemName: "xmark").font(.system(size: 15, weight: .semibold)).foregroundStyle(OpenBitFunTheme.contentOnAction) .frame(width: 44, height: 44).background(OpenBitFunTheme.mediaControlBackground).clipShape(Circle()) @@ -1143,9 +1144,10 @@ struct AsyncDecodedImage: View { var data: Data? = nil var dataURL: String? = nil var fill = false + var maximumPixelSize = ChatImageThumbnail.maximumPixelSize @State private var image: UIImage? @State private var loading = true - private struct Source: Equatable { let data: Data?; let url: String? } + private struct Source: Equatable { let data: Data?; let url: String?; let maximumPixelSize: Int } var body: some View { Group { if let image { @@ -1156,19 +1158,20 @@ struct AsyncDecodedImage: View { Image(systemName: "photo").foregroundStyle(OpenBitFunTheme.muted) } } - .task(id: Source(data: data, url: dataURL)) { + .task(id: Source(data: data, url: dataURL, maximumPixelSize: maximumPixelSize)) { image = nil loading = true let bytes = data let url = dataURL + let pixelSize = maximumPixelSize let decoded = await Task.detached(priority: .userInitiated) { let source: Data? if let bytes { source = bytes } else if let url, let marker = url.range(of: "base64,") { source = Data(base64Encoded: String(url[marker.upperBound...])) } else { source = nil } - guard let source, let original = UIImage(data: source) else { return nil as UIImage? } - return original.preparingForDisplay() ?? original + guard let source, let thumbnail = ChatImageThumbnail.decode(source, maximumPixelSize: pixelSize) else { return nil as UIImage? } + return UIImage(cgImage: thumbnail) }.value guard !Task.isCancelled else { return } image = decoded diff --git a/src/apps/mobile/ios/OpenBitFun/Features/Chat/ComposerBar.swift b/src/apps/mobile/ios/OpenBitFun/Features/Chat/ComposerBar.swift index 36b6a62c6c..e01f6ac0d6 100644 --- a/src/apps/mobile/ios/OpenBitFun/Features/Chat/ComposerBar.swift +++ b/src/apps/mobile/ios/OpenBitFun/Features/Chat/ComposerBar.swift @@ -138,6 +138,7 @@ struct ComposerBar: View { .onChange(of: scenePhase) { if $0 != .active { speech.stop() } } .onChange(of: model.selectedSessionID) { _ in speech.stop() } .onChange(of: model.remoteTargetEpoch) { _ in speech.stop() } + .onChange(of: model.surface) { _ in speech.stop() } .onAppear { if model.composerModelPickerPreview { modelSelectorOpen = true @@ -274,7 +275,15 @@ struct ComposerBar: View { ZStack(alignment: .leading) { TextField( "", - text: $model.draft, + text: Binding( + get: { model.draft }, + set: { edited in + // Only user edits travel through this binding. Stop even + // while authorization is pending, before a queued result. + speech.stop() + model.draft = edited + } + ), prompt: Text(speech.isListening ? model.localized("正在聆听") : placeholder) .foregroundColor(speech.isListening ? OpenBitFunTheme.statusSuccess : OpenBitFunTheme.muted), axis: .vertical @@ -596,11 +605,24 @@ struct ComposerBar: View { } private func startVoiceInput() { - let existing = model.draft + let surface = model.surface + let sessionID = model.selectedSessionID + let targetEpoch = model.remoteTargetEpoch + var dictation = DictationDraftSession(draft: model.draft) speech.start( localeIdentifier: model.appLanguage == .simplifiedChinese ? "zh-CN" : "en-US", onPartial: { transcript in - model.draft = VoiceDraftPolicy.shared.merge(base: existing, transcript: transcript) + guard model.surface == surface, model.selectedSessionID == sessionID, + model.remoteTargetEpoch == targetEpoch, + let updated = dictation.apply( + transcript: transcript, + currentDraft: model.draft, + merge: { VoiceDraftPolicy.shared.merge(base: $0, transcript: $1) } + ) else { + speech.stop() + return + } + model.draft = updated }, onFailure: { message in model.showToast(model.localized(message)) } ) diff --git a/src/apps/mobile/ios/OpenBitFun/Infrastructure/ChatImageThumbnail.swift b/src/apps/mobile/ios/OpenBitFun/Infrastructure/ChatImageThumbnail.swift new file mode 100644 index 0000000000..267218e013 --- /dev/null +++ b/src/apps/mobile/ios/OpenBitFun/Infrastructure/ChatImageThumbnail.swift @@ -0,0 +1,21 @@ +import Foundation +import ImageIO + +/// Decode chat previews at bounded resolution, including photos from older peers. +enum ChatImageThumbnail { + static let maximumPixelSize = 1024 + static let fullScreenMaximumPixelSize = 2560 + + static func decode(_ data: Data, maximumPixelSize: Int = maximumPixelSize) -> CGImage? { + guard maximumPixelSize > 0 else { return nil } + let sourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary + guard let source = CGImageSourceCreateWithData(data as CFData, sourceOptions) else { return nil } + let options: [CFString: Any] = [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceThumbnailMaxPixelSize: maximumPixelSize, + kCGImageSourceShouldCacheImmediately: true, + ] + return CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) + } +} diff --git a/src/apps/mobile/ios/OpenBitFun/Infrastructure/DictationDraftSession.swift b/src/apps/mobile/ios/OpenBitFun/Infrastructure/DictationDraftSession.swift new file mode 100644 index 0000000000..492523a77d --- /dev/null +++ b/src/apps/mobile/ios/OpenBitFun/Infrastructure/DictationDraftSession.swift @@ -0,0 +1,25 @@ +/// A recognition result replaces the preceding partial transcript, never a user edit. +struct DictationDraftSession { + private let base: String + private var expectedDraft: String + private var acceptingResults = true + + init(draft: String) { + base = draft + expectedDraft = draft + } + + mutating func apply( + transcript: String, + currentDraft: String, + merge: (String, String) -> String + ) -> String? { + guard acceptingResults, currentDraft == expectedDraft else { + acceptingResults = false + return nil + } + let updated = merge(base, transcript) + expectedDraft = updated + return updated + } +} diff --git a/src/apps/mobile/ios/OpenBitFun/Infrastructure/Platform/SpeechInputController.swift b/src/apps/mobile/ios/OpenBitFun/Infrastructure/Platform/SpeechInputController.swift index 4329bd0bdf..27c8a328d3 100644 --- a/src/apps/mobile/ios/OpenBitFun/Infrastructure/Platform/SpeechInputController.swift +++ b/src/apps/mobile/ios/OpenBitFun/Infrastructure/Platform/SpeechInputController.swift @@ -93,6 +93,7 @@ final class SpeechInputController: ObservableObject { } private func finishRecognition() { + let hadAudioCapture = request != nil || tapInstalled || audioEngine.isRunning if audioEngine.isRunning { audioEngine.stop() } @@ -105,6 +106,10 @@ final class SpeechInputController: ObservableObject { recognitionTask?.cancel() recognitionTask = nil isListening = false - try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) + // Editing an idle draft may invalidate authorization callbacks too, but + // must not deactivate audio owned by another feature. + if hadAudioCapture { + try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) + } } } diff --git a/src/apps/mobile/ios/README.md b/src/apps/mobile/ios/README.md index a0142ec602..9fa7772f17 100644 --- a/src/apps/mobile/ios/README.md +++ b/src/apps/mobile/ios/README.md @@ -49,6 +49,14 @@ export DEVELOPER_DIR="$HOME/Downloads/Xcode.app/Contents/Developer" ./Testing/run-pure-swift-tests.sh ``` +This also covers dictation draft ownership (partial-result corrections and +manual edits) and ImageIO thumbnail decoding (large photos, camera rotation, +full-screen bounds, and invalid bytes). Chat previews decode off the UI thread +at up to 1024 pixels on the long edge; the full-screen viewer uses up to 2560. +Typing during dictation keeps the manual edit and stops the recognition attempt, +including while authorization is pending. Recognition callbacks also check the active +surface, session, and remote target generation before updating a draft. + After changing shared Kotlin code, regenerate the framework with the same compatible toolchain before building the Xcode project. Xcode links the existing XCFramework; its build does not rebuild Kotlin. Compiling a Kotlin target alone also does not diff --git a/src/apps/mobile/ios/Testing/ChatImageThumbnailTests.swift b/src/apps/mobile/ios/Testing/ChatImageThumbnailTests.swift new file mode 100644 index 0000000000..a20ee075ba --- /dev/null +++ b/src/apps/mobile/ios/Testing/ChatImageThumbnailTests.swift @@ -0,0 +1,40 @@ +import Foundation +import CoreGraphics +import ImageIO + +@main +struct ChatImageThumbnailTests { + static func main() { + let large = encodedImage(width: 4000, height: 3000) + let decoded = ChatImageThumbnail.decode(large)! + precondition(decoded.width == 1024 && decoded.height == 768) + precondition(decoded.bytesPerRow * decoded.height <= 1024 * 1024 * 4, + "Decoded preview memory must be bounded, independent of original pixels") + let fullScreen = ChatImageThumbnail.decode(large, maximumPixelSize: ChatImageThumbnail.fullScreenMaximumPixelSize)! + precondition(fullScreen.width == 2560 && fullScreen.height == 1920, + "Opening a photo keeps more detail than its chat thumbnail") + + let rotated = ChatImageThumbnail.decode(encodedImage(width: 4000, height: 3000, orientation: 6))! + precondition(rotated.width == 768 && rotated.height == 1024, + "Camera orientation must be applied while creating the thumbnail") + let small = ChatImageThumbnail.decode(encodedImage(width: 32, height: 24))! + precondition(small.width == 32 && small.height == 24) + precondition(ChatImageThumbnail.decode(Data()) == nil) + precondition(ChatImageThumbnail.decode(Data("not an image".utf8)) == nil) + print("Chat image thumbnail tests passed") + } + + static func encodedImage(width: Int, height: Int, orientation: Int = 1) -> Data { + let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, + bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)! + context.setFillColor(CGColor(red: 0.2, green: 0.4, blue: 0.6, alpha: 1)) + context.fill(CGRect(x: 0, y: 0, width: width, height: height)) + let data = NSMutableData() + let destination = CGImageDestinationCreateWithData(data, "public.jpeg" as CFString, 1, nil)! + CGImageDestinationAddImage(destination, context.makeImage()!, + [kCGImagePropertyOrientation: orientation] as CFDictionary) + precondition(CGImageDestinationFinalize(destination)) + return data as Data + } +} diff --git a/src/apps/mobile/ios/Testing/DictationDraftSessionTests.swift b/src/apps/mobile/ios/Testing/DictationDraftSessionTests.swift new file mode 100644 index 0000000000..3f6c335d4a --- /dev/null +++ b/src/apps/mobile/ios/Testing/DictationDraftSessionTests.swift @@ -0,0 +1,25 @@ +@main +struct DictationDraftSessionTests { + static func main() { + let merge: (String, String) -> String = { $0 + $1 } + var session = DictationDraftSession(draft: "existing ") + precondition(session.apply(transcript: "hel", currentDraft: "existing ", merge: merge) == "existing hel") + precondition(session.apply(transcript: "hello", currentDraft: "existing hel", merge: merge) == "existing hello") + precondition(session.apply(transcript: "help", currentDraft: "existing hello", merge: merge) == "existing help", + "Recognition corrections replace the previous partial, without duplication") + + precondition(session.apply(transcript: "help me", currentDraft: "existing help and typing", merge: merge) == nil, + "Typing during dictation must never be overwritten") + precondition(session.apply(transcript: "late result", currentDraft: "existing help", merge: merge) == nil, + "An invalidated recognition attempt cannot resume writing") + + var beforeFirstResult = DictationDraftSession(draft: "before permission prompt") + precondition(beforeFirstResult.apply(transcript: "speech", currentDraft: "edited during permission prompt", merge: merge) == nil) + var deleted = DictationDraftSession(draft: "delete me") + precondition(deleted.apply(transcript: "speech", currentDraft: "", merge: merge) == nil, + "Deleting the draft is a user edit too") + var restarted = DictationDraftSession(draft: "new base ") + precondition(restarted.apply(transcript: "new speech", currentDraft: "new base ", merge: merge) == "new base new speech") + print("Dictation draft session tests passed") + } +} diff --git a/src/apps/mobile/ios/Testing/run-pure-swift-tests.sh b/src/apps/mobile/ios/Testing/run-pure-swift-tests.sh index c7bd14ac5e..183f361943 100755 --- a/src/apps/mobile/ios/Testing/run-pure-swift-tests.sh +++ b/src/apps/mobile/ios/Testing/run-pure-swift-tests.sh @@ -43,8 +43,6 @@ xcrun --sdk macosx swiftc \ -o "$OUTPUT_DIR/mobile-process-group-tests" "$OUTPUT_DIR/mobile-process-group-tests" -printf '%s\n' 'iOS pure Swift focused tests passed.' - xcrun --sdk macosx swiftc \ "$IOS_DIR/OpenBitFun/Infrastructure/StartupRevealPreference.swift" \ "$SCRIPT_DIR/StartupRevealPreferenceTests.swift" \ @@ -56,3 +54,17 @@ xcrun --sdk macosx swiftc \ "$SCRIPT_DIR/HistoryPageArrivalTrackerTests.swift" \ -o "$OUTPUT_DIR/history-page-arrival-tracker-tests" "$OUTPUT_DIR/history-page-arrival-tracker-tests" + +xcrun --sdk macosx swiftc \ + "$IOS_DIR/OpenBitFun/Infrastructure/DictationDraftSession.swift" \ + "$SCRIPT_DIR/DictationDraftSessionTests.swift" \ + -o "$OUTPUT_DIR/dictation-draft-session-tests" +"$OUTPUT_DIR/dictation-draft-session-tests" + +xcrun --sdk macosx swiftc \ + "$IOS_DIR/OpenBitFun/Infrastructure/ChatImageThumbnail.swift" \ + "$SCRIPT_DIR/ChatImageThumbnailTests.swift" \ + -o "$OUTPUT_DIR/chat-image-thumbnail-tests" +"$OUTPUT_DIR/chat-image-thumbnail-tests" + +printf '%s\n' 'iOS pure Swift focused tests passed.' diff --git a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionStore.kt b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionStore.kt index 111aad7c8d..aa2f1ecd89 100644 --- a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionStore.kt +++ b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionStore.kt @@ -598,24 +598,37 @@ public class RemoteSessionStore internal constructor( private fun publishCommittedCreate(session: RemoteSession, previous: RemoteSessionUiState.Ready?): Long { projectConfirmedCreatedSession(session) - if (_state.value !is RemoteSessionUiState.Ready) { - publishAuthorityReady(RemoteSessionUiState.Ready( - sessions = listOf(session), - selectedSessionId = session.id, - timeline = null, - busy = true, - permissionMode = previous?.permissionMode, - permissionModeFailure = previous?.permissionModeFailure, - query = previous?.query.orEmpty(), - agentFilter = previous?.agentFilter ?: SessionAgentFilter.ALL, - hasMore = previous?.hasMore ?: false, - hasMoreMessages = false, - modelCatalog = modelCatalog ?: previous?.modelCatalog, - modelCatalogFailure = modelCatalogFailure ?: previous?.modelCatalogFailure, - draft = "", - )) - } - return (_state.value as RemoteSessionUiState.Ready).revision + val current = _state.value as? RemoteSessionUiState.Ready + return publishAuthorityReady( + if (current != null) { + current.copy( + selectedSessionId = session.id, + timeline = null, + busy = true, + hasMoreMessages = false, + draft = "", + lastSentMessage = null, + historyLoadState = HistoryLoadState.IDLE, + promptSuggestion = null, + ) + } else { + RemoteSessionUiState.Ready( + sessions = listOf(session), + selectedSessionId = session.id, + timeline = null, + busy = true, + permissionMode = previous?.permissionMode, + permissionModeFailure = previous?.permissionModeFailure, + query = previous?.query.orEmpty(), + agentFilter = previous?.agentFilter ?: SessionAgentFilter.ALL, + hasMore = previous?.hasMore ?: false, + hasMoreMessages = false, + modelCatalog = modelCatalog ?: previous?.modelCatalog, + modelCatalogFailure = modelCatalogFailure ?: previous?.modelCatalogFailure, + draft = "", + ) + }, + ) } private fun publishAuthorityReady(ready: RemoteSessionUiState.Ready): Long { @@ -1432,13 +1445,36 @@ public class RemoteSessionStore internal constructor( if (!succeedCreate(requestId, generation, confirmedSession, commitRevision)) return@launch activeCreateGeneration = null - intent.modelId?.trim()?.takeIf(String::isNotEmpty)?.let { modelId -> - transport.send( - RemoteCommand(cmd = "set_session_model", sessionId = sessionId, modelId = modelId), - ) - if (!isCurrentWork(operationToken)) return@launch + val modelSelection = intent.modelId?.trim()?.takeIf(String::isNotEmpty)?.let { modelId -> + async { + try { + Result.success( + transport.send( + RemoteCommand(cmd = "set_session_model", sessionId = sessionId, modelId = modelId), + ), + ) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (error: Throwable) { + Result.failure(error) + } + } } val opened = openSession(sessionId, operationToken) ?: return@launch + if (!isCurrentWork(operationToken)) return@launch + // Hydration may finish before model selection. Publish the transcript + // now, retaining typing and mailbox updates received while waiting. + val hydrated = _state.value as? RemoteSessionUiState.Ready ?: return@launch + publishAuthorityReady(hydrated.copy( + timeline = timelineStore.snapshot(), + permissionMode = opened.permission.mode, + permissionModeFailure = opened.permission.failure, + hasMoreMessages = opened.hasMoreMessages, + )) + modelSelection?.await()?.getOrThrow()?.let { response -> + if (!isCurrentWork(operationToken)) return@launch + timelineStore.setSelectedModelId(response.modelId ?: intent.modelId.orEmpty()) + } intent.instruction.trim().takeIf(String::isNotEmpty)?.let { instruction -> val sent = transport.send( RemoteCommand( @@ -1455,20 +1491,12 @@ public class RemoteSessionStore internal constructor( val page = listSessions(0, current?.query.orEmpty(), current?.agentFilter ?: SessionAgentFilter.ALL) if (!isCurrentWork(operationToken)) return@launch commitSessionPage(page) - publishAuthorityReady(RemoteSessionUiState.Ready( + val ready = _state.value as? RemoteSessionUiState.Ready ?: return@launch + publishAuthorityReady(ready.copy( sessions = page.sessions, - selectedSessionId = sessionId, timeline = timelineStore.snapshot(), busy = false, - permissionMode = opened.permission.mode, - permissionModeFailure = opened.permission.failure, - query = current?.query.orEmpty(), - agentFilter = current?.agentFilter ?: SessionAgentFilter.ALL, hasMore = page.hasMore, - hasMoreMessages = opened.hasMoreMessages, - modelCatalog = modelCatalog ?: current?.modelCatalog, - modelCatalogFailure = modelCatalogFailure ?: current?.modelCatalogFailure, - draft = "", )) markConnected() refreshModelCatalog() diff --git a/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionStoreTest.kt b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionStoreTest.kt index e66c034b33..0516f07b26 100644 --- a/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionStoreTest.kt +++ b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionStoreTest.kt @@ -1039,13 +1039,63 @@ class RemoteSessionStoreTest { val committed = assertIs(store.createOperation.value) assertEquals("s-new", committed.createdSessionId) val committedReady = assertIs(store.state.value) - assertEquals(committed.commitRevision, committedReady.revision) + assertTrue(committed.commitRevision <= committedReady.revision) assertTrue(committedReady.sessions.any { it.id == committed.createdSessionId }) + assertEquals(committed.createdSessionId, committedReady.selectedSessionId) + assertEquals(committed.createdSessionId, committedReady.timeline?.sessionId) + assertTrue(committedReady.busy) store.stop() runCurrent() assertIs(store.createOperation.value) } + @Test + fun createModelFailureDoesNotCancelSessionHydration() = runTest { + val transport = FakeSessionTransport().apply { + modelSelectionFailure = RelayFailure.NetworkUnreachable + } + val store = RemoteSessionStore(this, transport) + store.dispatch(RemoteSessionIntent.CreateSessionOperation("model-failed", "code", "", "", "model-primary", "/repo")) + runCurrent() + + assertIs(store.createOperation.value) + val ready = assertIs(store.state.value) + assertEquals("s-new", ready.selectedSessionId) + assertEquals("s-new", ready.timeline?.sessionId) + store.stop() + } + + @Test + fun createHydrationAndModelSelectionPreserveNewTypingAndOrderTheInitialMessage() = runTest { + val transport = FakeSessionTransport() + val modelGate = CompletableDeferred() + val historyGate = CompletableDeferred() + transport.commandGates["set_session_model"] = modelGate + transport.initialHistoryGate = historyGate + val store = RemoteSessionStore(this, transport) + store.dispatch(RemoteSessionIntent.CreateSessionOperation("create-with-model", "code", "", "first instruction", "model-primary", "/repo")) + runCurrent() + store.dispatch(RemoteSessionIntent.UpdateDraft("typed during history")) + historyGate.complete(Unit) + runCurrent() + + val hydrated = assertIs(store.state.value) + assertEquals("s-new", hydrated.timeline?.sessionId) + assertEquals("typed during history", hydrated.draft) + assertTrue(hydrated.busy) + assertTrue(transport.commands.none { it.cmd == "send_message" }) + + store.dispatch(RemoteSessionIntent.UpdateDraft("next question")) + modelGate.complete(Unit) + runCurrent() + val ready = assertIs(store.state.value) + assertEquals("next question", ready.draft) + assertEquals("model-primary", ready.timeline?.selectedModelId) + assertFalse(ready.busy) + assertEquals("first instruction", transport.commands.single { it.cmd == "send_message" }.content) + store.stop() + } + @Test fun stopWhileOpenInitializationIsGatedKeepsCommittedProjection() = runTest { val transport = FakeSessionTransport() @@ -1745,6 +1795,11 @@ class RemoteSessionStoreTest { assertFalse(failed.busy) transport.sendMessageFailure = null + // A failed network send gates retries until the host stream reconnects. + assertEquals(ConnectionPhase.RECONNECTING, store.connectionPhase.value) + requireNotNull(transport.streamCaughtUp).invoke() + runCurrent() + assertEquals(ConnectionPhase.CONNECTED, store.connectionPhase.value) val gate = CompletableDeferred() transport.commandGates["send_message"] = gate store.dispatch(RemoteSessionIntent.SendMessage("s-code", "look", images))