Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
refactor(i18n): view-model messages, errors and the app-control ask in resources
Durganshu9de26e7d1d8a
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex 4004fb8..cc7bfce 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -1,6 +1,7 @@package com.gotcha.agentimport android.content.Context+import com.gotcha.Rimport com.gotcha.agent.skills.SkillPromptBuilderimport com.gotcha.agent.skills.SkillRegistryimport com.gotcha.connectors.ConnectorRegistry@@ -10,6 +11,8 @@ import com.gotcha.data.GotchaStorageimport com.gotcha.data.RunSummaryimport com.gotcha.data.Settingsimport com.gotcha.data.ToolSummary+import com.gotcha.i18n.StringLookup+import com.gotcha.i18n.stringLookupimport com.gotcha.llm.ChatMessageimport com.gotcha.llm.LLMClientimport com.gotcha.llm.ToolCall@@ -48,19 +51,15 @@ private enum class ConfirmDecision { APPROVED, DENIED, TIMED_OUT }private val WHITESPACE = Regex("\\s+")/** Maps API/network failures to a short, user-readable message. */-internal fun friendlyAgentError(e: Exception): String = HumanReadableError.format(e)--/** Shown when the model server sends nothing back within the API timeout (#104). */-internal const val MODEL_TIMEOUT_MESSAGE =- "The model didn't respond in time. Try again, or raise the API timeout in Settings → AI → AI Configuration."+internal fun friendlyAgentError(e: Exception, strings: StringLookup): String = HumanReadableError.format(e, strings)/*** [friendlyAgentError] for a failed model request. A timeout here means the model* never answered, which the generic network wording ("try a smaller request")* does not say; the generic one stays for speech-to-text and the rest.*/-internal fun friendlyModelError(e: Exception): String =- if (e is SocketTimeoutException) MODEL_TIMEOUT_MESSAGE else friendlyAgentError(e)+internal fun friendlyModelError(e: Exception, strings: StringLookup): String =+ if (e is SocketTimeoutException) strings(R.string.error_model_timeout) else friendlyAgentError(e, strings)/*** The core agent loop, extracted from ChatViewModel so it can run both inside@@ -587,7 +586,7 @@ class AgentEngine(} catch (e: Exception) {lastModelRequestFailed = true// Also spoken: on a voice call an unannounced return is silence.- val error = friendlyModelError(e)+ val error = friendlyModelError(e, appContext.stringLookup())events.onUi(MessageKind.ERROR, error)events.onAssistantReply(error)emitRunSummary(error, succeeded = false)diff --git a/app/src/main/java/com/gotcha/agent/ChatRunner.kt b/app/src/main/java/com/gotcha/agent/ChatRunner.ktindex 5754c25..9b0f6a7 100644--- a/app/src/main/java/com/gotcha/agent/ChatRunner.kt+++ b/app/src/main/java/com/gotcha/agent/ChatRunner.kt@@ -3,6 +3,7 @@ package com.gotcha.agentimport android.app.Applicationimport android.app.Notificationimport com.gotcha.GotchaApp+import com.gotcha.Rimport com.gotcha.audio.AudioModelimport com.gotcha.audio.AudioProviderimport com.gotcha.audio.CompletionFeedback@@ -171,8 +172,7 @@ class ChatRunner(private val app: Application) : AgentEvents {withContext(Dispatchers.Main) {appendTranscript(MessageKind.TOOL,- "Assistant updated your profile: " +- merged.changedFields.joinToString(", ") + "."+ app.getString(R.string.runner_profile_updated, merged.changedFields.joinToString(", ")))}ToolResult.ok(@@ -587,7 +587,7 @@ class ChatRunner(private val app: Application) : AgentEvents {engine.run(agent)} catch (_: CancellationException) {stopped = true- appendTranscript(MessageKind.ERROR, "Agent was interrupted by the user.")+ appendTranscript(MessageKind.ERROR, app.getString(R.string.runner_interrupted_by_user))// The interrupt may have orphaned an assistant with tool_calls but no// matching tool results. Repair it in NonCancellable before the next// turn is built — otherwise the provider 400s every later request.@@ -917,16 +917,16 @@ class ChatRunner(private val app: Application) : AgentEvents {override fun onForegroundControlChanged(active: Boolean, appLabel: String?) {if (active) {- val text = ForegroundControlRequest.controllingMessage(appLabel)+ val text = ForegroundControlRequest.controllingMessage(appLabel, app.stringLookup())setState { it.copy(foregroundControlStatus = text) }foregroundControlIndicator.showControlling(text)} else {- setState { it.copy(foregroundControlStatus = ForegroundControlRequest.DONE_MESSAGE) }+ setState { it.copy(foregroundControlStatus = app.getString(ForegroundControlRequest.DONE_MESSAGE)) }// In the app the status line says it; outside, the card over their app does.if (appInForeground) {foregroundControlIndicator.dismiss()} else {- foregroundControlIndicator.showDone(ForegroundControlRequest.DONE_MESSAGE)+ foregroundControlIndicator.showDone(app.getString(ForegroundControlRequest.DONE_MESSAGE))}}}@@ -950,12 +950,12 @@ class ChatRunner(private val app: Application) : AgentEvents {val gate = foregroundControlGateif (foregroundControl != null && gate != null && confirmationOverlay.canShow()) {confirmationOverlay.show(- summary = foregroundControl.promptText(),+ summary = foregroundControl.promptText(app.stringLookup()),onAllow = { gate.complete(true) },onDeny = { gate.complete(false) },- title = foregroundControl.title,- allowLabel = ForegroundControlRequest.ALLOW_LABEL,- denyLabel = ForegroundControlRequest.DENY_LABEL+ title = foregroundControl.title(app.stringLookup()),+ allowLabel = app.getString(ForegroundControlRequest.ALLOW_LABEL),+ denyLabel = app.getString(ForegroundControlRequest.DENY_LABEL))return}@@ -998,7 +998,8 @@ class ChatRunner(private val app: Application) : AgentEvents {private fun currentBackgroundHint(): String = backgroundHintText(vibrate = settings.notifyVibrationEnabled,chime = settings.notifyChimeEnabled,- notify = settings.chatCompletionNotificationsEnabled && completionNotifier.canPost()+ notify = settings.chatCompletionNotificationsEnabled && completionNotifier.canPost(),+ text = app.stringLookup())/**@@ -1074,7 +1075,7 @@ class ChatRunner(private val app: Application) : AgentEvents {session.displayMessages} else {val nextId = session.displayMessages.maxOf { it.id } + 1- session.displayMessages + UiMessage(nextId, MessageKind.ERROR, INTERRUPTED_NOTICE)+ session.displayMessages + UiMessage(nextId, MessageKind.ERROR, app.getString(R.string.runner_interrupted_notice))}historyRepository.saveSession(session.copy(messages = closeOrphanedToolCalls(session.messages), displayMessages = shown),@@ -1084,8 +1085,15 @@ class ChatRunner(private val app: Application) : AgentEvents {!localNotificationStore.isChatSensitive(sessionId, session.personaId)localNotificationStore.addEntry(category = NotificationCategory.TASK_FINISHED,- title = if (named) "Interrupted: ${session.title}" else "Task interrupted",- body = INTERRUPTED_INBOX_BODY,+ title = if (named) {+ app.getString(+ R.string.runner_interrupted_title,+ ChatTitle.display(session.title, app.stringLookup())+ )+ } else {+ app.getString(R.string.runner_interrupted_title_anonymous)+ },+ body = app.getString(R.string.runner_interrupted_inbox_body),target = NotificationTarget.Chat(sessionId))_inboxChanges.update { it + 1 }@@ -1137,10 +1145,6 @@ class ChatRunner(private val app: Application) : AgentEvents {private const val MIGRATED_CHAT_DIRS_KEY = "migrated_chat_dirs_v1"/** Ends the chat of a run that died with the process; see [reportInterruptedRun]. */- private const val INTERRUPTED_NOTICE = "This task was interrupted: Android closed Gotcha while it was " +- "working, usually to free memory. Send a message to pick up where it left off."- private const val INTERRUPTED_INBOX_BODY = "Android closed Gotcha while it was working on this task. " +- "Tap to open the chat and pick up where it left off."@Volatileprivate var fallback: ChatRunner? = nulldiff --git a/app/src/main/java/com/gotcha/agent/ChatTitle.kt b/app/src/main/java/com/gotcha/agent/ChatTitle.ktindex 98943e3..baa1483 100644--- a/app/src/main/java/com/gotcha/agent/ChatTitle.kt+++ b/app/src/main/java/com/gotcha/agent/ChatTitle.kt@@ -1,6 +1,8 @@package com.gotcha.agent+import com.gotcha.Rimport com.gotcha.data.isScreenCapture+import com.gotcha.i18n.StringLookupimport com.gotcha.llm.ChatMessage/**@@ -33,6 +35,17 @@ object ChatTitle {private const val NEW_CHAT = "New Chat"+ /**+ * [title] as the user sees it. The placeholder names ([NEW_CHAT], [IMAGE_CHAT])+ * are stored in English, so they are recognised as placeholders whatever the+ * display language; this shows them in it.+ */+ fun display(title: String, strings: StringLookup): String = when (title) {+ NEW_CHAT -> strings(R.string.chat_title_new)+ IMAGE_CHAT -> strings(R.string.chat_title_image)+ else -> title+ }+/*** The first thing the user wrote in the chat, trimmed, or null while every* message so far is attachments alone. An image-only message carries adiff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex 0c9e708..642733c 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -7,8 +7,11 @@ import android.graphics.BitmapFactoryimport android.net.Uriimport android.os.Buildimport android.provider.OpenableColumns+import androidx.annotation.PluralsRes+import androidx.annotation.StringResimport androidx.lifecycle.AndroidViewModelimport androidx.lifecycle.viewModelScope+import com.gotcha.Rimport com.gotcha.audio.AudioModelimport com.gotcha.audio.AudioProviderimport com.gotcha.audio.SttEngine@@ -23,6 +26,8 @@ import com.gotcha.data.Settingsimport com.gotcha.data.documentPromptTextimport com.gotcha.i18n.Languageimport com.gotcha.i18n.SpokenPhrases+import com.gotcha.i18n.StringLookup+import com.gotcha.i18n.stringLookupimport com.gotcha.llm.ChatMessageimport com.gotcha.llm.LLMClientimport com.gotcha.marketing.PosterRenderer@@ -131,16 +136,20 @@ internal fun shortTitle(text: String, max: Int = 40): String {return atWord.trimEnd(',', '.', ';', ':', ' ') + "…"}-internal fun backgroundHintText(vibrate: Boolean, chime: Boolean, notify: Boolean = false): String {- val base = "Gotcha is working in the background. You can use another app while it works"+internal fun backgroundHintText(vibrate: Boolean, chime: Boolean, notify: Boolean = false, text: StringLookup): String {+ val base = text(R.string.hint_background)val signal = when {- notify -> "Gotcha will notify you when the task is finished"- vibrate && chime -> "your phone will buzz and chime when it's done"- vibrate -> "your phone will buzz when it's done"- chime -> "your phone will chime when it's done"+ notify -> R.string.hint_signal_notify+ vibrate && chime -> R.string.hint_signal_buzz_chime+ vibrate -> R.string.hint_signal_buzz+ chime -> R.string.hint_signal_chimeelse -> null}- return if (signal == null) "$base." else "$base — $signal."+ return if (signal == null) {+ text(R.string.hint_background_alone, base)+ } else {+ text(R.string.hint_background_with_signal, base, text(signal))+ }}@kotlinx.serialization.Serializable@@ -445,7 +454,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), C// the user can browse other chats but must let the current run finish.if (_uiState.value.isBusy || _uiState.value.runningSessionId != null) returnif (client == null) {- appendUi(MessageKind.ERROR, "No API key configured. Open settings to add one.")+ appendUi(MessageKind.ERROR, str(R.string.chat_vm_no_api_key_configured_open))return}val isVoice = isVoiceInput || lastInputWasVoice@@ -549,7 +558,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Cif (trimmed.isEmpty() && attachments.isNullOrEmpty()) returnif (_uiState.value.isBusy || _uiState.value.runningSessionId != null) returnif (client == null) {- appendUi(MessageKind.ERROR, "No API key configured. Open settings to add one.")+ appendUi(MessageKind.ERROR, str(R.string.chat_vm_no_api_key_configured_open))return}lastInputWasVoice = false@@ -645,12 +654,10 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Cstate.copy(pendingAttachments = queue)}if (overCount > 0) {- errors += "You can attach up to ${ComposerAttachment.MAX_PER_MESSAGE} files per message — " +- "skipped ${plural(overCount, "file")}."+ errors += quantityStr(R.plurals.chat_vm_too_many_files, overCount, ComposerAttachment.MAX_PER_MESSAGE)}if (overText > 0) {- errors += "The attached documents are too long to send together — " +- "skipped ${plural(overText, "document")}. Send them in separate messages."+ errors += quantityStr(R.plurals.chat_vm_documents_too_long, overText)}errors.forEach { appendUi(MessageKind.ERROR, it) }}@@ -671,7 +678,15 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Cprivate fun List<ComposerAttachment>.documentChars(): Int =sumOf { (it as? ComposerAttachment.Document)?.attachment?.text?.length ?: 0 }- private fun plural(count: Int, noun: String): String = if (count == 1) "1 $noun" else "$count ${noun}s"+ /** This app's strings, in the display language. */+ private fun strings(): StringLookup = getApplication<Application>().stringLookup()++ /** This app's string [id], in the display language. */+ private fun str(@StringRes id: Int, vararg args: Any): String = getApplication<Application>().getString(id, *args)++ /** A plural of [count], formatted with the count first and then [args]. */+ private fun quantityStr(@PluralsRes id: Int, count: Int, vararg args: Any): String =+ getApplication<Application>().resources.getQuantityString(id, count, count, *args)/*** Reads one picked file into an attachment. A failure carries the message to@@ -688,13 +703,26 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), C// Both loaders return null when the stream cannot be opened; treat that// like any other failed pick so the user gets a visible error instead of// a silent no-op.- if (attachment != null) Result.success(attachment) else Result.failure(Exception("Could not read that file."))+ if (attachment != null) {+ Result.success(+ attachment+ )+ } else {+ Result.failure(Exception(str(R.string.chat_vm_could_not_read_that_file_2)))+ }} catch (e: CancellationException) {throw e} catch (e: DocumentError) {- Result.failure(Exception(e.message ?: "Could not read that file."))+ Result.failure(Exception(e.message ?: str(R.string.chat_vm_could_not_read_that_file_2)))} catch (e: Exception) {- Result.failure(Exception("Could not read that file: ${HumanReadableError.format(e)}"))+ Result.failure(+ Exception(+ str(+ R.string.chat_vm_could_not_read_that_file,+ HumanReadableError.format(e, strings())+ )+ )+ )}/**@@ -797,7 +825,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Cif (!granted) {appendUi(MessageKind.ERROR,- "Microphone permission not granted. Enable it in Settings → Permissions."+ str(R.string.chat_vm_microphone_permission_not_granted_enable))return}@@ -805,7 +833,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Cif (started) {_uiState.update { it.copy(isListening = true) }} else {- appendUi(MessageKind.ERROR, "Failed to start speech recognition.")+ appendUi(MessageKind.ERROR, str(R.string.chat_vm_failed_to_start_speech_recognition))}}settings.sttProvider.isApiBased() -> {@@ -813,26 +841,26 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), CappendUi(MessageKind.ERROR,if (settings.sttProvider == AudioProvider.SAMOSA_AI) {- "Samosa STT is not configured. Sign in from Settings → Speech."+ str(R.string.chat_vm_samosa_stt_is_not_configured)} else {- "No STT API URL configured in settings."+ str(R.string.chat_vm_no_stt_api_url_configured)})return}if (settings.sttApiModel.isBlank()) {- appendUi(MessageKind.ERROR, "No STT model selected. Refresh audio models in settings.")+ appendUi(MessageKind.ERROR, str(R.string.chat_vm_no_stt_model_selected_refresh))return}val started = sttEngine.startRecording()if (started) {_uiState.update { it.copy(isRecording = true) }} else {- appendUi(MessageKind.ERROR, "Failed to start recording.")+ appendUi(MessageKind.ERROR, str(R.string.chat_vm_failed_to_start_recording))}}else -> {- appendUi(MessageKind.ERROR, "No STT provider configured. Enable one in settings.")+ appendUi(MessageKind.ERROR, str(R.string.chat_vm_no_stt_provider_configured_enable))}}}@@ -850,7 +878,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Cprovider.isApiBased() -> {val audioFile = sttEngine.stopRecording()if (audioFile == null) {- appendUi(MessageKind.ERROR, "Failed to record audio.")+ appendUi(MessageKind.ERROR, str(R.string.chat_vm_failed_to_record_audio))return@launch}val sttLanguage = settings.sttLanguage.ifBlank {@@ -860,7 +888,10 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), CaudioFile, settings.sttApiModel, sttLanguage).onFailure { e ->- appendUi(MessageKind.ERROR, "Transcription failed: ${HumanReadableError.format(e)}")+ appendUi(+ MessageKind.ERROR,+ str(R.string.chat_vm_transcription_failed, HumanReadableError.format(e, strings()))+ )}.getOrDefault("")}@@ -933,9 +964,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), C}val uiMsg = when (next) {AgentMode.MONITOR ->- "Switched to Monitor mode — the agent can only observe; it cannot make any changes to your device."+ str(R.string.chat_vm_switched_to_monitor_mode_the)AgentMode.OPERATOR ->- "Switched to Operator mode — the agent can now make changes to your device."+ str(R.string.chat_vm_switched_to_operator_mode_the)}// Only inject into the LLM history when the viewed chat is the engine's;// otherwise the mode is applied at the next send (run(engineAgent)).@@ -1277,14 +1308,14 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Cval request = pendingBackup ?: returnpendingBackup = nullif (uri == null) return- _chatTransfer.value = ChatTransferState.Working("Saving backup…")+ _chatTransfer.value = ChatTransferState.Working(str(R.string.chat_vm_saving_backup))viewModelScope.launch {val outcome = runCatching {withContext(Dispatchers.IO) {val sessions = request.sessionId?.let { listOfNotNull(historyRepository.loadSession(it)) }?: historyRepository.listSessions()- check(sessions.isNotEmpty()) { "There are no saved chats to back up yet." }+ check(sessions.isNotEmpty()) { str(R.string.chat_vm_there_are_no_saved_chats) }val archive = ChatArchive(exportedAt = System.currentTimeMillis(),appVersion = com.gotcha.BuildConfig.VERSION_NAME,@@ -1292,7 +1323,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Csessions = if (request.includeImages) sessions else sessions.map(ChatArchive::withoutImages))val stream = getApplication<Application>().contentResolver.openOutputStream(uri, "wt")- ?: error("The chosen location can't be written to.")+ ?: error(str(R.string.chat_vm_the_chosen_location_can_t))stream.use { it.write(ChatArchive.encode(archive).toByteArray(Charsets.UTF_8)) }sessions.size}@@ -1300,12 +1331,12 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), C_chatTransfer.value = outcome.fold(onSuccess = { count ->ChatTransferState.Report(- "Backup saved",- if (count == 1) "Saved 1 chat." else "Saved $count chats."+ str(R.string.chat_vm_backup_saved),+ quantityStr(R.plurals.chat_vm_saved_chats, count))},onFailure = { e ->- ChatTransferState.Report("Backup failed", e.message ?: "The backup couldn't be saved.")+ ChatTransferState.Report(str(R.string.chat_vm_backup_failed), e.message ?: str(R.string.chat_vm_the_backup_couldn_t_be))})}@@ -1314,20 +1345,20 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), C/** Reads the file the user picked to import and shows what it holds; null means the picker was cancelled. */fun readImport(uri: Uri?) {if (uri == null) return- _chatTransfer.value = ChatTransferState.Working("Reading file…")+ _chatTransfer.value = ChatTransferState.Working(str(R.string.chat_vm_reading_file))viewModelScope.launch {val bytes = runCatching {withContext(Dispatchers.IO) { readAtMost(uri, ChatImporter.MAX_BYTES) }}.getOrNull()_chatTransfer.value = when {- bytes == null -> ChatTransferState.Report("Import failed", "The file couldn't be opened.")+ bytes == null -> ChatTransferState.Report(str(R.string.chat_vm_import_failed), str(R.string.chat_vm_the_file_couldn_t_be))bytes.size > ChatImporter.MAX_BYTES -> ChatTransferState.Report(- "Import failed",- "The file is larger than ${ChatImporter.MAX_BYTES / (1024 * 1024)} MB, the most Gotcha imports at once."+ str(R.string.chat_vm_import_failed),+ str(R.string.chat_vm_the_file_is_larger_than, ChatImporter.MAX_BYTES / (1024 * 1024)))else -> when (val read = chatImporter.preview(bytes)) {is ImportParseResult.Ready -> ChatTransferState.Previewing(read.preview)- is ImportParseResult.Failed -> ChatTransferState.Report("Import failed", read.message)+ is ImportParseResult.Failed -> ChatTransferState.Report(str(R.string.chat_vm_import_failed), read.message)}}}@@ -1336,7 +1367,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), C/** Imports the previewed file, resolving clashes with existing chats by [strategy]. */fun confirmImport(strategy: DuplicateStrategy) {val preview = (_chatTransfer.value as? ChatTransferState.Previewing)?.preview ?: return- _chatTransfer.value = ChatTransferState.Working("Importing…")+ _chatTransfer.value = ChatTransferState.Working(str(R.string.chat_vm_importing))viewModelScope.launch {val result = chatImporter.commit(preview,@@ -1350,15 +1381,17 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Cif (open != null && open in result.writtenIds) openSession(open)val counts = listOfNotNull(- "Imported ${result.imported}",- result.replaced.takeIf { it > 0 }?.let { "replaced $it" },- result.skipped.takeIf { it > 0 }?.let { "skipped $it" },- result.failed.size.takeIf { it > 0 }?.let { "$it failed" }+ str(R.string.chat_vm_imported_count, result.imported),+ result.replaced.takeIf { it > 0 }?.let { str(R.string.chat_vm_replaced_count, it) },+ result.skipped.takeIf { it > 0 }?.let { str(R.string.chat_vm_skipped_count, it) },+ result.failed.size.takeIf { it > 0 }?.let { str(R.string.chat_vm_failed_count, it) })_chatTransfer.value = ChatTransferState.Report(- title = if (result.imported + result.replaced > 0) "Import finished" else "Nothing imported",+ title = str(+ if (result.imported + result.replaced > 0) R.string.chat_vm_import_finished else R.string.chat_vm_nothing_imported+ ),summary = counts.joinToString(" · ") + ".",- details = result.failed.map { "${it.title}: ${it.reason}" } + preview.warnings+ details = result.failed.map { str(R.string.import_rejected_note, it.title, it.reason) } + preview.warnings)}}@@ -1394,7 +1427,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Cval client = ShareCardClient(getApplication(), settings)val content = client.generate(runs)if (!content.eligible) {- error("Nothing accomplished in this run to showcase yet.")+ error(str(R.string.chat_vm_nothing_accomplished_in_this_run))}val stats = PosterStatsBuilder.from(runs)withContext(Dispatchers.Main) {diff --git a/app/src/main/java/com/gotcha/agent/ForegroundControl.kt b/app/src/main/java/com/gotcha/agent/ForegroundControl.ktindex a8bf780..89809cc 100644--- a/app/src/main/java/com/gotcha/agent/ForegroundControl.kt+++ b/app/src/main/java/com/gotcha/agent/ForegroundControl.kt@@ -1,5 +1,8 @@package com.gotcha.agent+import androidx.annotation.StringRes+import com.gotcha.R+import com.gotcha.i18n.StringLookupimport com.gotcha.tools.ToolCategoriesimport com.gotcha.tools.ToolResultimport kotlinx.coroutines.sync.Mutex@@ -20,30 +23,29 @@ data class ForegroundControlRequest(/** navigate_app's task, when that is what asked: more specific than [userRequest]. */val task: String? = null) {- val title: String get() = "Let Gotcha control ${appLabel ?: "your apps"}?"+ fun title(text: StringLookup): String = text(R.string.fg_title, appLabel ?: text(R.string.fg_your_apps))- fun promptText(): String {- val target = appLabel ?: "another app"+ fun promptText(text: StringLookup): String {+ val target = appLabel ?: text(R.string.fg_another_app)val why = task?.trim()?.takeIf { it.isNotEmpty() }- ?.let { "Gotcha wants to: ${it.take(MAX_QUOTE)}" }+ ?.let { text(R.string.fg_wants_to, it.take(MAX_QUOTE)) }?: userRequest.trim().takeIf { it.isNotEmpty() }- ?.let { "To do what you asked (“${it.take(MAX_QUOTE)}”), Gotcha needs to use $target." }- ?: "To do what you asked, Gotcha needs to use $target."- return why + "\n\n" +- "Gotcha may bring $target to the front and tap, type, scroll and read its screen " +- "until this request is done. You'll see when it has finished.\n\n" +- "If you deny, Gotcha won't open or control other apps for this request."+ ?.let { text(R.string.fg_to_do_what_you_asked_quoted, it.take(MAX_QUOTE), target) }+ ?: text(R.string.fg_to_do_what_you_asked, target)+ return text(R.string.fg_prompt, why, target)}companion object {- const val ALLOW_LABEL = "Allow for this request"- const val DENY_LABEL = "Deny"- const val DONE_MESSAGE = "Gotcha is done. You can use your app again."+ @StringRes val ALLOW_LABEL = R.string.fg_allow++ @StringRes val DENY_LABEL = R.string.action_deny++ @StringRes val DONE_MESSAGE = R.string.fg_doneprivate const val MAX_QUOTE = 160- fun controllingMessage(appLabel: String?): String =- "Gotcha is controlling ${appLabel ?: "your screen"}…"+ fun controllingMessage(appLabel: String?, text: StringLookup): String =+ text(R.string.fg_controlling, appLabel ?: text(R.string.fg_your_screen))}}diff --git a/app/src/main/java/com/gotcha/audio/SttEngine.kt b/app/src/main/java/com/gotcha/audio/SttEngine.ktindex d49c0dd..752c6ad 100644--- a/app/src/main/java/com/gotcha/audio/SttEngine.kt+++ b/app/src/main/java/com/gotcha/audio/SttEngine.kt@@ -16,7 +16,6 @@ import android.speech.SpeechRecognizerimport android.util.Logimport com.gotcha.i18n.Languageimport com.gotcha.util.GotchaLog-import com.gotcha.util.HumanReadableErrorimport kotlinx.coroutines.CompletableDeferredimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContext@@ -304,8 +303,7 @@ class SttEngine(override fun onBufferReceived(buffer: ByteArray?) {}override fun onEndOfSpeech() { GotchaLog.d(TAG) { "onEndOfSpeech" } }override fun onError(error: Int) {- val humanMsg = HumanReadableError.fromSpeechRecognizerCode(error)- GotchaLog.d(TAG) { "onError: $error ($humanMsg)" }+ GotchaLog.d(TAG) { "onError: $error" }if (error == SpeechRecognizer.ERROR_CLIENT ||error == SpeechRecognizer.ERROR_RECOGNIZER_BUSY ||error == SpeechRecognizer.ERROR_SERVERdiff --git a/app/src/main/java/com/gotcha/notifications/ChatCompletionNotifier.kt b/app/src/main/java/com/gotcha/notifications/ChatCompletionNotifier.ktindex 861aaae..d2fdb60 100644--- a/app/src/main/java/com/gotcha/notifications/ChatCompletionNotifier.kt+++ b/app/src/main/java/com/gotcha/notifications/ChatCompletionNotifier.kt@@ -14,6 +14,7 @@ import androidx.core.app.NotificationCompatimport androidx.core.app.NotificationManagerCompatimport androidx.core.content.ContextCompatimport com.gotcha.R+import com.gotcha.agent.ChatTitleimport com.gotcha.data.CompletionPreviewimport com.gotcha.i18n.StringLookupimport com.gotcha.i18n.stringLookup@@ -163,7 +164,7 @@ class ChatCompletionNotifier(private val context: Context) {internal fun notificationId(sessionId: String): Int = "chat:$sessionId".hashCode() and 0x7FFF_FFFFinternal fun notificationTitle(chatTitle: String, outcome: RunOutcome, text: StringLookup): String {- val chat = chatTitle.ifBlank { text(R.string.completion_untitled_chat) }+ val chat = chatTitle.ifBlank { text(R.string.completion_untitled_chat) }.let { ChatTitle.display(it, text) }return when (outcome) {RunOutcome.DONE -> text(R.string.completion_done_title, chat)RunOutcome.FAILED -> text(R.string.completion_failed_title, chat)diff --git a/app/src/main/java/com/gotcha/notifications/LocalNotifications.kt b/app/src/main/java/com/gotcha/notifications/LocalNotifications.ktindex 425f6e6..d492730 100644--- a/app/src/main/java/com/gotcha/notifications/LocalNotifications.kt+++ b/app/src/main/java/com/gotcha/notifications/LocalNotifications.kt@@ -2,6 +2,7 @@ package com.gotcha.notificationsimport androidx.annotation.StringResimport com.gotcha.R+import com.gotcha.agent.ChatTitleimport com.gotcha.data.RunSummaryimport com.gotcha.data.Settingsimport com.gotcha.i18n.StringLookup@@ -178,8 +179,8 @@ internal fun unfinishedChat(val asked = run.succeededval body = when {!mention -> text(R.string.local_unfinished_generic)- asked -> text(R.string.local_unfinished_asked, chat.title)- else -> text(R.string.local_unfinished_stopped, chat.title)+ asked -> text(R.string.local_unfinished_asked, ChatTitle.display(chat.title, text))+ else -> text(R.string.local_unfinished_stopped, ChatTitle.display(chat.title, text))}return LocalCandidate(category = NotificationCategory.UNFINISHED_CHAT,@@ -287,7 +288,7 @@ internal fun inactivityReminder(dedupKey = "inactive:$lastOpenedAt",title = text(if (recent != null) R.string.local_inactive_title_recent else R.string.local_inactive_title),body = if (recent != null) {- text(R.string.local_inactive_body_recent, recent.title)+ text(R.string.local_inactive_body_recent, ChatTitle.display(recent.title, text))} else {text(R.string.local_inactive_body)},diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.ktindex 27636cd..57582f8 100644--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt@@ -361,7 +361,9 @@ class AssistiveBallService : Service() {)screenCompanionPanel.updateResponse(replyText)} catch (e: Exception) {- screenCompanionPanel.updateResponse(getString(R.string.companion_error, HumanReadableError.format(e)))+ screenCompanionPanel.updateResponse(+ getString(R.string.companion_error, HumanReadableError.format(e, stringLookup()))+ )}}}@@ -412,7 +414,9 @@ class AssistiveBallService : Service() {)screenCompanionPanel.updateResponse(replyText)} catch (e: Exception) {- screenCompanionPanel.updateResponse(getString(R.string.companion_error, HumanReadableError.format(e)))+ screenCompanionPanel.updateResponse(+ getString(R.string.companion_error, HumanReadableError.format(e, stringLookup()))+ )}}}@@ -625,7 +629,9 @@ class AssistiveBallService : Service() {intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)startActivity(intent)} catch (e: Exception) {- overlay.showError(getString(R.string.ball_couldn_t_open_action, HumanReadableError.format(e)))+ overlay.showError(+ getString(R.string.ball_couldn_t_open_action, HumanReadableError.format(e, stringLookup()))+ )}}@@ -681,7 +687,9 @@ class AssistiveBallService : Service() {)screenCompanionPanel.updateResponse(replyText)} catch (e: Exception) {- screenCompanionPanel.updateResponse(getString(R.string.companion_error, HumanReadableError.format(e)))+ screenCompanionPanel.updateResponse(+ getString(R.string.companion_error, HumanReadableError.format(e, stringLookup()))+ )}}}@@ -708,7 +716,7 @@ class AssistiveBallService : Service() {showToast(getString(R.string.ball_copied_to_clipboard))}} catch (e: Exception) {- showToast(getString(R.string.ball_couldn_t_read_text, HumanReadableError.format(e)))+ showToast(getString(R.string.ball_couldn_t_read_text, HumanReadableError.format(e, stringLookup())))} finally {if (!bitmap.isRecycled) bitmap.recycle()}@@ -795,7 +803,7 @@ class AssistiveBallService : Service() {)updateResponse(replyText)} catch (e: Exception) {- updateResponse(getString(R.string.ball_error, HumanReadableError.format(e)))+ updateResponse(getString(R.string.ball_error, HumanReadableError.format(e, stringLookup())))}}}@@ -875,7 +883,9 @@ class AssistiveBallService : Service() {result.onSuccess { text -> if (text.isNotBlank()) screenCompanionPanel.appendVoiceInput(text) }.onFailure { e ->- overlay.showError(getString(R.string.ball_transcription_failed, HumanReadableError.format(e)))+ overlay.showError(+ getString(R.string.ball_transcription_failed, HumanReadableError.format(e, stringLookup()))+ )}}}@@ -1094,7 +1104,9 @@ class AssistiveBallService : Service() {overlay.showChromeAfterCapture()chatWindow.setVisibleForCapture(true)screenCompanionPanel.setVisibleForCapture(true)- overlay.showError(getString(R.string.ball_screenshot_error, HumanReadableError.format(e)))+ overlay.showError(+ getString(R.string.ball_screenshot_error, HumanReadableError.format(e, stringLookup()))+ )}}}diff --git a/app/src/main/java/com/gotcha/service/CallSessionController.kt b/app/src/main/java/com/gotcha/service/CallSessionController.ktindex 2ac4f9e..a32bed0 100644--- a/app/src/main/java/com/gotcha/service/CallSessionController.kt+++ b/app/src/main/java/com/gotcha/service/CallSessionController.kt@@ -20,6 +20,7 @@ import com.gotcha.data.ChatHistoryRepositoryimport com.gotcha.data.SettingsRepositoryimport com.gotcha.i18n.Languageimport com.gotcha.i18n.SpokenPhrases+import com.gotcha.i18n.stringLookupimport com.gotcha.llm.ChatMessageimport com.gotcha.llm.LLMClientimport com.gotcha.llm.visionUserMessage@@ -322,7 +323,7 @@ class CallSessionController(// never spoke.val error = outcome.exceptionOrNull()if (error != null && !SttEngine.isBenignSttError(error)) {- reportError(friendlyAgentError(error as? Exception ?: Exception(error.message)))+ reportError(friendlyAgentError(error as? Exception ?: Exception(error.message), appContext.stringLookup()))endCall()break}@@ -484,7 +485,7 @@ class CallSessionController(// surface a dialog for actual STT failures (e.g. a bad API key/model).val error = result.exceptionOrNull()if (error != null && error.message != "No speech detected") {- reportError(friendlyAgentError(error as? Exception ?: Exception(error.message)))+ reportError(friendlyAgentError(error as? Exception ?: Exception(error.message), appContext.stringLookup()))}_state.value = CallState.READYreturn@launch@@ -537,7 +538,7 @@ class CallSessionController(} catch (e: CancellationException) {throw e} catch (e: Exception) {- val msg = friendlyAgentError(e)+ val msg = friendlyAgentError(e, appContext.stringLookup())reportError(msg)pendingReply = msg}@@ -755,11 +756,11 @@ class CallSessionController(*/override suspend fun awaitForegroundControl(request: ForegroundControlRequest): Boolean =askOverScreen(- transcript = "${request.title} ${request.promptText()}",- summary = request.promptText(),- title = request.title,- allowLabel = ForegroundControlRequest.ALLOW_LABEL,- denyLabel = ForegroundControlRequest.DENY_LABEL+ transcript = "${request.title(appContext.stringLookup())} ${request.promptText(appContext.stringLookup())}",+ summary = request.promptText(appContext.stringLookup()),+ title = request.title(appContext.stringLookup()),+ allowLabel = appContext.getString(ForegroundControlRequest.ALLOW_LABEL),+ denyLabel = appContext.getString(ForegroundControlRequest.DENY_LABEL))/** Says a decision is needed, then waits on the overlay's Allow/Deny; denies on timeout. */@@ -795,10 +796,12 @@ class CallSessionController(override fun onForegroundControlChanged(active: Boolean, appLabel: String?) {if (active) {- foregroundControlIndicator.showControlling(ForegroundControlRequest.controllingMessage(appLabel))+ foregroundControlIndicator.showControlling(+ ForegroundControlRequest.controllingMessage(appLabel, appContext.stringLookup())+ )} else {- addTranscript(MessageKind.ASSISTANT, ForegroundControlRequest.DONE_MESSAGE)- foregroundControlIndicator.showDone(ForegroundControlRequest.DONE_MESSAGE)+ addTranscript(MessageKind.ASSISTANT, appContext.getString(ForegroundControlRequest.DONE_MESSAGE))+ foregroundControlIndicator.showDone(appContext.getString(ForegroundControlRequest.DONE_MESSAGE))}}diff --git a/app/src/main/java/com/gotcha/service/ChatRunService.kt b/app/src/main/java/com/gotcha/service/ChatRunService.ktindex 494c3c0..f7e2789 100644--- a/app/src/main/java/com/gotcha/service/ChatRunService.kt+++ b/app/src/main/java/com/gotcha/service/ChatRunService.kt@@ -17,6 +17,7 @@ import androidx.core.app.NotificationCompatimport androidx.core.app.NotificationManagerCompatimport androidx.core.content.ContextCompatimport com.gotcha.R+import com.gotcha.agent.ChatTitleimport com.gotcha.i18n.StringLookupimport com.gotcha.i18n.stringLookupimport com.gotcha.notifications.ChatCompletionNotifier@@ -248,7 +249,8 @@ class ChatRunService : Service() {}internal fun title(chat: RunningChat?, text: StringLookup): String {- val name = chat?.chatTitle?.takeIf { it.isNotBlank() } ?: return text(R.string.run_public_title)+ val name = chat?.chatTitle?.takeIf { it.isNotBlank() }?.let { ChatTitle.display(it, text) }+ ?: return text(R.string.run_public_title)// A name already cut short with "…" doesn't need a second one.return text(if (name.endsWith("…")) R.string.run_title_cut else R.string.run_title, name)}diff --git a/app/src/main/java/com/gotcha/ui/AppDrawer.kt b/app/src/main/java/com/gotcha/ui/AppDrawer.ktindex 4280bbf..4f90aff 100644--- a/app/src/main/java/com/gotcha/ui/AppDrawer.kt+++ b/app/src/main/java/com/gotcha/ui/AppDrawer.kt@@ -34,11 +34,14 @@ import androidx.compose.runtime.rememberimport androidx.compose.runtime.setValueimport androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResourceimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport com.gotcha.R+import com.gotcha.agent.ChatTitleimport com.gotcha.data.ChatSession+import com.gotcha.i18n.stringLookupimport com.gotcha.ui.theme.GotchaMonoimport com.gotcha.ui.theme.LocalSkinimport com.gotcha.ui.theme.SkinAlertDialog@@ -126,7 +129,7 @@ fun AppDrawerContent(label = {Column {Text(- session.title,+ ChatTitle.display(session.title, LocalContext.current.stringLookup()),maxLines = 1,overflow = TextOverflow.Ellipsis)@@ -212,7 +215,8 @@ fun AppDrawerContent(}sessionToDelete?.let { id ->- val title = sessions.find { it.id == id }?.title ?: stringResource(R.string.drawer_this_chat)+ val title = sessions.find { it.id == id }?.title?.let { ChatTitle.display(it, LocalContext.current.stringLookup()) }+ ?: stringResource(R.string.drawer_this_chat)SkinAlertDialog(onDismissRequest = { sessionToDelete = null },title = { Text(stringResource(R.string.drawer_delete_chat)) },diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.ktindex f09d624..3ebe55b 100644--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt@@ -89,9 +89,11 @@ import androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport com.gotcha.Rimport com.gotcha.agent.ATTACHMENT_PLACEHOLDERS+import com.gotcha.agent.ChatTitleimport com.gotcha.agent.ChatUiStateimport com.gotcha.agent.ComposerAttachmentimport com.gotcha.agent.ForegroundControlRequest+import com.gotcha.i18n.stringLookupimport com.gotcha.tools.AgentModeimport com.gotcha.ui.theme.GotchaMonoimport com.gotcha.ui.theme.LocalSkin@@ -198,7 +200,11 @@ fun ChatScreen(title = {Column {Text(- if (isHome) "Gotcha" else (sessionTitle ?: "Gotcha"),+ if (isHome) {+ "Gotcha"+ } else {+ sessionTitle?.let { ChatTitle.display(it, LocalContext.current.stringLookup()) } ?: "Gotcha"+ },maxLines = 1,overflow = TextOverflow.Ellipsis)@@ -561,7 +567,8 @@ fun ChatScreen(Text(stringResource(R.string.chat_agent_working_elsewhere,- state.runningSessionTitle ?: stringResource(R.string.chat_another_chat)+ state.runningSessionTitle?.let { ChatTitle.display(it, LocalContext.current.stringLookup()) }+ ?: stringResource(R.string.chat_another_chat)),style = MaterialTheme.typography.bodySmall,color = MaterialTheme.colorScheme.onSecondaryContainer,@@ -843,16 +850,21 @@ fun ChatScreen(state.pendingForegroundControl?.let { pending ->SkinAlertDialog(onDismissRequest = { onAnswerForegroundControl(false) },- title = { Text(pending.title) },- text = { Text(pending.promptText(), style = MaterialTheme.typography.bodyMedium) },+ title = { Text(pending.title(LocalContext.current.stringLookup())) },+ text = {+ Text(+ pending.promptText(LocalContext.current.stringLookup()),+ style = MaterialTheme.typography.bodyMedium+ )+ },confirmButton = {Button(onClick = { onAnswerForegroundControl(true) }) {- Text(ForegroundControlRequest.ALLOW_LABEL)+ Text(stringResource(ForegroundControlRequest.ALLOW_LABEL))}},dismissButton = {TextButton(onClick = { onAnswerForegroundControl(false) }) {- Text(ForegroundControlRequest.DENY_LABEL)+ Text(stringResource(ForegroundControlRequest.DENY_LABEL))}})diff --git a/app/src/main/java/com/gotcha/util/HumanReadableError.kt b/app/src/main/java/com/gotcha/util/HumanReadableError.ktindex c7c6448..b9d7627 100644--- a/app/src/main/java/com/gotcha/util/HumanReadableError.kt+++ b/app/src/main/java/com/gotcha/util/HumanReadableError.kt@@ -2,6 +2,8 @@ package com.gotcha.utilimport android.speech.SpeechRecognizerimport android.speech.tts.TextToSpeech+import com.gotcha.R+import com.gotcha.i18n.StringLookupimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitive@@ -22,82 +24,82 @@ object HumanReadableError {* names images (e.g. a provider allowing fewer images per request than the* user attached) gets its own explanation, since the fix is on the user's side.*/- fun fromHttpCode(code: Int, rawMessage: String? = null): String = when {+ fun fromHttpCode(code: Int, rawMessage: String? = null, strings: StringLookup): String = when {code in IMAGE_REJECTION_CODES && rawMessage?.contains("image", ignoreCase = true) == true ->- "The model rejected the attached images (HTTP $code): $rawMessage. " +- "It may accept fewer or smaller images per request — images from earlier in " +- "this chat count too. Remove some attachments or start a new chat, then try again."- else -> fromHttpCodeOnly(code, rawMessage)+ strings(R.string.error_the_model_rejected_the_attached, code, rawMessage)+ else -> fromHttpCodeOnly(code, rawMessage, strings)}private val IMAGE_REJECTION_CODES = setOf(400, 413, 422)- private fun fromHttpCodeOnly(code: Int, rawMessage: String?): String = when (code) {- 400 -> "Bad request (HTTP 400). The request format or parameters sent to the API were invalid."- 401 -> "Authentication failed (HTTP 401). Please check your API key in Settings."+ private fun fromHttpCodeOnly(code: Int, rawMessage: String?, strings: StringLookup): String = when (code) {+ 400 -> strings(R.string.error_bad_request_http_400_the)+ 401 -> strings(R.string.error_authentication_failed_http_401_please)403 -> {if (!rawMessage.isNullOrBlank()) {rawMessage} else {- "Access restricted (HTTP 403). This model is not available on your current tier. " +- "Please upgrade your account in Settings to access it."+ strings(R.string.error_access_restricted_http_403_this)}}- 404 -> "Resource not found (HTTP 404). Check if the selected model ID or endpoint URL is correct in Settings."- 408 -> "Request timeout (HTTP 408). The server timed out waiting for the request."- 413 -> "Request too large (HTTP 413). Try sending fewer or smaller attachments."- 429 -> "Rate limit or quota exceeded (HTTP 429). Please wait a moment or check your API usage limits."- 500 -> "Server error (HTTP 500). The remote AI service encountered an internal error. Please try again."- 502 -> "Bad gateway (HTTP 502). The proxy or upstream service received an invalid response."- 503 -> "Service unavailable (HTTP 503). The remote AI service is temporarily down or overloaded."- 504 -> "Gateway timeout (HTTP 504). The upstream AI service took too long to respond."+ 404 -> strings(R.string.error_resource_not_found_http_404)+ 408 -> strings(R.string.error_request_timeout_http_408_the)+ 413 -> strings(R.string.error_request_too_large_http_413)+ 429 -> strings(R.string.error_rate_limit_or_quota_exceeded)+ 500 -> strings(R.string.error_server_error_http_500_the)+ 502 -> strings(R.string.error_bad_gateway_http_502_the)+ 503 -> strings(R.string.error_service_unavailable_http_503_the)+ 504 -> strings(R.string.error_gateway_timeout_http_504_the)else -> {- val suffix = if (!rawMessage.isNullOrBlank()) " ($rawMessage)" else ""- "The API returned an error (HTTP $code)$suffix."+ if (rawMessage.isNullOrBlank()) {+ strings(R.string.error_http_generic, code)+ } else {+ strings(R.string.error_http_generic_detail, code, rawMessage)+ }}}/** Maps Android [SpeechRecognizer] integer error codes (1–13) to clear explanations. */- fun fromSpeechRecognizerCode(code: Int): String = when (code) {+ fun fromSpeechRecognizerCode(code: Int, strings: StringLookup): String = when (code) {SpeechRecognizer.ERROR_NETWORK_TIMEOUT ->- "Network connection timed out while recognizing speech."+ strings(R.string.error_network_connection_timed_out_while)SpeechRecognizer.ERROR_NETWORK ->- "Network connection error during speech recognition. Check your internet connection."+ strings(R.string.error_network_connection_error_during_speech)SpeechRecognizer.ERROR_AUDIO ->- "Microphone hardware error. Ensure your microphone is not in use by another app."+ strings(R.string.error_microphone_hardware_error_ensure_your)SpeechRecognizer.ERROR_SERVER ->- "Device speech recognition server error. Please try again."+ strings(R.string.error_device_speech_recognition_server_error)SpeechRecognizer.ERROR_CLIENT ->- "Android speech recognition client error."+ strings(R.string.error_android_speech_recognition_client_error)SpeechRecognizer.ERROR_SPEECH_TIMEOUT ->- "No speech detected. Please speak closer to the microphone."+ strings(R.string.error_no_speech_detected_please_speak)SpeechRecognizer.ERROR_NO_MATCH ->- "Could not understand speech. Please try speaking clearer or closer to the mic."+ strings(R.string.error_could_not_understand_speech_please)SpeechRecognizer.ERROR_RECOGNIZER_BUSY ->- "Speech recognizer is busy. Please wait a moment and try again."+ strings(R.string.error_speech_recognizer_is_busy_please)SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS ->- "Microphone permission is required for voice input."+ strings(R.string.error_microphone_permission_is_required_for)SpeechRecognizer.ERROR_TOO_MANY_REQUESTS ->- "Too many speech recognition requests sent. Please wait a moment."+ strings(R.string.error_too_many_speech_recognition_requests)SpeechRecognizer.ERROR_SERVER_DISCONNECTED ->- "Speech recognition service disconnected. Reconnecting..."+ strings(R.string.error_speech_recognition_service_disconnected_reconnecting)SpeechRecognizer.ERROR_LANGUAGE_NOT_SUPPORTED ->- "Selected language is not supported by device speech recognition."+ strings(R.string.error_selected_language_is_not_supported)SpeechRecognizer.ERROR_LANGUAGE_UNAVAILABLE ->- "Language pack for selected language is not installed on your device."- else -> "Speech recognition error (code $code)."+ strings(R.string.error_language_pack_for_selected_language)+ else -> strings(R.string.error_speech_recognition_error_code, code)}/** Maps Android [TextToSpeech] status codes to human-readable explanations. */- fun fromTtsCode(code: Int): String = when (code) {- TextToSpeech.ERROR_SYNTHESIS -> "Speech synthesis error while generating audio."- TextToSpeech.ERROR_SERVICE -> "Android TextToSpeech engine service error."- TextToSpeech.ERROR_OUTPUT -> "Audio output stream error during speech playback."- TextToSpeech.ERROR_NETWORK -> "Network failure during online speech synthesis."- TextToSpeech.ERROR_NETWORK_TIMEOUT -> "Network timeout during speech synthesis."- TextToSpeech.ERROR_INVALID_REQUEST -> "Invalid text input or parameters passed to TTS engine."- TextToSpeech.ERROR_NOT_INSTALLED_YET -> "TTS voice data is still downloading on your device."- else -> "Text-to-speech error (code $code)."+ fun fromTtsCode(code: Int, strings: StringLookup): String = when (code) {+ TextToSpeech.ERROR_SYNTHESIS -> strings(R.string.error_speech_synthesis_error_while_generating)+ TextToSpeech.ERROR_SERVICE -> strings(R.string.error_android_texttospeech_engine_service_error)+ TextToSpeech.ERROR_OUTPUT -> strings(R.string.error_audio_output_stream_error_during)+ TextToSpeech.ERROR_NETWORK -> strings(R.string.error_network_failure_during_online_speech)+ TextToSpeech.ERROR_NETWORK_TIMEOUT -> strings(R.string.error_network_timeout_during_speech_synthesis)+ TextToSpeech.ERROR_INVALID_REQUEST -> strings(R.string.error_invalid_text_input_or_parameters)+ TextToSpeech.ERROR_NOT_INSTALLED_YET -> strings(R.string.error_tts_voice_data_is_still)+ else -> strings(R.string.error_text_to_speech_error_code, code)}/** Safely parses error JSON from an HttpException response body once and extracts detail, message, or error. */@@ -124,32 +126,32 @@ object HumanReadableError {}/** Translates any exception into a user-friendly error message. */- fun format(e: Throwable): String = when {+ fun format(e: Throwable, strings: StringLookup): String = when {e is HttpException -> {val bodyDetail = extractHttpErrorDetail(e)- fromHttpCode(e.code(), bodyDetail ?: e.message())+ fromHttpCode(e.code(), bodyDetail ?: e.message(), strings)}e is UnknownHostException ->- "Cannot connect to server. Check your internet connection or server URL in Settings."+ strings(R.string.error_cannot_connect_to_server_check)e is ConnectException ->- "Connection refused by server. Ensure the server is running and accessible."+ strings(R.string.error_connection_refused_by_server_ensure)e is SocketTimeoutException ->- "Connection timed out waiting for server response. Check network speed or try a smaller request."+ strings(R.string.error_connection_timed_out_waiting_for)e is IOException && e.message?.contains("HTTP ") == true -> {val codeStr = e.message?.substringAfter("HTTP ")?.substringBefore(":")?.trim()val code = codeStr?.toIntOrNull()if (code != null) {- fromHttpCode(code, e.message)+ fromHttpCode(code, e.message, strings)} else {- "Network problem: ${e.message}"+ strings(R.string.error_network_problem, e.message.orEmpty())}}e is IOException ->- "Network problem: ${e.message ?: "could not reach the server"}. Check your connection."+ strings(R.string.error_network_problem_check, e.message ?: strings(R.string.error_could_not_reach_server))e is SecurityException ->- "Permission denied: ${e.message ?: "required permission was not granted"}."+ strings(R.string.error_permission_denied, e.message ?: strings(R.string.error_permission_not_granted))!e.message.isNullOrBlank() ->- "Error: ${e.message}"- else -> "An unexpected error occurred (${e.javaClass.simpleName})."+ strings(R.string.error_generic, e.message.orEmpty())+ else -> strings(R.string.error_an_unexpected_error_occurred, e.javaClass.simpleName)}}diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex 67643b7..95ebf67 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -1367,4 +1367,135 @@<!-- GotchaNotificationListenerService --><string name="notification_listener_otp_copied_to_clipboard">🔑 OTP %1$s copied to clipboard</string>++ <!-- Chat: messages from the view model -->+ <string name="chat_vm_no_api_key_configured_open">No API key configured. Open settings to add one.</string>+ <string name="chat_vm_microphone_permission_not_granted_enable">Microphone permission not granted. Enable it in Settings → Permissions.</string>+ <string name="chat_vm_failed_to_start_speech_recognition">Failed to start speech recognition.</string>+ <string name="chat_vm_samosa_stt_is_not_configured">Samosa STT is not configured. Sign in from Settings → Speech.</string>+ <string name="chat_vm_no_stt_api_url_configured">No STT API URL configured in settings.</string>+ <string name="chat_vm_no_stt_model_selected_refresh">No STT model selected. Refresh audio models in settings.</string>+ <string name="chat_vm_failed_to_start_recording">Failed to start recording.</string>+ <string name="chat_vm_no_stt_provider_configured_enable">No STT provider configured. Enable one in settings.</string>+ <string name="chat_vm_failed_to_record_audio">Failed to record audio.</string>+ <string name="chat_vm_transcription_failed">Transcription failed: %1$s</string>+ <string name="chat_vm_switched_to_monitor_mode_the">Switched to Monitor mode — the agent can only observe; it cannot make any changes to your device.</string>+ <string name="chat_vm_switched_to_operator_mode_the">Switched to Operator mode — the agent can now make changes to your device.</string>+ <string name="chat_vm_could_not_read_that_file">Could not read that file: %1$s</string>+ <string name="chat_vm_backup_saved">Backup saved</string>+ <string name="chat_vm_backup_failed">Backup failed</string>+ <string name="chat_vm_the_backup_couldn_t_be">The backup couldn\'t be saved.</string>+ <string name="chat_vm_reading_file">Reading file…</string>+ <string name="chat_vm_the_file_couldn_t_be">The file couldn\'t be opened.</string>+ <string name="chat_vm_the_file_is_larger_than">The file is larger than %1$s MB, the most Gotcha imports at once.</string>+ <string name="chat_vm_importing">Importing…</string>+ <string name="chat_vm_import_finished">Import finished</string>+ <string name="chat_vm_nothing_imported">Nothing imported</string>+ <string name="chat_vm_saving_backup">Saving backup…</string>+ <string name="chat_vm_there_are_no_saved_chats">There are no saved chats to back up yet.</string>+ <string name="chat_vm_the_chosen_location_can_t">The chosen location can\'t be written to.</string>+ <string name="chat_vm_nothing_accomplished_in_this_run">Nothing accomplished in this run to showcase yet.</string>+ <string name="chat_vm_import_failed">Import failed</string>+ <string name="chat_vm_could_not_read_that_file_2">Could not read that file.</string>+ <string name="chat_vm_imported_count">Imported %1$d</string>+ <string name="chat_vm_replaced_count">replaced %1$d</string>+ <string name="chat_vm_skipped_count">skipped %1$d</string>+ <string name="chat_vm_failed_count">%1$d failed</string>+ <plurals name="chat_vm_saved_chats">+ <item quantity="one">Saved %1$d chat.</item>+ <item quantity="other">Saved %1$d chats.</item>+ </plurals>+ <plurals name="chat_vm_too_many_files">+ <item quantity="one">You can attach up to %2$d files per message — skipped %1$d file.</item>+ <item quantity="other">You can attach up to %2$d files per message — skipped %1$d files.</item>+ </plurals>+ <plurals name="chat_vm_documents_too_long">+ <item quantity="one">The attached documents are too long to send together — skipped %1$d document. Send them in separate messages.</item>+ <item quantity="other">The attached documents are too long to send together — skipped %1$d documents. Send them in separate messages.</item>+ </plurals>++ <!-- Chat runner and background hint -->+ <string name="runner_profile_updated">Assistant updated your profile: %1$s.</string>+ <string name="runner_interrupted_by_user">Agent was interrupted by the user.</string>+ <string name="runner_interrupted_title">Interrupted: %1$s</string>+ <string name="runner_interrupted_title_anonymous">Task interrupted</string>+ <string name="runner_interrupted_notice">This task was interrupted: Android closed Gotcha while it was working, usually to free memory. Send a message to pick up where it left off.</string>+ <string name="runner_interrupted_inbox_body">Android closed Gotcha while it was working on this task. Tap to open the chat and pick up where it left off.</string>+ <string name="hint_background">Gotcha is working in the background. You can use another app while it works</string>+ <string name="hint_background_with_signal">%1$s — %2$s.</string>+ <string name="hint_background_alone">%1$s.</string>+ <string name="hint_signal_notify">Gotcha will notify you when the task is finished</string>+ <string name="hint_signal_buzz_chime">your phone will buzz and chime when it\'s done</string>+ <string name="hint_signal_buzz">your phone will buzz when it\'s done</string>+ <string name="hint_signal_chime">your phone will chime when it\'s done</string>++ <!-- Chat titles until one is generated -->+ <string name="chat_title_new">New Chat</string>+ <string name="chat_title_image">Image chat</string>++ <!-- Controlling other apps (foreground control) -->+ <string name="fg_title">Let Gotcha control %1$s?</string>+ <string name="fg_your_apps">your apps</string>+ <string name="fg_another_app">another app</string>+ <string name="fg_wants_to">Gotcha wants to: %1$s</string>+ <string name="fg_to_do_what_you_asked_quoted">To do what you asked (“%1$s”), Gotcha needs to use %2$s.</string>+ <string name="fg_to_do_what_you_asked">To do what you asked, Gotcha needs to use %1$s.</string>+ <string name="fg_prompt">%1$s\n\nGotcha may bring %2$s to the front and tap, type, scroll and read its screen until this request is done. You\'ll see when it has finished.\n\nIf you deny, Gotcha won\'t open or control other apps for this request.</string>+ <string name="fg_allow">Allow for this request</string>+ <string name="fg_done">Gotcha is done. You can use your app again.</string>+ <string name="fg_controlling">Gotcha is controlling %1$s…</string>+ <string name="fg_your_screen">your screen</string>++ <!-- Errors shown to the user -->+ <string name="error_network_problem_check">Network problem: %1$s. Check your connection.</string>+ <string name="error_could_not_reach_server">could not reach the server</string>+ <string name="error_permission_denied">Permission denied: %1$s.</string>+ <string name="error_permission_not_granted">required permission was not granted</string>+ <string name="error_http_generic">The API returned an error (HTTP %1$d).</string>+ <string name="error_http_generic_detail">The API returned an error (HTTP %1$d) (%2$s).</string>+ <string name="error_the_model_rejected_the_attached">The model rejected the attached images (HTTP %1$s): %2$s. It may accept fewer or smaller images per request — images from earlier in this chat count too. Remove some attachments or start a new chat, then try again.</string>+ <string name="error_bad_request_http_400_the">Bad request (HTTP 400). The request format or parameters sent to the API were invalid.</string>+ <string name="error_authentication_failed_http_401_please">Authentication failed (HTTP 401). Please check your API key in Settings.</string>+ <string name="error_access_restricted_http_403_this">Access restricted (HTTP 403). This model is not available on your current tier. Please upgrade your account in Settings to access it.</string>+ <string name="error_resource_not_found_http_404">Resource not found (HTTP 404). Check if the selected model ID or endpoint URL is correct in Settings.</string>+ <string name="error_request_timeout_http_408_the">Request timeout (HTTP 408). The server timed out waiting for the request.</string>+ <string name="error_request_too_large_http_413">Request too large (HTTP 413). Try sending fewer or smaller attachments.</string>+ <string name="error_rate_limit_or_quota_exceeded">Rate limit or quota exceeded (HTTP 429). Please wait a moment or check your API usage limits.</string>+ <string name="error_server_error_http_500_the">Server error (HTTP 500). The remote AI service encountered an internal error. Please try again.</string>+ <string name="error_bad_gateway_http_502_the">Bad gateway (HTTP 502). The proxy or upstream service received an invalid response.</string>+ <string name="error_service_unavailable_http_503_the">Service unavailable (HTTP 503). The remote AI service is temporarily down or overloaded.</string>+ <string name="error_gateway_timeout_http_504_the">Gateway timeout (HTTP 504). The upstream AI service took too long to respond.</string>+ <string name="error_network_connection_timed_out_while">Network connection timed out while recognizing speech.</string>+ <string name="error_network_connection_error_during_speech">Network connection error during speech recognition. Check your internet connection.</string>+ <string name="error_microphone_hardware_error_ensure_your">Microphone hardware error. Ensure your microphone is not in use by another app.</string>+ <string name="error_device_speech_recognition_server_error">Device speech recognition server error. Please try again.</string>+ <string name="error_android_speech_recognition_client_error">Android speech recognition client error.</string>+ <string name="error_no_speech_detected_please_speak">No speech detected. Please speak closer to the microphone.</string>+ <string name="error_could_not_understand_speech_please">Could not understand speech. Please try speaking clearer or closer to the mic.</string>+ <string name="error_speech_recognizer_is_busy_please">Speech recognizer is busy. Please wait a moment and try again.</string>+ <string name="error_microphone_permission_is_required_for">Microphone permission is required for voice input.</string>+ <string name="error_too_many_speech_recognition_requests">Too many speech recognition requests sent. Please wait a moment.</string>+ <string name="error_speech_recognition_service_disconnected_reconnecting">Speech recognition service disconnected. Reconnecting...</string>+ <string name="error_selected_language_is_not_supported">Selected language is not supported by device speech recognition.</string>+ <string name="error_language_pack_for_selected_language">Language pack for selected language is not installed on your device.</string>+ <string name="error_speech_recognition_error_code">Speech recognition error (code %1$s).</string>+ <string name="error_speech_synthesis_error_while_generating">Speech synthesis error while generating audio.</string>+ <string name="error_android_texttospeech_engine_service_error">Android TextToSpeech engine service error.</string>+ <string name="error_audio_output_stream_error_during">Audio output stream error during speech playback.</string>+ <string name="error_network_failure_during_online_speech">Network failure during online speech synthesis.</string>+ <string name="error_network_timeout_during_speech_synthesis">Network timeout during speech synthesis.</string>+ <string name="error_invalid_text_input_or_parameters">Invalid text input or parameters passed to TTS engine.</string>+ <string name="error_tts_voice_data_is_still">TTS voice data is still downloading on your device.</string>+ <string name="error_text_to_speech_error_code">Text-to-speech error (code %1$s).</string>+ <string name="error_cannot_connect_to_server_check">Cannot connect to server. Check your internet connection or server URL in Settings.</string>+ <string name="error_connection_refused_by_server_ensure">Connection refused by server. Ensure the server is running and accessible.</string>+ <string name="error_connection_timed_out_waiting_for">Connection timed out waiting for server response. Check network speed or try a smaller request.</string>+ <string name="error_network_problem">Network problem: %1$s</string>+ <string name="error_an_unexpected_error_occurred">An unexpected error occurred (%1$s).</string>++ <!-- Errors shown to the user: generic -->+ <string name="error_generic">Error: %1$s</string>++ <!-- Errors: model timeout -->+ <string name="error_model_timeout">The model didn\'t respond in time. Try again, or raise the API timeout in Settings → AI → AI Configuration.</string></resources>diff --git a/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt b/app/src/test/java/com/gotcha/agent/AgentLoopTest.ktindex bbab9a9..b5b8b23 100644--- a/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt+++ b/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt@@ -5,6 +5,7 @@ import androidx.test.core.app.ApplicationProviderimport com.gotcha.data.ChatHistoryRepositoryimport com.gotcha.data.LlmProviderimport com.gotcha.data.Settings+import com.gotcha.i18n.stringLookupimport com.gotcha.llm.ChatRequestimport com.gotcha.llm.LLMClientimport com.gotcha.llm.visionUserMessage@@ -482,7 +483,11 @@ class AgentLoopTest {val request = events.foregroundControlRequests.single()assertEquals("open_app", request.toolName)assertEquals("Chat App", request.appLabel)- assertTrue(request.promptText().contains("Say hi to Sam on Chat App"))+ assertTrue(+ request.promptText(+ ApplicationProvider.getApplicationContext<Context>().stringLookup()+ ).contains("Say hi to Sam on Chat App")+ )assertEquals(listOf(true to "Chat App", false to "Chat App"), events.foregroundControlChanges)}diff --git a/app/src/test/java/com/gotcha/agent/ChatViewModelBackgroundHintTest.kt b/app/src/test/java/com/gotcha/agent/ChatViewModelBackgroundHintTest.ktindex c61e1a1..8a439f3 100644--- a/app/src/test/java/com/gotcha/agent/ChatViewModelBackgroundHintTest.kt+++ b/app/src/test/java/com/gotcha/agent/ChatViewModelBackgroundHintTest.kt@@ -1,10 +1,12 @@package com.gotcha.agentimport android.app.Application+import android.content.Contextimport androidx.test.core.app.ApplicationProviderimport com.gotcha.data.LlmProviderimport com.gotcha.data.Settingsimport com.gotcha.data.SettingsRepository+import com.gotcha.i18n.stringLookupimport com.gotcha.llm.ChatMessageimport com.gotcha.testsupport.FakeAndroidKeyStoreimport kotlinx.coroutines.CoroutineScope@@ -77,21 +79,56 @@ class ChatViewModelBackgroundHintTest {return viewModel.runner.engine.history.toList()}- private val expectedHint = backgroundHintText(vibrate = true, chime = false)+ private val expectedHint =+ backgroundHintText(+ vibrate = true,+ chime = false,+ text = ApplicationProvider.getApplicationContext<Context>().stringLookup()+ )@Testfun `hint promises only the signals the user has enabled`() {val base = "Gotcha is working in the background. You can use another app while it works"- assertEquals("$base — your phone will buzz when it's done.", backgroundHintText(vibrate = true, chime = false))- assertEquals("$base — your phone will chime when it's done.", backgroundHintText(vibrate = false, chime = true))+ assertEquals(+ "$base — your phone will buzz when it's done.",+ backgroundHintText(+ vibrate = true,+ chime = false,+ text = ApplicationProvider.getApplicationContext<Context>().stringLookup()+ )+ )+ assertEquals(+ "$base — your phone will chime when it's done.",+ backgroundHintText(+ vibrate = false,+ chime = true,+ text = ApplicationProvider.getApplicationContext<Context>().stringLookup()+ )+ )assertEquals("$base — your phone will buzz and chime when it's done.",- backgroundHintText(vibrate = true, chime = true)+ backgroundHintText(+ vibrate = true,+ chime = true,+ text = ApplicationProvider.getApplicationContext<Context>().stringLookup()+ )+ )+ assertEquals(+ "$base.",+ backgroundHintText(+ vibrate = false,+ chime = false,+ text = ApplicationProvider.getApplicationContext<Context>().stringLookup()+ ))- assertEquals("$base.", backgroundHintText(vibrate = false, chime = false))assertEquals("$base — Gotcha will notify you when the task is finished.",- backgroundHintText(vibrate = true, chime = true, notify = true)+ backgroundHintText(+ vibrate = true,+ chime = true,+ notify = true,+ text = ApplicationProvider.getApplicationContext<Context>().stringLookup()+ ))}diff --git a/app/src/test/java/com/gotcha/agent/ChatViewModelCompletionNotificationTest.kt b/app/src/test/java/com/gotcha/agent/ChatViewModelCompletionNotificationTest.ktindex 91bbc87..b619eef 100644--- a/app/src/test/java/com/gotcha/agent/ChatViewModelCompletionNotificationTest.kt+++ b/app/src/test/java/com/gotcha/agent/ChatViewModelCompletionNotificationTest.kt@@ -3,11 +3,13 @@ package com.gotcha.agentimport android.Manifestimport android.app.Applicationimport android.app.NotificationManager+import android.content.Contextimport androidx.core.app.NotificationCompatimport androidx.test.core.app.ApplicationProviderimport com.gotcha.data.LlmProviderimport com.gotcha.data.Settingsimport com.gotcha.data.SettingsRepository+import com.gotcha.i18n.stringLookupimport com.gotcha.notifications.ChatCompletionNotifierimport com.gotcha.notifications.LocalNotificationStoreimport com.gotcha.service.ChatRunService@@ -221,7 +223,12 @@ class ChatViewModelCompletionNotificationTest {ShadowLooper.idleMainLooper()assertEquals(- backgroundHintText(vibrate = true, chime = false, notify = true),+ backgroundHintText(+ vibrate = true,+ chime = false,+ notify = true,+ text = ApplicationProvider.getApplicationContext<Context>().stringLookup()+ ),viewModel.uiState.value.backgroundHint)waitForRunToFinish()@@ -250,13 +257,25 @@ class ChatViewModelCompletionNotificationTest {start(granted = false)viewModel.sendMessage("Hello")ShadowLooper.idleMainLooper()- assertEquals(backgroundHintText(vibrate = true, chime = false), viewModel.uiState.value.backgroundHint)+ assertEquals(+ backgroundHintText(+ vibrate = true,+ chime = false,+ text = ApplicationProvider.getApplicationContext<Context>().stringLookup()+ ),+ viewModel.uiState.value.backgroundHint+ )shadowOf(application).grantPermissions(Manifest.permission.POST_NOTIFICATIONS)viewModel.onNotificationPermissionResult(true)assertEquals(- backgroundHintText(vibrate = true, chime = false, notify = true),+ backgroundHintText(+ vibrate = true,+ chime = false,+ notify = true,+ text = ApplicationProvider.getApplicationContext<Context>().stringLookup()+ ),viewModel.uiState.value.backgroundHint)assertFalse(viewModel.uiState.value.askNotificationPermission)diff --git a/app/src/test/java/com/gotcha/agent/ForegroundControlGateTest.kt b/app/src/test/java/com/gotcha/agent/ForegroundControlGateTest.ktindex ae81166..ff7e882 100644--- a/app/src/test/java/com/gotcha/agent/ForegroundControlGateTest.kt+++ b/app/src/test/java/com/gotcha/agent/ForegroundControlGateTest.kt@@ -1,5 +1,8 @@package com.gotcha.agent+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.gotcha.i18n.stringLookupimport kotlinx.coroutines.CompletableDeferredimport kotlinx.coroutines.asyncimport kotlinx.coroutines.test.runTest@@ -10,7 +13,10 @@ import org.junit.Assert.assertFalseimport org.junit.Assert.assertNullimport org.junit.Assert.assertTrueimport org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+@RunWith(RobolectricTestRunner::class)class ForegroundControlGateTest {private val noArgs = JsonObject(emptyMap())@@ -102,7 +108,7 @@ class ForegroundControlGateTest {toolName = "open_app",appLabel = "WhatsApp",userRequest = "text Sam I'm late"- ).promptText()+ ).promptText(ApplicationProvider.getApplicationContext<Context>().stringLookup())assertTrue(text.contains("WhatsApp"))assertTrue(text.contains("text Sam I'm late"))diff --git a/app/src/test/java/com/gotcha/agent/FriendlyModelErrorTest.kt b/app/src/test/java/com/gotcha/agent/FriendlyModelErrorTest.ktindex 0f5e5a1..c466156 100644--- a/app/src/test/java/com/gotcha/agent/FriendlyModelErrorTest.kt+++ b/app/src/test/java/com/gotcha/agent/FriendlyModelErrorTest.kt@@ -1,22 +1,34 @@package com.gotcha.agent+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.gotcha.R+import com.gotcha.i18n.stringLookupimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertTrueimport org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunnerimport java.net.SocketTimeoutExceptionimport java.net.UnknownHostException+@RunWith(RobolectricTestRunner::class)class FriendlyModelErrorTest {+ private val strings = ApplicationProvider.getApplicationContext<Context>().stringLookup()+/** A model server that never answers ends the run with this, not a network hint (#104). */@Testfun `a timeout says the model did not respond in time`() {- assertEquals(MODEL_TIMEOUT_MESSAGE, friendlyModelError(SocketTimeoutException("timeout")))+ assertEquals(+ strings(R.string.error_model_timeout),+ friendlyModelError(SocketTimeoutException("timeout"), strings = strings)+ )}@Testfun `other failures keep the generic wording`() {- val message = friendlyModelError(UnknownHostException("api.openai.com"))+ val message = friendlyModelError(UnknownHostException("api.openai.com"), strings = strings)assertTrue(message, message.contains("Cannot connect to server"))}}diff --git a/app/src/test/java/com/gotcha/util/HumanReadableErrorTest.kt b/app/src/test/java/com/gotcha/util/HumanReadableErrorTest.ktindex af666a5..5a0977d 100644--- a/app/src/test/java/com/gotcha/util/HumanReadableErrorTest.kt+++ b/app/src/test/java/com/gotcha/util/HumanReadableErrorTest.kt@@ -1,10 +1,15 @@package com.gotcha.util+import android.content.Contextimport android.speech.SpeechRecognizerimport android.speech.tts.TextToSpeech+import androidx.test.core.app.ApplicationProvider+import com.gotcha.i18n.stringLookupimport okhttp3.ResponseBody.Companion.toResponseBodyimport org.junit.Assert.assertTrueimport org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunnerimport retrofit2.HttpExceptionimport retrofit2.Responseimport java.io.IOException@@ -12,102 +17,125 @@ import java.net.ConnectExceptionimport java.net.SocketTimeoutExceptionimport java.net.UnknownHostException+@RunWith(RobolectricTestRunner::class)class HumanReadableErrorTest {+ private val strings = ApplicationProvider.getApplicationContext<Context>().stringLookup()+@Testfun testFromHttpCodeKnownAndFallbackCodes() {- assertTrue(HumanReadableError.fromHttpCode(400).contains("Bad request"))- assertTrue(HumanReadableError.fromHttpCode(401).contains("Authentication failed"))- assertTrue(HumanReadableError.fromHttpCode(403).contains("Access restricted"))- assertTrue(HumanReadableError.fromHttpCode(404).contains("Resource not found"))- assertTrue(HumanReadableError.fromHttpCode(408).contains("Request timeout"))- assertTrue(HumanReadableError.fromHttpCode(429).contains("Rate limit"))- assertTrue(HumanReadableError.fromHttpCode(500).contains("Server error"))- assertTrue(HumanReadableError.fromHttpCode(502).contains("Bad gateway"))- assertTrue(HumanReadableError.fromHttpCode(503).contains("Service unavailable"))- assertTrue(HumanReadableError.fromHttpCode(504).contains("Gateway timeout"))-- val fallback = HumanReadableError.fromHttpCode(418, "I'm a teapot")+ assertTrue(HumanReadableError.fromHttpCode(400, strings = strings).contains("Bad request"))+ assertTrue(HumanReadableError.fromHttpCode(401, strings = strings).contains("Authentication failed"))+ assertTrue(HumanReadableError.fromHttpCode(403, strings = strings).contains("Access restricted"))+ assertTrue(HumanReadableError.fromHttpCode(404, strings = strings).contains("Resource not found"))+ assertTrue(HumanReadableError.fromHttpCode(408, strings = strings).contains("Request timeout"))+ assertTrue(HumanReadableError.fromHttpCode(429, strings = strings).contains("Rate limit"))+ assertTrue(HumanReadableError.fromHttpCode(500, strings = strings).contains("Server error"))+ assertTrue(HumanReadableError.fromHttpCode(502, strings = strings).contains("Bad gateway"))+ assertTrue(HumanReadableError.fromHttpCode(503, strings = strings).contains("Service unavailable"))+ assertTrue(HumanReadableError.fromHttpCode(504, strings = strings).contains("Gateway timeout"))++ val fallback = HumanReadableError.fromHttpCode(418, "I'm a teapot", strings = strings)assertTrue(fallback.contains("HTTP 418"))assertTrue(fallback.contains("I'm a teapot"))}@Testfun testFromSpeechRecognizerCodeKnownAndFallbackCodes() {- val errTimeout = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_NETWORK_TIMEOUT)+ val errTimeout = HumanReadableError.fromSpeechRecognizerCode(+ SpeechRecognizer.ERROR_NETWORK_TIMEOUT,+ strings = strings+ )assertTrue(errTimeout.contains("timed out"))- val errNet = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_NETWORK)+ val errNet = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_NETWORK, strings = strings)assertTrue(errNet.contains("Network connection error"))- val errAudio = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_AUDIO)+ val errAudio = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_AUDIO, strings = strings)assertTrue(errAudio.contains("Microphone hardware error"))- val errServer = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_SERVER)+ val errServer = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_SERVER, strings = strings)assertTrue(errServer.contains("server error"))- val errClient = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_CLIENT)+ val errClient = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_CLIENT, strings = strings)assertTrue(errClient.contains("client error"))- val errSpeechTimeout = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_SPEECH_TIMEOUT)+ val errSpeechTimeout = HumanReadableError.fromSpeechRecognizerCode(+ SpeechRecognizer.ERROR_SPEECH_TIMEOUT,+ strings = strings+ )assertTrue(errSpeechTimeout.contains("No speech detected"))- val errNoMatch = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_NO_MATCH)+ val errNoMatch = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_NO_MATCH, strings = strings)assertTrue(errNoMatch.contains("Could not understand speech"))- val errBusy = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_RECOGNIZER_BUSY)+ val errBusy = HumanReadableError.fromSpeechRecognizerCode(+ SpeechRecognizer.ERROR_RECOGNIZER_BUSY,+ strings = strings+ )assertTrue(errBusy.contains("recognizer is busy"))- val errPerm = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS)+ val errPerm = HumanReadableError.fromSpeechRecognizerCode(+ SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS,+ strings = strings+ )assertTrue(errPerm.contains("Microphone permission"))- val errRate = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_TOO_MANY_REQUESTS)+ val errRate = HumanReadableError.fromSpeechRecognizerCode(+ SpeechRecognizer.ERROR_TOO_MANY_REQUESTS,+ strings = strings+ )assertTrue(errRate.contains("Too many speech recognition"))- val errDisc = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_SERVER_DISCONNECTED)+ val errDisc = HumanReadableError.fromSpeechRecognizerCode(+ SpeechRecognizer.ERROR_SERVER_DISCONNECTED,+ strings = strings+ )assertTrue(errDisc.contains("disconnected"))- val fallback = HumanReadableError.fromSpeechRecognizerCode(99)+ val fallback = HumanReadableError.fromSpeechRecognizerCode(99, strings = strings)assertTrue(fallback.contains("code 99"))}@Testfun testFromTtsCodeKnownAndFallbackCodes() {- val synthErr = HumanReadableError.fromTtsCode(TextToSpeech.ERROR_SYNTHESIS)+ val synthErr = HumanReadableError.fromTtsCode(TextToSpeech.ERROR_SYNTHESIS, strings = strings)assertTrue(synthErr.contains("Speech synthesis error"))- val svcErr = HumanReadableError.fromTtsCode(TextToSpeech.ERROR_SERVICE)+ val svcErr = HumanReadableError.fromTtsCode(TextToSpeech.ERROR_SERVICE, strings = strings)assertTrue(svcErr.contains("service error"))- val fallback = HumanReadableError.fromTtsCode(99)+ val fallback = HumanReadableError.fromTtsCode(99, strings = strings)assertTrue(fallback.contains("code 99"))}@Testfun testFormatExceptions() {val httpEx = HttpException(Response.error<String>(401, "".toResponseBody(null)))- assertTrue(HumanReadableError.format(httpEx).contains("Authentication failed"))+ assertTrue(HumanReadableError.format(httpEx, strings = strings).contains("Authentication failed"))val unknownHost = UnknownHostException("api.openai.com")- assertTrue(HumanReadableError.format(unknownHost).contains("Cannot connect to server"))+ assertTrue(HumanReadableError.format(unknownHost, strings = strings).contains("Cannot connect to server"))val connectEx = ConnectException("Failed to connect")- assertTrue(HumanReadableError.format(connectEx).contains("Connection refused"))+ assertTrue(HumanReadableError.format(connectEx, strings = strings).contains("Connection refused"))val timeout = SocketTimeoutException("Read timed out")- assertTrue(HumanReadableError.format(timeout).contains("Connection timed out"))+ assertTrue(HumanReadableError.format(timeout, strings = strings).contains("Connection timed out"))val ioWithHttp = IOException("HTTP 429: Too Many Requests")- assertTrue(HumanReadableError.format(ioWithHttp).contains("Rate limit"))+ assertTrue(HumanReadableError.format(ioWithHttp, strings = strings).contains("Rate limit"))val genericIo = IOException("Disk read failed")- assertTrue(HumanReadableError.format(genericIo).contains("Network problem: Disk read failed"))+ assertTrue(+ HumanReadableError.format(genericIo, strings = strings).contains("Network problem: Disk read failed")+ )val secEx = SecurityException("RECORD_AUDIO missing")- assertTrue(HumanReadableError.format(secEx).contains("Permission denied"))+ assertTrue(HumanReadableError.format(secEx, strings = strings).contains("Permission denied"))val genericEx = IllegalStateException("State invalid")- assertTrue(HumanReadableError.format(genericEx).contains("Error: State invalid"))+ assertTrue(HumanReadableError.format(genericEx, strings = strings).contains("Error: State invalid"))val tierGating403 = HttpException(Response.error<String>(@@ -115,28 +143,34 @@ class HumanReadableErrorTest {"{\"detail\":\"Upgrade to Pro to access this model\"}".toResponseBody(null)))- assertTrue(HumanReadableError.format(tierGating403).contains("Upgrade to Pro"))+ assertTrue(HumanReadableError.format(tierGating403, strings = strings).contains("Upgrade to Pro"))val emptyEx = RuntimeException("")- assertTrue(HumanReadableError.format(emptyEx).contains("An unexpected error occurred"))+ assertTrue(HumanReadableError.format(emptyEx, strings = strings).contains("An unexpected error occurred"))}@Testfun `an HTTP rejection that names images explains how to recover`() {- val msg = HumanReadableError.fromHttpCode(400, "Too many images in request. Max is 3.")+ val msg = HumanReadableError.fromHttpCode(400, "Too many images in request. Max is 3.", strings = strings)assertTrue(msg.contains("rejected the attached images"))assertTrue(msg.contains("Too many images in request. Max is 3."))assertTrue(msg.contains("Remove some attachments"))- val tooLarge = HumanReadableError.fromHttpCode(413, "image exceeds 5 MB maximum")+ val tooLarge = HumanReadableError.fromHttpCode(413, "image exceeds 5 MB maximum", strings = strings)assertTrue(tooLarge.contains("rejected the attached images"))}@Testfun `an HTTP rejection without images keeps its usual explanation`() {- assertTrue(HumanReadableError.fromHttpCode(400, "bad json").contains("Bad request"))- assertTrue(HumanReadableError.fromHttpCode(413).contains("Request too large"))+ assertTrue(HumanReadableError.fromHttpCode(400, "bad json", strings = strings).contains("Bad request"))+ assertTrue(HumanReadableError.fromHttpCode(413, strings = strings).contains("Request too large"))// Only request errors are reinterpreted, not e.g. auth failures that mention images.- assertTrue(HumanReadableError.fromHttpCode(401, "image model requires auth").contains("Authentication failed"))+ assertTrue(+ HumanReadableError.fromHttpCode(+ 401,+ "image model requires auth",+ strings = strings+ ).contains("Authentication failed")+ )}}