IME: accept the one stale-caret commit after a key-event edit; fix the IME hold

Gboard sends Enter as a key event, not a commit, so the IME's model
lags the buffer by exactly one edit and its next commit is anchored at
the pre-edit caret. The drift guard snapped such commits to the new
caret, duplicating the just-typed word (2026-09-19 phone incident:
'a<enter>a' became 'A' + 'AaAa').

- state.go: track one pending non-IME content edit (imeStaleEditByte,
  armed by noteNonIMEEdit on Enter/backspace/delete/cut/paste, consumed
  by the next IME commit or key edit, cleared by a tap). The guard
  accepts a small (<= 2 rune) TEXT commit ending at or before the edit
  position as-is (IME STALE-OK): everything before the edit is
  byte-identical in both models. Empty-text commits and commits ending
  past the edit still snap to the caret.
- render.go + state.go + main.go: arm the pre-commit flush hold with the
  drained frame's own EditSeq. The hold was armed with the last drawn
  frame's seq while the frame's TextField.EditSeq was never set (always
  0), so every frame matched and the hold released only via its
  8-frame timeout - silently swallowing the resync pushes (and all IME
  sync) that heal the desync. EditorLayout now ships EditSeq with the
  frame's TextField; FlushIME releases on the next higher seq.
- e2e (ime_key_edit_test.go): reproduce the incident (same-batch and
  next-batch variants) and pin the guard edges (deletions and
  past-the-edit commits still snap).
