fix: restore kitty keyboard stack on exit (#1750)

Co-authored-by: drew <me@andrinoff.com>
Signed-off-by: drew <me@andrinoff.com>
This commit is contained in:
deepakganesh78 2026-08-19 17:26:33 +05:30 committed by GitHub
parent 930e18c966
commit 0d3e281d14
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 199 additions and 29 deletions

View file

@ -34,6 +34,7 @@ type cursedRenderer struct {
syncdUpdates bool // whether to use synchronized output mode for updates
starting bool // indicates whether the renderer is starting after being stopped
pendingErase bool // an scr.Erase() is pending and hasn't been drained by flush yet
noInput bool // whether input is disabled, in which case keyboard enhancement queries are pointless
}
var _ renderer = &cursedRenderer{}
@ -56,6 +57,29 @@ func (s *cursedRenderer) setLogger(logger uv.Logger) {
s.mu.Unlock()
}
// setNoInput disables keyboard enhancement requests. When the program runs
// without input, the terminal's response to a keyboard enhancement query
// would arrive after the program has exited and leak into the shell.
func (s *cursedRenderer) setNoInput(noInput bool) {
s.noInput = noInput
}
// resetKeyboardEnhancements writes the sequences that reset keyboard
// enhancement protocols when switching between the main and alt screens.
// modifyOtherKeys has no stack, so it is reset in place; the Kitty keyboard
// stack is popped, but only if we previously pushed an entry (i.e. this is
// not the first render). With input disabled the keyboard protocol is never
// touched.
func (s *cursedRenderer) resetKeyboardEnhancements(buf *bytes.Buffer) {
if s.noInput {
return
}
_, _ = buf.WriteString(ansi.ResetModifyOtherKeys)
if s.lastView != nil {
_, _ = buf.WriteString(ansi.PopKittyKeyboard(1))
}
}
// setOptimizations sets the cursor movement optimizations.
func (s *cursedRenderer) setOptimizations(hardTabs, backspace, mapnl bool) {
s.mu.Lock()
@ -132,12 +156,16 @@ func (s *cursedRenderer) start() {
if s.lastView.ProgressBar != nil {
setProgressBar(s, s.lastView.ProgressBar)
}
// Enable modifyOtherKeys and Kitty keyboard protocol.
// Both can coexist; terminals ignore what they don't support.
_, _ = s.scr.WriteString(ansi.SetModifyOtherKeys2)
if !s.noInput {
// Enable modifyOtherKeys and Kitty keyboard protocol.
// Both can coexist; terminals ignore what they don't support.
_, _ = s.scr.WriteString(ansi.SetModifyOtherKeys2)
kittyFlags := keyboardEnhancementsFlags(s.lastView.KeyboardEnhancements)
_, _ = s.scr.WriteString(ansi.KittyKeyboard(kittyFlags, 1))
kittyFlags := keyboardEnhancementsFlags(s.lastView.KeyboardEnhancements)
// The entry was popped when the renderer was stopped, so push a fresh
// one for the screen we're about to restore.
_, _ = s.scr.WriteString(ansi.PushKittyKeyboard(kittyFlags))
}
}
// close implements renderer.
@ -154,10 +182,14 @@ func (s *cursedRenderer) close() (err error) {
// two registries for the main and alt screens. We disable keyboard
// enhancements whenever we enter/exit alt screen mode in
// [cursedRenderer.flush].
// Here, we reset the keyboard protocol of the last screen used
// assuming the other screen is already reset when we switched screens.
_, _ = s.buf.WriteString(ansi.ResetModifyOtherKeys)
_, _ = s.buf.WriteString(ansi.KittyKeyboard(0, 1))
// Here, we pop the keyboard protocol of the last screen used
// assuming the other screen is already popped when we switched
// screens. With input disabled we never pushed an entry, so there is
// nothing to pop.
if !s.noInput {
_, _ = s.buf.WriteString(ansi.ResetModifyOtherKeys)
_, _ = s.buf.WriteString(ansi.PopKittyKeyboard(1))
}
// Go to the bottom of the screen.
// We need to go to the bottom of the screen regardless of whether
@ -377,9 +409,12 @@ func (s *cursedRenderer) flush(closing bool) error {
}
}
// kitty keyboard protocol
if s.lastView == nil || view.KeyboardEnhancements != s.lastView.KeyboardEnhancements ||
view.AltScreen != s.lastView.AltScreen {
// kitty keyboard protocol. Skipped entirely when input is disabled: the
// enhancements only affect keyboard input, and querying the terminal
// would leave its response unconsumed, leaking into the shell after
// the program exits.
if !s.noInput && (s.lastView == nil || view.KeyboardEnhancements != s.lastView.KeyboardEnhancements ||
view.AltScreen != s.lastView.AltScreen) {
// NOTE: We need to reset the keyboard protocol when switching
// between main and alt screen. This is because the specs specify
// two different states for the main and alt screen.
@ -388,7 +423,19 @@ func (s *cursedRenderer) flush(closing bool) error {
_, _ = s.scr.WriteString(ansi.SetModifyOtherKeys2)
kittyFlags := keyboardEnhancementsFlags(view.KeyboardEnhancements)
_, _ = s.scr.WriteString(ansi.KittyKeyboard(kittyFlags, 1))
if s.lastView == nil || view.AltScreen != s.lastView.AltScreen {
// First render or screen switch: the previous screen's entry
// (if any) is popped below, so push a fresh one for this
// screen.
_, _ = s.scr.WriteString(ansi.PushKittyKeyboard(kittyFlags))
} else {
// Only the flags changed while the same screen stays active.
// Update the topmost stack entry in place instead of popping
// and re-pushing, so a keyboard change doesn't churn the
// stack. Note that this overwrites whatever entry is currently
// on top, which is normally ours.
_, _ = s.scr.WriteString(ansi.KittyKeyboard(kittyFlags, 1))
}
if !closing {
// Request keyboard enhancements when they change
_, _ = s.scr.WriteString(ansi.RequestKittyKeyboard)
@ -513,11 +560,10 @@ func (s *cursedRenderer) flush(closing bool) error {
var buf bytes.Buffer
if shouldUpdateAltScreen {
// We always disable keyboard enhancements when switching screens
// We always reset keyboard enhancements when switching screens
// because the terminal is expected to have two different keyboard
// registries for main and alt screens.
_, _ = buf.WriteString(ansi.ResetModifyOtherKeys)
_, _ = buf.WriteString(ansi.KittyKeyboard(0, 1))
s.resetKeyboardEnhancements(&buf)
if view.AltScreen {
// Entering alt screen mode.
buf.WriteString(ansi.SetModeAltScreenSaveCursor)

View file

@ -1,10 +1,14 @@
package tea
import (
"bytes"
"fmt"
"io"
"strings"
"testing"
"time"
"github.com/charmbracelet/x/ansi"
)
type mouseRaceModel struct {
@ -78,3 +82,122 @@ func TestCursedRenderer_mouseVsFlush(t *testing.T) {
t.Fatal("program did not exit after Quit")
}
}
func assertInOrder(t *testing.T, got string, wants ...string) {
t.Helper()
rest := got
for _, want := range wants {
idx := strings.Index(rest, want)
if idx < 0 {
t.Fatalf("expected %q to appear after the previous sequences in %q", want, got)
}
rest = rest[idx+len(want):]
}
}
func TestCursedRenderer_restoresKittyKeyboardStack(t *testing.T) {
t.Parallel()
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 80, 24)
r.start()
view := NewView("hello")
view.KeyboardEnhancements.ReportEventTypes = true
pushMain := ansi.PushKittyKeyboard(keyboardEnhancementsFlags(view.KeyboardEnhancements))
pop := ansi.PopKittyKeyboard(1)
render := func(v View) {
t.Helper()
r.render(v)
if err := r.flush(false); err != nil {
t.Fatal(err)
}
}
render(view)
// Stop the renderer (as on suspend or ExecProcess) and start it again:
// close pops the stack entry, start pushes it back.
if err := r.close(); err != nil {
t.Fatal(err)
}
r.start()
// Enter and leave the alt screen. The terminal keeps a separate Kitty
// keyboard stack per screen, so each screen gets its own push and pop.
view.AltScreen = true
render(view)
view.AltScreen = false
render(view)
if err := r.close(); err != nil {
t.Fatal(err)
}
got := out.String()
// The flags are pushed once per screen activation: the first flush,
// the flush after the renderer was restarted, and on each screen
// switch. start() itself does not write to [out].
if n := strings.Count(got, pushMain); n != 4 {
t.Fatalf("expected kitty keyboard protocol to be pushed 4 times with %q (%d times), got %q", pushMain, n, got)
}
// One pop per stop/start cycle and per screen switch: closing pops the
// current screen's entry, and switching screens pops the entry of the
// screen being left.
if n := strings.Count(got, pop); n != 4 {
t.Fatalf("expected kitty keyboard protocol to be popped 4 times with %q (%d times), got %q", pop, n, got)
}
// Every pop must come after a push: the stack is balanced when pushes
// and pops alternate. The resumed flush pushes twice in a row (once in
// start(), once in flush()), and both entries are popped afterwards.
assertInOrder(t, got,
pushMain, pop, // close pops the entry pushed by the first flush
pop, // entering the alt screen pops the resumed entry
pushMain, pop, // leaving the alt screen
pushMain, pop, // the resumed main screen entry and the final close
)
if strings.Contains(got, ansi.KittyKeyboard(0, 1)) {
t.Fatalf("expected kitty keyboard protocol not to be reset in-place with %q, got %q", ansi.KittyKeyboard(0, 1), got)
}
}
func TestCursedRenderer_updatesKittyKeyboardFlagsInPlace(t *testing.T) {
t.Parallel()
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 80, 24)
render := func(v View) {
t.Helper()
r.render(v)
if err := r.flush(false); err != nil {
t.Fatal(err)
}
}
view := NewView("hello")
render(view)
// Changing the enhancement flags without switching screens updates the
// current stack entry in place instead of pushing a new one.
changed := view
changed.KeyboardEnhancements.ReportEventTypes = true
render(changed)
wantUpdate := ansi.KittyKeyboard(keyboardEnhancementsFlags(changed.KeyboardEnhancements), 1)
got := out.String()
if !strings.Contains(got, wantUpdate) {
t.Fatalf("expected kitty keyboard flags to be updated in place with %q, got %q", wantUpdate, got)
}
assertInOrder(t, got,
ansi.PushKittyKeyboard(keyboardEnhancementsFlags(view.KeyboardEnhancements)),
wantUpdate,
)
if strings.Contains(got, ansi.PopKittyKeyboard(1)) {
t.Fatalf("expected kitty keyboard protocol not to be popped with %q, got %q", ansi.PopKittyKeyboard(1), got)
}
if n := strings.Count(got, ansi.PushKittyKeyboard(0)); n > 1 {
t.Fatalf("expected kitty keyboard protocol to be pushed once, got %d pushes in %q", n, got)
}
}

1
tea.go
View file

@ -1073,6 +1073,7 @@ func (p *Program) Run() (returnModel Model, returnErr error) {
p.height,
)
r.setLogger(p.logger)
r.setNoInput(p.disableInput)
// XXX: This breaks many things especially when we want the output
// to be compatible with terminals that are not necessary a TTY.
// This was originally done to work around a Wish emulated-pty

View file

@ -1 +1 @@
[?25l[?2004h[>4;2m[=1;1u success[>4m[=0;1u [?25h[?2004l[?2026$p[?2027$p]10;?]11;?]12;?
[?25l[?2004h[>4;2m[>1u success[>4m[<1u [?25h[?2004l[?2026$p[?2027$p]10;?]11;?]12;?

View file

@ -1 +1 @@
[?25l [?2004h[>4;2m[=1;1usuccess[>4m[=0;1u [?25h[?2004l[?2026$p[?2027$p
[?25l [?2004h[>4;2m[>1usuccess[>4m[<1u [?25h[?2004l[?2026$p[?2027$p

View file

@ -1 +1 @@
[?25l[?2004h[>4;2m[=1;1u success[>4m[=0;1u [?25h[?2004l[?2026$p[?2027$p]52;c;?]52;c;c3VjY2Vzcw==
[?25l[?2004h[>4;2m[>1u success[>4m[<1u [?25h[?2004l[?2026$p[?2027$p]52;c;?]52;c;c3VjY2Vzcw==

View file

@ -1 +1 @@
[?25l[?2004h[>4;2m[=1;1u success[>4m[=0;1u [?25h[?2004l[?2026$p[?2027$p
[?25l[?2004h[>4;2m[>1u success[>4m[<1u [?25h[?2004l[?2026$p[?2027$p

View file

@ -1 +1 @@
[>4m[=0;1u[?1049h[?25l[?2004h[>4;2m[=1;1usuccess[>4m[=0;1u[?1049l[?25h[?2004l[?2026$p[?2027$p
[>4m[?1049h[?25l[?2004h[>4;2m[>1usuccess[>4m[<1u[?1049l[?25h[?2004l[?2026$p[?2027$p

View file

@ -1 +1 @@
[?25l[?2004h[>4;2m[=1;1u]11;#ffffff success[>4m[=0;1u [?25h[?2004l]111[?2026$p[?2027$p
[?25l[?2004h[>4;2m[>1u]11;#ffffff success[>4m[<1u [?25h[?2004l]111[?2026$p[?2027$p

View file

@ -1 +1 @@
[?25l[?2004h[>4;2m[=1;1u success[>4m[=0;1u [?25h[?2004l[?2026$p[?2027$p
[?25l[?2004h[>4;2m[>1u success[>4m[<1u [?25h[?2004l[?2026$p[?2027$p

View file

@ -1 +1 @@
[?25l[?2004h[>4;2m[=1;1u success[>4m[=0;1u [?25h[?2004l[?2026$p[?2027$p
[?25l[?2004h[>4;2m[>1u success[>4m[<1u [?25h[?2004l[?2026$p[?2027$p

View file

@ -1 +1 @@
[?2004h[>4;2m[=1;1u[1 q success [?25h[>4m[=0;1u[?2004l[?2026$p[?2027$p
[?2004h[>4;2m[>1u[1 q success [?25h[>4m[<1u[?2004l[?2026$p[?2027$p

View file

@ -1 +1 @@
[?25l[?2004h[>4;2m[=3;1u success[>4m[=0;1u [?25h[?2004l[?2026$p[?2027$p
[?25l[?2004h[>4;2m[>3u success[>4m[<1u [?25h[?2004l[?2026$p[?2027$p

View file

@ -1 +1 @@
[?25l[?2004h[?1003h[?1006h[>4;2m[=1;1u success[>4m[=0;1u [?25h[?2004l[?1002l[?1003l[?1006l[?2026$p[?2027$p
[?25l[?2004h[?1003h[?1006h[>4;2m[>1u success[>4m[<1u [?25h[?2004l[?1002l[?1003l[?1006l[?2026$p[?2027$p

View file

@ -1 +1 @@
[?25l[?2004h[?1002h[?1006h[>4;2m[=1;1u success[>4m[=0;1u [?25h[?2004l[?1002l[?1003l[?1006l[?2026$p[?2027$p
[?25l[?2004h[?1002h[?1006h[>4;2m[>1u success[>4m[<1u [?25h[?2004l[?1002l[?1003l[?1006l[?2026$p[?2027$p

View file

@ -1 +1 @@
[?25l[?2004h[>4;2m[=1;1u success[>4m[=0;1u [?25h[?2004l[?2026$p[?2027$p
[?25l[?2004h[>4;2m[>1u success[>4m[<1u [?25h[?2004l[?2026$p[?2027$p