Skip to content

Commit 583d1b3

Browse files
4di-helloclaude
andcommitted
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VuiaMhLXwhErf9shhrr1uD
1 parent 5966a60 commit 583d1b3

8 files changed

Lines changed: 229 additions & 22 deletions

File tree

‎app/src/main/java/helium314/keyboard/latin/LatinIME.kt‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1090,7 +1090,8 @@ class LatinIME : InputMethodService(),
10901090
keyboardSwitcher.hideGifPicker()
10911091
keyboardSwitcher.hideOcrPanels()
10921092
clipboardHistoryManager.onWindowHidden()
1093-
ProofreadHelper.cancelCurrentJob()
1093+
// a custom AI key request keeps running, its result is inserted when the keyboard is back in the same field
1094+
ProofreadHelper.cancelCurrentJob(keepCustomKeyJob = true)
10941095
val fkm = floatingKeyboardManager
10951096
if (fkm != null) {
10961097
if (!settings.current.mRememberFloatingKeyboard) {
@@ -1123,7 +1124,7 @@ class LatinIME : InputMethodService(),
11231124
if (keyboardSwitcher.isOcrShowing) {
11241125
keyboardSwitcher.hideOcrPanels()
11251126
}
1126-
ProofreadHelper.cancelCurrentJob()
1127+
ProofreadHelper.cancelCurrentJob(keepCustomKeyJob = true)
11271128
voiceInputManager?.cancelVoice()
11281129
updateVoiceKeepScreenOn(VoiceInputManager.VoiceState.IDLE)
11291130
releaseVoicePluginOnIdle(preserveExistingSchedule = true)
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// SPDX-License-Identifier: GPL-3.0-only
2+
package helium314.keyboard.latin.inputlogic
3+
4+
/**
5+
* Whether an AI result can still be inserted into the field it was asked for, after the keyboard was
6+
* hidden or another field was opened meanwhile. Many apps use the same field id for all their text
7+
* fields (e.g. every chat), so the field is identified by the app, the input type and its text as it
8+
* was read for the request. Only a hash and the length of the text are kept.
9+
*/
10+
internal object AiFieldCheck {
11+
class Fingerprint internal constructor(
12+
private val packageName: String?,
13+
private val inputType: Int,
14+
private val textHash: Int,
15+
private val textLength: Int,
16+
) {
17+
/**
18+
* [aroundCursor]: text before the cursor + selected text + text after the cursor. [extracted]
19+
* gives the whole text as the app gives it for extraction; it is only asked for if the text
20+
* around the cursor differs, as some apps report it unreliably.
21+
*/
22+
fun matches(packageName: String?, inputType: Int, isPassword: Boolean, aroundCursor: String, extracted: () -> String?): Boolean {
23+
if (isPassword || packageName != this.packageName || inputType != this.inputType) return false
24+
if (isSameText(aroundCursor)) return true
25+
return extracted()?.let { isSameText(it) } == true
26+
}
27+
28+
private fun isSameText(text: String) = text.length == textLength && text.hashCode() == textHash
29+
}
30+
31+
/** [text]: the whole text of the field as read for the request. Null for password fields: nothing is inserted there later. */
32+
fun fingerprint(packageName: String?, inputType: Int, isPassword: Boolean, text: String): Fingerprint? =
33+
if (isPassword) null else Fingerprint(packageName, inputType, text.hashCode(), text.length)
34+
}

‎app/src/main/java/helium314/keyboard/latin/inputlogic/InputLogic.kt‎

Lines changed: 98 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,10 @@ class InputLogic(
158158
mInputLogicHandler.reset()
159159
mConnection.requestCursorUpdates(true, true)
160160
setInlineEmojiSearchAction(false)
161+
mInputSession++
162+
// a custom AI key result that arrived while the keyboard was hidden, once the field is ready again
163+
if (mPendingAIResult != null)
164+
android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({ insertPendingAIResult() }, 300)
161165
}
162166

163167
fun onSubtypeChanged(combiningSpec: String?, settingsValues: SettingsValues) {
@@ -3267,28 +3271,37 @@ class InputLogic(
32673271
val targetEditorInfo = getCurrentInputEditorInfo()
32683272
val targetPackage = targetEditorInfo?.packageName
32693273
val targetFieldId = targetEditorInfo?.fieldId
3274+
// to recognize the field if the keyboard is hidden or another field opened meanwhile; from the text read
3275+
// above, which is the whole text without a selection (with a selection, such a result goes to the clipboard)
3276+
val targetInputType = targetEditorInfo?.inputType ?: 0
3277+
val targetField = if (hasSelection) null else AiFieldCheck.fingerprint(targetPackage, targetInputType,
3278+
InputTypeUtils.isPasswordInputType(targetInputType), textToProcess)
3279+
val inputSession = mInputSession
3280+
mPendingAIResult = null // an older result must not be inserted after this one
32703281

32713282
ProofreadHelper.customAsync(
32723283
mLatinIME,
32733284
textToProcess, prompt, hasSelection, showThinking,
32743285
onSuccess = { resultText ->
32753286
if (!mLatinIME.isInputViewShown || !mConnection.isConnected()) {
3276-
Log.w(TAG, "Input view hidden or disconnected during custom AI operation, ignoring result")
3287+
// some editors hide the keyboard meanwhile (e.g. when the cursor is moved):
3288+
// insert when the keyboard is back in this field, see insertPendingAIResult
3289+
Log.i(TAG, "Input view hidden during custom AI operation, keeping the result")
3290+
mPendingAIResult = PendingAIResult(resultText, targetPackage, targetFieldId, hasSelection,
3291+
shouldAppend, SystemClock.uptimeMillis(), targetField)
32773292
return@customAsync
32783293
}
32793294
val currentEditor = getCurrentInputEditorInfo()
32803295
if (currentEditor?.packageName != targetPackage || currentEditor?.fieldId != targetFieldId) {
32813296
Log.w(TAG, "Target editor changed during custom AI operation, ignoring result")
32823297
return@customAsync
32833298
}
3284-
if (shouldAppend) {
3285-
val textBefore = mConnection.getTextBeforeCursor(2, 0) ?: ""
3286-
mLatinIME.onTextInput(CustomAIKeyText.separatorBefore(textBefore) + resultText.trim())
3287-
} else if (!hasSelection) {
3288-
mConnection.replaceEntireText(resultText)
3289-
} else {
3290-
mLatinIME.onTextInput(resultText)
3299+
// another field was opened meanwhile, e.g. another chat with the same field id
3300+
if (mInputSession != inputSession && !isSameAiField(targetField)) {
3301+
keepAIResultInClipboard(resultText)
3302+
return@customAsync
32913303
}
3304+
insertAIResult(resultText, hasSelection, shouldAppend, moveToEnd = false)
32923305
},
32933306
onError = { errorMessage ->
32943307
Log.e(TAG, "Custom AI Error: $errorMessage")
@@ -3297,6 +3310,79 @@ class InputLogic(
32973310
)
32983311
}
32993312

3313+
/** counts the fields opened, to notice if another field was opened during an AI request */
3314+
private var mInputSession = 0
3315+
3316+
/** Result of a custom AI key that arrived while the keyboard was hidden */
3317+
private class PendingAIResult(
3318+
val text: String, val packageName: String?, val fieldId: Int?,
3319+
val hasSelection: Boolean, val shouldAppend: Boolean, val time: Long, val target: AiFieldCheck.Fingerprint?
3320+
)
3321+
private var mPendingAIResult: PendingAIResult? = null
3322+
3323+
/** Whether the current field is the one of [target], see [AiFieldCheck] */
3324+
private fun isSameAiField(target: AiFieldCheck.Fingerprint?): Boolean {
3325+
val editor = getCurrentInputEditorInfo() ?: return false
3326+
if (target == null) return false
3327+
val before = mConnection.getTextBeforeCursor(AI_FIELD_TEXT_CHARS, 0)?.toString() ?: ""
3328+
val selected = mConnection.getSelectedText(0)?.toString() ?: ""
3329+
val after = mConnection.getTextAfterCursor(AI_FIELD_TEXT_CHARS, 0)?.toString() ?: ""
3330+
return target.matches(editor.packageName, editor.inputType, InputTypeUtils.isPasswordInputType(editor.inputType),
3331+
before + selected + after) { extractedFieldText() }
3332+
}
3333+
3334+
/** The whole text as the app gives it for extraction, null if it does not */
3335+
private fun extractedFieldText(): String? = try {
3336+
val request = android.view.inputmethod.ExtractedTextRequest().apply { hintMaxChars = AI_FIELD_TEXT_CHARS * 2 }
3337+
mLatinIME.currentInputConnection?.getExtractedText(request, 0)?.text?.toString()
3338+
} catch (e: Exception) {
3339+
null
3340+
}
3341+
3342+
/** An AI result for a field that changed meanwhile: not lost, but not inserted at the wrong place */
3343+
private fun keepAIResultInClipboard(text: String) {
3344+
if (text.isBlank()) return
3345+
Log.w(TAG, "field changed during the AI request, result copied to the clipboard")
3346+
val clipboard = mLatinIME.getSystemService(android.content.Context.CLIPBOARD_SERVICE) as? android.content.ClipboardManager ?: return
3347+
clipboard.setPrimaryClip(android.content.ClipData.newPlainText("AI", text))
3348+
KeyboardSwitcher.getInstance().showToast(mLatinIME.getString(R.string.ai_result_to_clipboard), false)
3349+
}
3350+
3351+
private fun insertAIResult(text: String, hasSelection: Boolean, shouldAppend: Boolean, moveToEnd: Boolean) {
3352+
if (shouldAppend) {
3353+
if (moveToEnd && !hasSelection) {
3354+
// the field was tapped again after the keyboard was hidden: the cursor may be elsewhere
3355+
val after = mConnection.getTextAfterCursor(AI_FIELD_TEXT_CHARS, 0)?.length ?: 0
3356+
if (after > 0 && mConnection.expectedSelectionEnd >= 0) {
3357+
val end = mConnection.expectedSelectionEnd + after
3358+
mConnection.setSelection(end, end)
3359+
}
3360+
}
3361+
val textBefore = mConnection.getTextBeforeCursor(2, 0) ?: ""
3362+
mLatinIME.onTextInput(CustomAIKeyText.separatorBefore(textBefore) + text.trim())
3363+
} else if (!hasSelection) {
3364+
mConnection.replaceEntireText(text)
3365+
} else {
3366+
mLatinIME.onTextInput(text)
3367+
}
3368+
}
3369+
3370+
/** Inserts a result that arrived while the keyboard was hidden, if the keyboard is back in the same field soon */
3371+
private fun insertPendingAIResult() {
3372+
val pending = mPendingAIResult ?: return
3373+
mPendingAIResult = null
3374+
if (SystemClock.uptimeMillis() - pending.time > PENDING_AI_RESULT_MS) return
3375+
if (!mLatinIME.isInputViewShown || !mConnection.isConnected()) return
3376+
val editor = getCurrentInputEditorInfo()
3377+
// a newer request is running, or a selection was to be replaced: it is gone with the hidden keyboard
3378+
if (ProofreadHelper.isOperationInProgress || editor?.packageName != pending.packageName
3379+
|| editor?.fieldId != pending.fieldId || pending.hasSelection || !isSameAiField(pending.target)) {
3380+
keepAIResultInClipboard(pending.text)
3381+
return
3382+
}
3383+
insertAIResult(pending.text, hasSelection = false, shouldAppend = pending.shouldAppend, moveToEnd = true)
3384+
}
3385+
33003386
private fun tryJumpToNextPlaceholder(): Boolean {
33013387
val before = mConnection.getTextBeforeCursor(1000, 0)
33023388
val after = mConnection.getTextAfterCursor(1000, 0)
@@ -3440,6 +3526,10 @@ class InputLogic(
34403526
}
34413527
private const val BACKSPACE_WORD_LOOKBACK = 200
34423528
private val THAI_LOCALE = Locale.forLanguageTag("th")
3529+
/** how long a result waits for the keyboard to come back into its field */
3530+
private const val PENDING_AI_RESULT_MS = 2 * 60 * 1000L
3531+
/** text read around the cursor to recognize the field of an AI request, as for the request */
3532+
private const val AI_FIELD_TEXT_CHARS = 60000
34433533
private val THAI_WORD_BREAK_ITERATOR = object : ThreadLocal<BreakIterator>() {
34443534
override fun initialValue(): BreakIterator = BreakIterator.getWordInstance(THAI_LOCALE)
34453535
}

‎app/src/main/res/values/strings.xml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2128,6 +2128,7 @@ New dictionary:
21282128
<string name="translation_unchanged">Translation unchanged or identical to source text.</string>
21292129
<string name="error_getting_suggestions">Error getting suggestions</string>
21302130
<string name="ai_error_format">AI Error: %s</string>
2131+
<string name="ai_result_to_clipboard">The text field changed meanwhile, the AI result is in the clipboard</string>
21312132
<string name="suggestion_word_removed">\"%1$s\" removed</string>
21322133
<string name="key_set">Key set</string>
21332134
<string name="key_not_set">Not set</string>

‎app/src/offline/java/helium314/keyboard/latin/utils/ProofreadHelper.kt‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,15 @@ object ProofreadHelper {
6767
}
6868
}
6969

70-
fun cancelCurrentJob() {
70+
/** whether the running request was started by a custom AI key */
71+
private var currentJobIsCustomKey = false
72+
73+
/**
74+
* Cancels the running request, e.g. when the keyboard is hidden. With [keepCustomKeyJob], a request
75+
* of a custom AI key keeps running: its result is inserted when the keyboard is back in the same field.
76+
*/
77+
fun cancelCurrentJob(keepCustomKeyJob: Boolean = false) {
78+
if (keepCustomKeyJob && currentJobIsCustomKey && isOperationInProgress) return
7179
cancelCurrentOperation()
7280
}
7381

@@ -79,7 +87,8 @@ object ProofreadHelper {
7987
skipModelCheck: Boolean = false,
8088
apiCall: suspend (ProofreadService) -> Result<String>,
8189
onSuccess: (String) -> Unit,
82-
onError: (String) -> Unit
90+
onError: (String) -> Unit,
91+
isCustomKey: Boolean = false
8392
) {
8493
val service = ProofreadService(context)
8594

@@ -113,6 +122,7 @@ object ProofreadHelper {
113122
}
114123

115124
// Launch coroutine for inference and track it for cancellation
125+
currentJobIsCustomKey = isCustomKey
116126
currentJob = scope.launch {
117127
val result = apiCall(service)
118128

@@ -471,7 +481,8 @@ object ProofreadHelper {
471481
errorResId = R.string.proofread_error,
472482
apiCall = { service -> service.proofread(text, overridePrompt = prompt, showThinking = showThinking) },
473483
onSuccess = onSuccess,
474-
onError = onError
484+
onError = onError,
485+
isCustomKey = true
475486
)
476487
}
477488

‎app/src/offline/java/helium314/keyboard/latin/utils/ProofreadService.kt‎

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import helium314.keyboard.latin.settings.Defaults
1515
import helium314.keyboard.latin.settings.Settings
1616
import kotlinx.coroutines.Dispatchers
1717
import kotlinx.coroutines.withContext
18+
import kotlinx.coroutines.isActive
1819
import kotlinx.coroutines.Job
1920
import kotlinx.coroutines.launch
2021
import kotlinx.coroutines.CoroutineScope
@@ -85,6 +86,14 @@ class ProofreadService(private val context: Context) {
8586
isModelAvailable = true
8687
}
8788

89+
/**
90+
* One generation at a time. A cancelled request keeps running in the plugin until it is done
91+
* (e.g. a custom AI key whose keyboard was hidden, or a cancelled one), and a new one would fail
92+
* with "Context is busy" and give no output. It waits here instead. A plain lock, as it is held by
93+
* the thread blocked in the plugin.
94+
*/
95+
val generateLock = Any()
96+
8897
suspend fun loadModel(
8998
context: Context,
9099
modelPath: String
@@ -413,13 +422,20 @@ class ProofreadService(private val context: Context) {
413422
// Use provider to generate completion
414423
OfflineAiLoader.isBusy = true
415424
val output = try {
416-
provider.generate(fullPrompt, mapOf(
417-
"temperature" to temp.toDouble(),
418-
"top_p" to topP.toDouble(),
419-
"top_k" to topK,
420-
"min_p" to minP.toDouble(),
421-
"max_tokens" to effectiveMaxTokens
422-
))
425+
synchronized(ModelHolder.generateLock) {
426+
// cancelled while waiting for the previous generation: don't start one, it can't be stopped
427+
if (!isActive) {
428+
ModelHolder.scheduleUnload(context)
429+
return@withContext Result.failure(ProofreadException("Cancelled"))
430+
}
431+
provider.generate(fullPrompt, mapOf(
432+
"temperature" to temp.toDouble(),
433+
"top_p" to topP.toDouble(),
434+
"top_k" to topK,
435+
"min_p" to minP.toDouble(),
436+
"max_tokens" to effectiveMaxTokens
437+
))
438+
}
423439
} finally {
424440
OfflineAiLoader.isBusy = false
425441
}

‎app/src/standard/java/helium314/keyboard/latin/utils/ProofreadHelper.kt‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,15 @@ object ProofreadHelper {
5858
}
5959
}
6060

61-
fun cancelCurrentJob() {
61+
/** whether the running request was started by a custom AI key */
62+
private var currentJobIsCustomKey = false
63+
64+
/**
65+
* Cancels the running request, e.g. when the keyboard is hidden. With [keepCustomKeyJob], a request
66+
* of a custom AI key keeps running: its result is inserted when the keyboard is back in the same field.
67+
*/
68+
fun cancelCurrentJob(keepCustomKeyJob: Boolean = false) {
69+
if (keepCustomKeyJob && currentJobIsCustomKey && isOperationInProgress) return
6270
cancelCurrentOperation()
6371
}
6472

@@ -71,7 +79,8 @@ object ProofreadHelper {
7179
onSuccess: (String) -> Unit,
7280
onError: (String) -> Unit,
7381
allowEmptyInput: Boolean = false,
74-
skipApiKeyCheck: Boolean = false
82+
skipApiKeyCheck: Boolean = false,
83+
isCustomKey: Boolean = false
7584
) {
7685
val service = ProofreadService(context)
7786

@@ -144,6 +153,7 @@ object ProofreadHelper {
144153
}
145154

146155
// Launch coroutine for API call and track it for cancellation
156+
currentJobIsCustomKey = isCustomKey
147157
currentJob = scope.launch {
148158
val result = apiCall(service)
149159

@@ -540,6 +550,7 @@ object ProofreadHelper {
540550
apiCall = { service -> service.proofread(text, overridePrompt = prompt, showThinking = showThinking) },
541551
onSuccess = onSuccess,
542552
onError = onError,
553+
isCustomKey = true,
543554
allowEmptyInput = true
544555
)
545556
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// SPDX-License-Identifier: GPL-3.0-only
2+
package helium314.keyboard.latin.inputlogic
3+
4+
import org.junit.Assert.assertEquals
5+
import org.junit.Assert.assertFalse
6+
import org.junit.Assert.assertNull
7+
import org.junit.Assert.assertTrue
8+
import org.junit.Test
9+
10+
class AiFieldCheckTest {
11+
private val pkg = "com.example.chat"
12+
private val target = AiFieldCheck.fingerprint(pkg, 1, false, "Hallo Welt")!!
13+
14+
@Test
15+
fun sameFieldAndTextMatches() {
16+
assertTrue(target.matches(pkg, 1, false, "Hallo Welt") { null })
17+
}
18+
19+
@Test
20+
fun otherChatOrChangedTextDoesNotMatch() {
21+
// same app and field id, but another chat with other text
22+
assertFalse(target.matches(pkg, 1, false, "Bis morgen") { "Bis morgen" })
23+
assertFalse(target.matches(pkg, 1, false, "Hallo Welt!") { null })
24+
assertFalse(target.matches("com.example.mail", 1, false, "Hallo Welt") { null })
25+
assertFalse(target.matches(pkg, 2, false, "Hallo Welt") { null })
26+
assertFalse(target.matches(pkg, 1, true, "Hallo Welt") { null })
27+
}
28+
29+
@Test
30+
fun wholeTextIsOnlyReadWhenNeeded() {
31+
var reads = 0
32+
assertTrue(target.matches(pkg, 1, false, "Hallo Welt") { reads++; "Hallo Welt" })
33+
assertEquals(0, reads)
34+
// the app reports the text around the cursor unreliably, the whole text is the same
35+
assertTrue(target.matches(pkg, 1, false, "Hallo ") { reads++; "Hallo Welt" })
36+
assertEquals(1, reads)
37+
}
38+
39+
@Test
40+
fun passwordFieldsAreNeverRemembered() {
41+
assertNull(AiFieldCheck.fingerprint(pkg, 1, true, "secret"))
42+
}
43+
}

0 commit comments

Comments
 (0)