From 583d1b379495c89fd2a87def4f87decdc01ffae1 Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sun, 22 Nov 2026 10:16:07 +0100 Subject: [PATCH] Custom AI keys: keep the result when the keyboard hides, insert it only into the same field Some editors hide the keyboard while a custom AI key runs (they react to the cursor being moved for the result). The request was cancelled and the result lost. Now a custom key request keeps running when the keyboard hides (proofread and translate are still cancelled), and a result that arrives meanwhile is inserted when the keyboard is back in the same field within two minutes. Many apps use the same field id for all their text fields (e.g. every chat). So a kept result, or a result after another field was opened meanwhile, is only inserted if the app, input type and text of the field are the same as when the request was made (from the text already read for the request; the text the app gives for extraction is only read if the first comparison fails), never in a password field. Otherwise it is copied to the clipboard with a short message. While the keyboard stays in the same field, the behaviour is as before. Offline AI: one generation at a time. The plugin can't stop a running generation, and a new request failed with "Context is busy". It now waits for the previous one, and is skipped if it was cancelled while waiting. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VuiaMhLXwhErf9shhrr1uD --- .../java/helium314/keyboard/latin/LatinIME.kt | 5 +- .../keyboard/latin/inputlogic/AiFieldCheck.kt | 34 ++++++ .../keyboard/latin/inputlogic/InputLogic.kt | 106 ++++++++++++++++-- app/src/main/res/values/strings.xml | 1 + .../keyboard/latin/utils/ProofreadHelper.kt | 17 ++- .../keyboard/latin/utils/ProofreadService.kt | 30 +++-- .../keyboard/latin/utils/ProofreadHelper.kt | 15 ++- .../latin/inputlogic/AiFieldCheckTest.kt | 43 +++++++ 8 files changed, 229 insertions(+), 22 deletions(-) create mode 100644 app/src/main/java/helium314/keyboard/latin/inputlogic/AiFieldCheck.kt create mode 100644 app/src/test/java/helium314/keyboard/latin/inputlogic/AiFieldCheckTest.kt diff --git a/app/src/main/java/helium314/keyboard/latin/LatinIME.kt b/app/src/main/java/helium314/keyboard/latin/LatinIME.kt index 0f6cb10065..fbe440fac7 100644 --- a/app/src/main/java/helium314/keyboard/latin/LatinIME.kt +++ b/app/src/main/java/helium314/keyboard/latin/LatinIME.kt @@ -1090,7 +1090,8 @@ class LatinIME : InputMethodService(), keyboardSwitcher.hideGifPicker() keyboardSwitcher.hideOcrPanels() clipboardHistoryManager.onWindowHidden() - ProofreadHelper.cancelCurrentJob() + // a custom AI key request keeps running, its result is inserted when the keyboard is back in the same field + ProofreadHelper.cancelCurrentJob(keepCustomKeyJob = true) val fkm = floatingKeyboardManager if (fkm != null) { if (!settings.current.mRememberFloatingKeyboard) { @@ -1123,7 +1124,7 @@ class LatinIME : InputMethodService(), if (keyboardSwitcher.isOcrShowing) { keyboardSwitcher.hideOcrPanels() } - ProofreadHelper.cancelCurrentJob() + ProofreadHelper.cancelCurrentJob(keepCustomKeyJob = true) voiceInputManager?.cancelVoice() updateVoiceKeepScreenOn(VoiceInputManager.VoiceState.IDLE) releaseVoicePluginOnIdle(preserveExistingSchedule = true) diff --git a/app/src/main/java/helium314/keyboard/latin/inputlogic/AiFieldCheck.kt b/app/src/main/java/helium314/keyboard/latin/inputlogic/AiFieldCheck.kt new file mode 100644 index 0000000000..54e9d36c61 --- /dev/null +++ b/app/src/main/java/helium314/keyboard/latin/inputlogic/AiFieldCheck.kt @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: GPL-3.0-only +package helium314.keyboard.latin.inputlogic + +/** + * Whether an AI result can still be inserted into the field it was asked for, after the keyboard was + * hidden or another field was opened meanwhile. Many apps use the same field id for all their text + * fields (e.g. every chat), so the field is identified by the app, the input type and its text as it + * was read for the request. Only a hash and the length of the text are kept. + */ +internal object AiFieldCheck { + class Fingerprint internal constructor( + private val packageName: String?, + private val inputType: Int, + private val textHash: Int, + private val textLength: Int, + ) { + /** + * [aroundCursor]: text before the cursor + selected text + text after the cursor. [extracted] + * gives the whole text as the app gives it for extraction; it is only asked for if the text + * around the cursor differs, as some apps report it unreliably. + */ + fun matches(packageName: String?, inputType: Int, isPassword: Boolean, aroundCursor: String, extracted: () -> String?): Boolean { + if (isPassword || packageName != this.packageName || inputType != this.inputType) return false + if (isSameText(aroundCursor)) return true + return extracted()?.let { isSameText(it) } == true + } + + private fun isSameText(text: String) = text.length == textLength && text.hashCode() == textHash + } + + /** [text]: the whole text of the field as read for the request. Null for password fields: nothing is inserted there later. */ + fun fingerprint(packageName: String?, inputType: Int, isPassword: Boolean, text: String): Fingerprint? = + if (isPassword) null else Fingerprint(packageName, inputType, text.hashCode(), text.length) +} diff --git a/app/src/main/java/helium314/keyboard/latin/inputlogic/InputLogic.kt b/app/src/main/java/helium314/keyboard/latin/inputlogic/InputLogic.kt index 4ead40cfc4..00a71f5caa 100644 --- a/app/src/main/java/helium314/keyboard/latin/inputlogic/InputLogic.kt +++ b/app/src/main/java/helium314/keyboard/latin/inputlogic/InputLogic.kt @@ -158,6 +158,10 @@ class InputLogic( mInputLogicHandler.reset() mConnection.requestCursorUpdates(true, true) setInlineEmojiSearchAction(false) + mInputSession++ + // a custom AI key result that arrived while the keyboard was hidden, once the field is ready again + if (mPendingAIResult != null) + android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({ insertPendingAIResult() }, 300) } fun onSubtypeChanged(combiningSpec: String?, settingsValues: SettingsValues) { @@ -3267,13 +3271,24 @@ class InputLogic( val targetEditorInfo = getCurrentInputEditorInfo() val targetPackage = targetEditorInfo?.packageName val targetFieldId = targetEditorInfo?.fieldId + // to recognize the field if the keyboard is hidden or another field opened meanwhile; from the text read + // above, which is the whole text without a selection (with a selection, such a result goes to the clipboard) + val targetInputType = targetEditorInfo?.inputType ?: 0 + val targetField = if (hasSelection) null else AiFieldCheck.fingerprint(targetPackage, targetInputType, + InputTypeUtils.isPasswordInputType(targetInputType), textToProcess) + val inputSession = mInputSession + mPendingAIResult = null // an older result must not be inserted after this one ProofreadHelper.customAsync( mLatinIME, textToProcess, prompt, hasSelection, showThinking, onSuccess = { resultText -> if (!mLatinIME.isInputViewShown || !mConnection.isConnected()) { - Log.w(TAG, "Input view hidden or disconnected during custom AI operation, ignoring result") + // some editors hide the keyboard meanwhile (e.g. when the cursor is moved): + // insert when the keyboard is back in this field, see insertPendingAIResult + Log.i(TAG, "Input view hidden during custom AI operation, keeping the result") + mPendingAIResult = PendingAIResult(resultText, targetPackage, targetFieldId, hasSelection, + shouldAppend, SystemClock.uptimeMillis(), targetField) return@customAsync } val currentEditor = getCurrentInputEditorInfo() @@ -3281,14 +3296,12 @@ class InputLogic( Log.w(TAG, "Target editor changed during custom AI operation, ignoring result") return@customAsync } - if (shouldAppend) { - val textBefore = mConnection.getTextBeforeCursor(2, 0) ?: "" - mLatinIME.onTextInput(CustomAIKeyText.separatorBefore(textBefore) + resultText.trim()) - } else if (!hasSelection) { - mConnection.replaceEntireText(resultText) - } else { - mLatinIME.onTextInput(resultText) + // another field was opened meanwhile, e.g. another chat with the same field id + if (mInputSession != inputSession && !isSameAiField(targetField)) { + keepAIResultInClipboard(resultText) + return@customAsync } + insertAIResult(resultText, hasSelection, shouldAppend, moveToEnd = false) }, onError = { errorMessage -> Log.e(TAG, "Custom AI Error: $errorMessage") @@ -3297,6 +3310,79 @@ class InputLogic( ) } + /** counts the fields opened, to notice if another field was opened during an AI request */ + private var mInputSession = 0 + + /** Result of a custom AI key that arrived while the keyboard was hidden */ + private class PendingAIResult( + val text: String, val packageName: String?, val fieldId: Int?, + val hasSelection: Boolean, val shouldAppend: Boolean, val time: Long, val target: AiFieldCheck.Fingerprint? + ) + private var mPendingAIResult: PendingAIResult? = null + + /** Whether the current field is the one of [target], see [AiFieldCheck] */ + private fun isSameAiField(target: AiFieldCheck.Fingerprint?): Boolean { + val editor = getCurrentInputEditorInfo() ?: return false + if (target == null) return false + val before = mConnection.getTextBeforeCursor(AI_FIELD_TEXT_CHARS, 0)?.toString() ?: "" + val selected = mConnection.getSelectedText(0)?.toString() ?: "" + val after = mConnection.getTextAfterCursor(AI_FIELD_TEXT_CHARS, 0)?.toString() ?: "" + return target.matches(editor.packageName, editor.inputType, InputTypeUtils.isPasswordInputType(editor.inputType), + before + selected + after) { extractedFieldText() } + } + + /** The whole text as the app gives it for extraction, null if it does not */ + private fun extractedFieldText(): String? = try { + val request = android.view.inputmethod.ExtractedTextRequest().apply { hintMaxChars = AI_FIELD_TEXT_CHARS * 2 } + mLatinIME.currentInputConnection?.getExtractedText(request, 0)?.text?.toString() + } catch (e: Exception) { + null + } + + /** An AI result for a field that changed meanwhile: not lost, but not inserted at the wrong place */ + private fun keepAIResultInClipboard(text: String) { + if (text.isBlank()) return + Log.w(TAG, "field changed during the AI request, result copied to the clipboard") + val clipboard = mLatinIME.getSystemService(android.content.Context.CLIPBOARD_SERVICE) as? android.content.ClipboardManager ?: return + clipboard.setPrimaryClip(android.content.ClipData.newPlainText("AI", text)) + KeyboardSwitcher.getInstance().showToast(mLatinIME.getString(R.string.ai_result_to_clipboard), false) + } + + private fun insertAIResult(text: String, hasSelection: Boolean, shouldAppend: Boolean, moveToEnd: Boolean) { + if (shouldAppend) { + if (moveToEnd && !hasSelection) { + // the field was tapped again after the keyboard was hidden: the cursor may be elsewhere + val after = mConnection.getTextAfterCursor(AI_FIELD_TEXT_CHARS, 0)?.length ?: 0 + if (after > 0 && mConnection.expectedSelectionEnd >= 0) { + val end = mConnection.expectedSelectionEnd + after + mConnection.setSelection(end, end) + } + } + val textBefore = mConnection.getTextBeforeCursor(2, 0) ?: "" + mLatinIME.onTextInput(CustomAIKeyText.separatorBefore(textBefore) + text.trim()) + } else if (!hasSelection) { + mConnection.replaceEntireText(text) + } else { + mLatinIME.onTextInput(text) + } + } + + /** Inserts a result that arrived while the keyboard was hidden, if the keyboard is back in the same field soon */ + private fun insertPendingAIResult() { + val pending = mPendingAIResult ?: return + mPendingAIResult = null + if (SystemClock.uptimeMillis() - pending.time > PENDING_AI_RESULT_MS) return + if (!mLatinIME.isInputViewShown || !mConnection.isConnected()) return + val editor = getCurrentInputEditorInfo() + // a newer request is running, or a selection was to be replaced: it is gone with the hidden keyboard + if (ProofreadHelper.isOperationInProgress || editor?.packageName != pending.packageName + || editor?.fieldId != pending.fieldId || pending.hasSelection || !isSameAiField(pending.target)) { + keepAIResultInClipboard(pending.text) + return + } + insertAIResult(pending.text, hasSelection = false, shouldAppend = pending.shouldAppend, moveToEnd = true) + } + private fun tryJumpToNextPlaceholder(): Boolean { val before = mConnection.getTextBeforeCursor(1000, 0) val after = mConnection.getTextAfterCursor(1000, 0) @@ -3440,6 +3526,10 @@ class InputLogic( } private const val BACKSPACE_WORD_LOOKBACK = 200 private val THAI_LOCALE = Locale.forLanguageTag("th") + /** how long a result waits for the keyboard to come back into its field */ + private const val PENDING_AI_RESULT_MS = 2 * 60 * 1000L + /** text read around the cursor to recognize the field of an AI request, as for the request */ + private const val AI_FIELD_TEXT_CHARS = 60000 private val THAI_WORD_BREAK_ITERATOR = object : ThreadLocal() { override fun initialValue(): BreakIterator = BreakIterator.getWordInstance(THAI_LOCALE) } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index d6d569facb..e930a94c23 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2128,6 +2128,7 @@ New dictionary: Translation unchanged or identical to source text. Error getting suggestions AI Error: %s + The text field changed meanwhile, the AI result is in the clipboard \"%1$s\" removed Key set Not set diff --git a/app/src/offline/java/helium314/keyboard/latin/utils/ProofreadHelper.kt b/app/src/offline/java/helium314/keyboard/latin/utils/ProofreadHelper.kt index 97d37d7b61..ebfbb6bda3 100644 --- a/app/src/offline/java/helium314/keyboard/latin/utils/ProofreadHelper.kt +++ b/app/src/offline/java/helium314/keyboard/latin/utils/ProofreadHelper.kt @@ -67,7 +67,15 @@ object ProofreadHelper { } } - fun cancelCurrentJob() { + /** whether the running request was started by a custom AI key */ + private var currentJobIsCustomKey = false + + /** + * Cancels the running request, e.g. when the keyboard is hidden. With [keepCustomKeyJob], a request + * of a custom AI key keeps running: its result is inserted when the keyboard is back in the same field. + */ + fun cancelCurrentJob(keepCustomKeyJob: Boolean = false) { + if (keepCustomKeyJob && currentJobIsCustomKey && isOperationInProgress) return cancelCurrentOperation() } @@ -79,7 +87,8 @@ object ProofreadHelper { skipModelCheck: Boolean = false, apiCall: suspend (ProofreadService) -> Result, onSuccess: (String) -> Unit, - onError: (String) -> Unit + onError: (String) -> Unit, + isCustomKey: Boolean = false ) { val service = ProofreadService(context) @@ -113,6 +122,7 @@ object ProofreadHelper { } // Launch coroutine for inference and track it for cancellation + currentJobIsCustomKey = isCustomKey currentJob = scope.launch { val result = apiCall(service) @@ -471,7 +481,8 @@ object ProofreadHelper { errorResId = R.string.proofread_error, apiCall = { service -> service.proofread(text, overridePrompt = prompt, showThinking = showThinking) }, onSuccess = onSuccess, - onError = onError + onError = onError, + isCustomKey = true ) } diff --git a/app/src/offline/java/helium314/keyboard/latin/utils/ProofreadService.kt b/app/src/offline/java/helium314/keyboard/latin/utils/ProofreadService.kt index 35de613bad..5d9c8f6a47 100644 --- a/app/src/offline/java/helium314/keyboard/latin/utils/ProofreadService.kt +++ b/app/src/offline/java/helium314/keyboard/latin/utils/ProofreadService.kt @@ -15,6 +15,7 @@ import helium314.keyboard.latin.settings.Defaults import helium314.keyboard.latin.settings.Settings import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext +import kotlinx.coroutines.isActive import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.CoroutineScope @@ -85,6 +86,14 @@ class ProofreadService(private val context: Context) { isModelAvailable = true } + /** + * One generation at a time. A cancelled request keeps running in the plugin until it is done + * (e.g. a custom AI key whose keyboard was hidden, or a cancelled one), and a new one would fail + * with "Context is busy" and give no output. It waits here instead. A plain lock, as it is held by + * the thread blocked in the plugin. + */ + val generateLock = Any() + suspend fun loadModel( context: Context, modelPath: String @@ -413,13 +422,20 @@ class ProofreadService(private val context: Context) { // Use provider to generate completion OfflineAiLoader.isBusy = true val output = try { - provider.generate(fullPrompt, mapOf( - "temperature" to temp.toDouble(), - "top_p" to topP.toDouble(), - "top_k" to topK, - "min_p" to minP.toDouble(), - "max_tokens" to effectiveMaxTokens - )) + synchronized(ModelHolder.generateLock) { + // cancelled while waiting for the previous generation: don't start one, it can't be stopped + if (!isActive) { + ModelHolder.scheduleUnload(context) + return@withContext Result.failure(ProofreadException("Cancelled")) + } + provider.generate(fullPrompt, mapOf( + "temperature" to temp.toDouble(), + "top_p" to topP.toDouble(), + "top_k" to topK, + "min_p" to minP.toDouble(), + "max_tokens" to effectiveMaxTokens + )) + } } finally { OfflineAiLoader.isBusy = false } diff --git a/app/src/standard/java/helium314/keyboard/latin/utils/ProofreadHelper.kt b/app/src/standard/java/helium314/keyboard/latin/utils/ProofreadHelper.kt index 848ef7b4fa..287c112905 100644 --- a/app/src/standard/java/helium314/keyboard/latin/utils/ProofreadHelper.kt +++ b/app/src/standard/java/helium314/keyboard/latin/utils/ProofreadHelper.kt @@ -58,7 +58,15 @@ object ProofreadHelper { } } - fun cancelCurrentJob() { + /** whether the running request was started by a custom AI key */ + private var currentJobIsCustomKey = false + + /** + * Cancels the running request, e.g. when the keyboard is hidden. With [keepCustomKeyJob], a request + * of a custom AI key keeps running: its result is inserted when the keyboard is back in the same field. + */ + fun cancelCurrentJob(keepCustomKeyJob: Boolean = false) { + if (keepCustomKeyJob && currentJobIsCustomKey && isOperationInProgress) return cancelCurrentOperation() } @@ -71,7 +79,8 @@ object ProofreadHelper { onSuccess: (String) -> Unit, onError: (String) -> Unit, allowEmptyInput: Boolean = false, - skipApiKeyCheck: Boolean = false + skipApiKeyCheck: Boolean = false, + isCustomKey: Boolean = false ) { val service = ProofreadService(context) @@ -144,6 +153,7 @@ object ProofreadHelper { } // Launch coroutine for API call and track it for cancellation + currentJobIsCustomKey = isCustomKey currentJob = scope.launch { val result = apiCall(service) @@ -540,6 +550,7 @@ object ProofreadHelper { apiCall = { service -> service.proofread(text, overridePrompt = prompt, showThinking = showThinking) }, onSuccess = onSuccess, onError = onError, + isCustomKey = true, allowEmptyInput = true ) } diff --git a/app/src/test/java/helium314/keyboard/latin/inputlogic/AiFieldCheckTest.kt b/app/src/test/java/helium314/keyboard/latin/inputlogic/AiFieldCheckTest.kt new file mode 100644 index 0000000000..f8cbd58b6c --- /dev/null +++ b/app/src/test/java/helium314/keyboard/latin/inputlogic/AiFieldCheckTest.kt @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: GPL-3.0-only +package helium314.keyboard.latin.inputlogic + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class AiFieldCheckTest { + private val pkg = "com.example.chat" + private val target = AiFieldCheck.fingerprint(pkg, 1, false, "Hallo Welt")!! + + @Test + fun sameFieldAndTextMatches() { + assertTrue(target.matches(pkg, 1, false, "Hallo Welt") { null }) + } + + @Test + fun otherChatOrChangedTextDoesNotMatch() { + // same app and field id, but another chat with other text + assertFalse(target.matches(pkg, 1, false, "Bis morgen") { "Bis morgen" }) + assertFalse(target.matches(pkg, 1, false, "Hallo Welt!") { null }) + assertFalse(target.matches("com.example.mail", 1, false, "Hallo Welt") { null }) + assertFalse(target.matches(pkg, 2, false, "Hallo Welt") { null }) + assertFalse(target.matches(pkg, 1, true, "Hallo Welt") { null }) + } + + @Test + fun wholeTextIsOnlyReadWhenNeeded() { + var reads = 0 + assertTrue(target.matches(pkg, 1, false, "Hallo Welt") { reads++; "Hallo Welt" }) + assertEquals(0, reads) + // the app reports the text around the cursor unreliably, the whole text is the same + assertTrue(target.matches(pkg, 1, false, "Hallo ") { reads++; "Hallo Welt" }) + assertEquals(1, reads) + } + + @Test + fun passwordFieldsAreNeverRemembered() { + assertNull(AiFieldCheck.fingerprint(pkg, 1, true, "secret")) + } +}