- ime.md: document the key-event desync invariant and the hold.
This commit is contained in:
gmp
2026-09-19 21:52:35 -04:00
parent 9d5c02db03
commit a9183a0f73
5 changed files with 328 additions and 21 deletions
+87 -2
View File
@@ -134,8 +134,24 @@ type EditorState struct {
// A selection push cannot heal this (it is deduplicated away after
// commits); only a restart makes the IME re-fetch the real text and
// selection around the caret. Set by HandleIMECommit on the first
// anomaly, consumed by the next frame (EditorLayout).
// anomaly and by noteNonIMEEdit (a key-event edit desyncs the IME just
// as surely as a dropped commit does), consumed by the next frame
// (EditorLayout).
IMEForceResync bool
// imeStaleEditByte is the byte position of one content edit the IME did
// NOT make (a key-event edit: Enter, hardware backspace/delete, cut,
// paste) that its local model is missing: the IME still addresses the
// caret as it was before that edit, and its next commit is anchored
// there (observed on device: Gboard sent Enter as a key event, the
// logic inserted the \n, and the very next keystroke committed against
// the pre-Enter caret, which the drift guard misread as a desync and
// snap-duplicated). -1 = no pending edit (the models agree). While set,
// the drift guard accepts one small TEXT commit that ends at or before
// the edit position — everything before it is byte-identical in both
// models, so applying it verbatim is exact (see HandleIMECommit). Any
// later IME commit or non-IME edit consumes it; a tap clears it (the
// tap's selection push / re-anchor re-reads the truth).
imeStaleEditByte int
// EditSeq counts content edits (incremented by markDirty). The shaped
// glyph layout arriving via layoutChan is only applied to the WrapIndex
// when its EditSeq matches, so a layout shaped before an edit can never
@@ -1732,6 +1748,7 @@ func handleMenuCut() {
return
}
TheState.clipboardSetChan <- text
noteNonIMEEdit(e.SelectionStart)
deleteRange(e.SelectionStart, e.SelectionEnd)
markDirty()
e.CursorPosition = e.SelectionStart
@@ -1985,6 +2002,7 @@ func utf8AdvanceWidth(seg string) int {
func HandleDelete() {
e := &TheState.Editor
if selActive() {
noteNonIMEEdit(e.SelectionStart)
deleteRange(e.SelectionStart, e.SelectionEnd)
e.CursorPosition = e.SelectionStart
ClearSelection()
@@ -1996,6 +2014,7 @@ func HandleDelete() {
if buf != nil {
seg := buf.Content(pos, pos+4)
if w := utf8AdvanceWidth(seg); w > 0 {
noteNonIMEEdit(pos)
buf.Delete(pos, w)
buf.UpdateLineIndexAfterDelete(pos, pos+w)
imeAnchorEdit(pos, seg[:w], "")
@@ -2014,6 +2033,9 @@ func HandleDelete() {
end = pos + 4
}
w := utf8AdvanceWidth(str[pos:end])
if w > 0 {
noteNonIMEEdit(pos)
}
TheState.Editor.Buffer = str[:pos] + str[pos+w:]
imeAnchorEdit(pos, str[pos:pos+w], "")
e.findEdit(pos, pos+w, 0)
@@ -2027,11 +2049,17 @@ func HandleInsert(s string) {
// copy, or the writes below are lost.
e := &TheState.Editor
pos := e.CursorPosition
if selActive() {
replacing := selActive()
if replacing {
pos = e.SelectionStart
deleteRange(e.SelectionStart, e.SelectionEnd)
ClearSelection()
}
if s != "" || replacing {
// A key-event/paste edit the IME did not make: desync bookkeeping
// (see noteNonIMEEdit).
noteNonIMEEdit(pos)
}
buf := e.ChunkedBuffer
if buf != nil {
buf.Insert(pos, s)
@@ -2052,6 +2080,7 @@ func HandleInsert(s string) {
func HandleBackspace() {
e := &TheState.Editor
if selActive() {
noteNonIMEEdit(e.SelectionStart)
deleteRange(e.SelectionStart, e.SelectionEnd)
e.CursorPosition = e.SelectionStart
ClearSelection()
@@ -2069,6 +2098,9 @@ func HandleBackspace() {
segStart = 0
}
w := utf8BackspaceWidth(buf.Content(segStart, pos))
if w > 0 {
noteNonIMEEdit(pos - w)
}
buf.Delete(pos-w, w)
buf.UpdateLineIndexAfterDelete(pos-w, pos)
imeAnchorEdit(pos-w, buf.Content(pos-w, pos), "")
@@ -2084,6 +2116,9 @@ func HandleBackspace() {
segStart = 0
}
w := utf8BackspaceWidth(str[segStart:pos])
if w > 0 {
noteNonIMEEdit(pos - w)
}
TheState.Editor.Buffer = str[:pos-w] + str[pos:]
imeAnchorEdit(pos-w, str[pos-w:pos], "")
TheState.Editor.CursorPosition = pos - w
@@ -2350,6 +2385,20 @@ type IMECommit struct {
Text string
}
// noteNonIMEEdit marks a content edit that the IME did not make: the IME's
// local model is missing it, so until a re-syncing snippet push reaches the
// IME (the next drawn frame, see IMEForceResync) the IME still addresses the
// caret as it was before the edit. Arm the resync now, and remember the edit
// position so the drift guard can accept the one commit the IME is about to
// send against its stale caret instead of snap-duplicating it. pos is the
// edit's byte position (before the mutation). Must be called on the logic
// goroutine (owner), only when the edit actually changes content.
func noteNonIMEEdit(pos int) {
e := &TheState.Editor
e.imeStaleEditByte = pos
e.IMEForceResync = true
}
// HandleIMECommit applies an IME commit from the real app (cmd/pad/main.go
// routes editor_text key.EditEvents here; the test harness uses
// HandleReplaceRange). In addition to the whole-buffer mapping it applies
@@ -2391,6 +2440,28 @@ func HandleIMECommit(data any) {
caretRune := TheState.imeRuneOffsetAt(TheState.Editor.CursorPosition)
selStartRune, selEndRune := imeSelectionRuneRange()
anomalous := endRune-startRune <= 2 && endRune != caretRune
if anomalous && c.Text != "" {
// Stale-caret tolerance (see imeStaleEditByte): a key-event edit
// (Enter, backspace, paste, cut) moved our buffer and caret without
// going through the IME, and the updated snippet may not have reached
// it yet — the commit can arrive in the very same input batch, so no
// frame has drawn. The IME's model still matches ours everywhere
// BEFORE the edit position and it still addresses the pre-edit caret,
// so a small TEXT commit ending at or before the edit position applies
// verbatim against identical text (the usual shape: the IME appending
// to, or correcting, the word it last committed). A range deletion
// (empty text) is never tolerated: deleting at a range the IME sees
// but we no longer have there is how documents get clobbered. The
// pending edit is consumed and a resync is armed: after the verbatim
// apply the IME's model is still missing our key edit, and the next
// frame's forced restart heals it.
if e := TheState.Editor.imeStaleEditByte; e >= 0 && endRune <= TheState.imeRuneOffsetAt(e) {
log.Printf("IME STALE-OK range=[%d,%d) text=%q caret=%d staleEdit=%d -> apply as-is + resync", startRune, endRune, c.Text, caretRune, e)
anomalous = false
TheState.Editor.imeStaleEditByte = -1
TheState.Editor.IMEForceResync = true
}
}
if !anomalous && c.Text != "" {
// The commit must be near the caret, or inside the live selection
// (a replacement of a user selection, wherever it is).
@@ -2423,6 +2494,9 @@ func HandleIMECommit(data any) {
// file offsets. Shared by HandleReplaceRange (rune-translated) and
// HandleIMECommit (model-translated). Must run on the logic goroutine.
func applyIMECommitBytes(startByte, endByte int, text string) {
// The IME made (or, drift-snapped, was snapped to) this edit, so its
// local model accounts for it: no key-edit is pending anymore.
TheState.Editor.imeStaleEditByte = -1
if startByte > endByte {
startByte, endByte = endByte, startByte
}
@@ -2893,6 +2967,13 @@ func EditorLayout(screenWidth, screenHeight ui.Dp, wordWrap bool) []ui.Element {
editorElem.IMESelEndRune = TheState.Editor.IMESelEndRune
editorElem.IMEForceResync = TheState.Editor.IMEForceResync
TheState.Editor.IMEForceResync = false
// EditSeq (the content-edit counter at frame-build time) is what the
// renderer's IME hold compares against: a pre-commit frame carries the
// seq the hold was armed with, a post-commit frame a newer one (which
// releases the hold). Without it every frame reads 0 and the hold can
// only time out, swallowing the resync pushes it is meant to protect
// against regressions from (see Renderer.FlushIME).
editorElem.EditSeq = TheState.Editor.EditSeq
editorElem.WindowStartByte = start
// While the find bar is open, key focus belongs to the main-owned
// "find_bar" widget.Editor: the editor stops its per-frame IME sync, and
@@ -3097,6 +3178,10 @@ func tapLocalY(ptY, regionTopY ui.Dp) float64 {
// clears any selection.
func SetCursorFromPoint(x, y float64) {
ClearSelection()
// A tap re-reads the truth: the selection push (and any snippet
// re-anchor) that follows re-synchronizes the IME, so a pending
// key-edit can no longer describe its model.
TheState.Editor.imeStaleEditByte = -1
if pos, ok := textPosFromLocalPoint(x, y); ok {
TheState.Editor.CursorPosition = pos
log.Printf("IME TAP local=(%.0f,%.0f) cursor=%d winStart=%d offsetRune=%d",