fix: skip capability queries when input is disabled (#1801)

Co-authored-by: drew <me@andrinoff.com>
Signed-off-by: drew <me@andrinoff.com>
This commit is contained in:
draw me an elephant 2026-09-24 04:05:48 -04:00 committed by GitHub
parent 657aaae216
commit 8b10e22689
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 199 additions and 13 deletions

View file

@ -38,7 +38,8 @@ func SetClipboard(s string) Cmd {
type readClipboardMsg struct{}
// ReadClipboard produces a command that reads the system clipboard using OSC52.
// Note that OSC52 is not supported in all terminals.
// Note that OSC52 is not supported in all terminals. Use [WithInput] to enable
// input, since the reply cannot be read otherwise.
func ReadClipboard() Msg {
return readClipboardMsg{}
}
@ -64,7 +65,8 @@ type readPrimaryClipboardMsg struct{}
// ReadPrimaryClipboard produces a command that reads the primary clipboard
// using OSC52. Primary clipboard selection is a feature present in X11 and
// Wayland only.
// Note that OSC52 is not supported in all terminals.
// Note that OSC52 is not supported in all terminals. Use [WithInput] to enable
// input, since the reply cannot be read otherwise.
func ReadPrimaryClipboard() Msg {
return readPrimaryClipboardMsg{}
}

View file

@ -10,6 +10,7 @@ import (
type backgroundColorMsg struct{}
// RequestBackgroundColor is a command that requests the terminal background color.
// Use [WithInput] to enable input, since the reply cannot be read otherwise.
func RequestBackgroundColor() Msg {
return backgroundColorMsg{}
}
@ -18,6 +19,7 @@ func RequestBackgroundColor() Msg {
type foregroundColorMsg struct{}
// RequestForegroundColor is a command that requests the terminal foreground color.
// Use [WithInput] to enable input, since the reply cannot be read otherwise.
func RequestForegroundColor() Msg {
return foregroundColorMsg{}
}
@ -26,6 +28,7 @@ func RequestForegroundColor() Msg {
type cursorColorMsg struct{}
// RequestCursorColor is a command that requests the terminal cursor color.
// Use [WithInput] to enable input, since the reply cannot be read otherwise.
func RequestCursorColor() Msg {
return cursorColorMsg{}
}

View file

@ -23,6 +23,7 @@ type requestCursorPosMsg struct{}
// RequestCursorPosition is a command that requests the cursor position.
// The cursor position will be sent as a [CursorPositionMsg] message.
// Use [WithInput] to enable input, since the reply cannot be read otherwise.
func RequestCursorPosition() Msg {
return requestCursorPosMsg{}
}

View file

@ -37,6 +37,13 @@ func WithOutput(output io.Writer) ProgramOption {
// won't need to use this. To disable input entirely pass nil.
//
// p := NewProgram(model, WithInput(nil))
//
// Note that with input disabled, no terminal query is ever sent, since the
// reply could not be read: commands that expect a response, such as
// [RequestBackgroundColor], [RequestCursorPosition], [ReadClipboard], or
// [RequestTerminalVersion], are skipped, as is the startup capability probe.
// A model waiting on the reply message of any of those commands will never
// receive it.
func WithInput(input io.Reader) ProgramOption {
return func(p *Program) {
p.input = input

34
tea.go
View file

@ -816,35 +816,35 @@ func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {
}
case readClipboardMsg:
p.execute(ansi.RequestSystemClipboard)
p.executeQuery(ansi.RequestSystemClipboard)
case setClipboardMsg:
p.execute(ansi.SetSystemClipboard(string(msg)))
case readPrimaryClipboardMsg:
p.execute(ansi.RequestPrimaryClipboard)
p.executeQuery(ansi.RequestPrimaryClipboard)
case setPrimaryClipboardMsg:
p.execute(ansi.SetPrimaryClipboard(string(msg)))
case backgroundColorMsg:
p.execute(ansi.RequestBackgroundColor)
p.executeQuery(ansi.RequestBackgroundColor)
case foregroundColorMsg:
p.execute(ansi.RequestForegroundColor)
p.executeQuery(ansi.RequestForegroundColor)
case cursorColorMsg:
p.execute(ansi.RequestCursorColor)
p.executeQuery(ansi.RequestCursorColor)
case execMsg:
// NB: this blocks.
p.exec(msg.cmd, msg.fn)
case terminalVersion:
p.execute(ansi.RequestNameVersion)
p.executeQuery(ansi.RequestNameVersion)
case requestCapabilityMsg:
p.execute(ansi.RequestTermcap(string(msg)))
p.executeQuery(ansi.RequestTermcap(string(msg)))
case BatchMsg:
go p.execBatchMsg(msg)
@ -861,7 +861,7 @@ func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {
go p.checkResize()
case requestCursorPosMsg:
p.execute(ansi.RequestCursorPositionReport)
p.executeQuery(ansi.RequestCursorPositionReport)
case RawMsg:
p.execute(fmt.Sprint(msg.Msg))
@ -1119,7 +1119,7 @@ func (p *Program) Run() (returnModel Model, returnErr error) {
// Query for synchronized updates support (mode 2026) and unicode core
// (mode 2027). If the terminal supports it, the renderer will enable
// it once we get the response.
p.execute(ansi.RequestModeSynchronizedOutput +
p.executeQuery(ansi.RequestModeSynchronizedOutput +
ansi.RequestModeUnicodeCore)
}
@ -1226,6 +1226,22 @@ func (p *Program) execute(seq string) {
p.mu.Unlock()
}
// executeQuery writes a terminal query to the program output. Queries expect a
// reply on p.input, so when input is disabled the query is skipped: the
// program cannot read the response, and the terminal's reply would leak into
// the shell once the program exits (#1590).
//
// This covers every query that expects a reply, not just the startup
// capability probe: background, foreground, and cursor color requests, cursor
// position reports, clipboard reads, and terminal version and termcap
// queries.
func (p *Program) executeQuery(seq string) {
if p.disableInput {
return
}
p.execute(seq)
}
// flush flushes the output buffer to the program output.
func (p *Program) flush() error {
p.mu.Lock()

View file

@ -11,6 +11,8 @@ import (
"sync/atomic"
"testing"
"time"
"github.com/charmbracelet/x/ansi"
)
type ctxImplodeMsg struct {
@ -670,6 +672,159 @@ func BenchmarkTeaRun(b *testing.B) {
}
}
// quitModel quits as soon as it starts.
type quitModel struct{}
func (quitModel) Init() Cmd { return Quit }
func (quitModel) Update(Msg) (Model, Cmd) { return quitModel{}, nil }
func (quitModel) View() View { return NewView("") }
// TestTeaNoCapabilityQueryWithoutInput is a regression test for
// https://github.com/charmbracelet/gum/issues/1118: programs without input
// can't read the terminal's responses to capability queries, so the replies
// leak into the shell after the program exits. Don't send the queries when
// input is disabled.
func TestTeaNoCapabilityQueryWithoutInput(t *testing.T) {
t.Parallel()
query := ansi.RequestModeSynchronizedOutput + ansi.RequestModeUnicodeCore
env := []string{"TERM=xterm-256color", "TERM_PROGRAM=ghostty"}
for _, tt := range []struct {
name string
input io.Reader
want bool
}{
{name: "input disabled", input: nil, want: false},
{name: "input enabled", input: bytes.NewReader(nil), want: true},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
var buf bytes.Buffer
p := NewProgram(quitModel{},
WithInput(tt.input),
WithOutput(&buf),
WithEnvironment(env),
)
if _, err := p.Run(); err != nil {
t.Fatal(err)
}
// The queued output may not have been flushed if the program
// exited before the first tick, so inspect it too. Reading
// p.outputBuf here is deliberate: it checks the buffered bytes
// that would have been flushed, without depending on flush
// timing (and it ties the test to the renderer's buffer, which
// is an intentional trade-off).
got := buf.String() + p.outputBuf.String()
if strings.Contains(got, query) != tt.want {
t.Fatalf("capability query present = %v, want %v; output: %q", !tt.want, tt.want, got)
}
})
}
}
// terminalQueryCmds lists every command that sends a terminal query whose
// reply must be read from the input reader.
var terminalQueryCmds = []Cmd{
RequestBackgroundColor,
RequestForegroundColor,
RequestCursorColor,
ReadClipboard,
ReadPrimaryClipboard,
RequestTerminalVersion,
RequestCapability("TN"),
RequestCursorPosition,
}
// queryModel issues every terminal query that needs a reply on the input
// reader, then quits once each one has been handled.
type queryModel struct {
handled int
}
func (queryModel) Init() Cmd {
return Batch(terminalQueryCmds...)
}
func (m queryModel) Update(msg Msg) (Model, Cmd) {
switch msg.(type) {
case backgroundColorMsg, foregroundColorMsg, cursorColorMsg,
readClipboardMsg, readPrimaryClipboardMsg, terminalVersion,
requestCapabilityMsg, requestCursorPosMsg:
// Each query is handled by an intermediate reader that turns the
// terminal's reply into a message, so Update only sees the request
// messages because the event loop passes them through after the
// intermediate reads. If that pass-through ever changes, this test
// will hang instead of quitting.
m.handled++
if m.handled == len(terminalQueryCmds) {
return m, Quit
}
}
return m, nil
}
func (queryModel) View() View { return NewView("") }
// TestTeaNoTerminalQueriesWithoutInput is a regression test for
// https://github.com/charmbracelet/gum/issues/1118: programs without input
// can't read the terminal's responses, so query replies leak into the shell
// after the program exits. No input-dependent query should be sent when input
// is disabled.
func TestTeaNoTerminalQueriesWithoutInput(t *testing.T) {
t.Parallel()
queries := []string{
ansi.RequestSystemClipboard,
ansi.RequestPrimaryClipboard,
ansi.RequestBackgroundColor,
ansi.RequestForegroundColor,
ansi.RequestCursorColor,
ansi.RequestNameVersion,
ansi.RequestTermcap("TN"),
ansi.RequestCursorPositionReport,
}
env := []string{"TERM=xterm-256color", "TERM_PROGRAM=ghostty"}
for _, tt := range []struct {
name string
input io.Reader
want bool
}{
{name: "input disabled", input: nil, want: false},
{name: "input enabled", input: bytes.NewReader(nil), want: true},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
var buf bytes.Buffer
p := NewProgram(queryModel{},
WithInput(tt.input),
WithOutput(&buf),
WithEnvironment(env),
)
if _, err := p.Run(); err != nil {
t.Fatal(err)
}
// The queued output may not have been flushed if the program
// exited before the first tick, so inspect it too. Reading
// p.outputBuf here is deliberate: it checks the buffered bytes
// that would have been flushed, without depending on flush
// timing (and it ties the test to the renderer's buffer, which
// is an intentional trade-off).
got := buf.String() + p.outputBuf.String()
for _, query := range queries {
if strings.Contains(got, query) != tt.want {
t.Errorf("query %q present = %v, want %v; output: %q", query, !tt.want, tt.want, got)
}
}
})
}
}
// TestProgressBarStateStringOutOfRange is a regression test for
// https://github.com/charmbracelet/bubbletea/issues/1711: String panicked
// with an index-out-of-range error for any ProgressBarState outside the

View file

@ -5,7 +5,8 @@ package tea
type requestCapabilityMsg string
// RequestCapability is a command that requests the terminal to send its
// Termcap/Terminfo response for the given capability.
// Termcap/Terminfo response for the given capability. Use [WithInput] to
// enable input, since the reply cannot be read otherwise.
//
// Bubble Tea recognizes the following capabilities and will use them to
// upgrade the program's color profile:

View file

@ -16,7 +16,8 @@ type terminalVersion struct{}
// RequestTerminalVersion is a command that queries the terminal for its
// version using XTVERSION. Note that some terminals may not support this
// command.
// command. Use [WithInput] to enable input, since the reply cannot be read
// otherwise.
func RequestTerminalVersion() Msg {
return terminalVersion{}
}