fix: skip capability queries when input is disabled (#1801)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by draw me an elephant · committed by GitHub · parent 657aaae · Browse files · 8 files·+199 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: drew <me@andrinoff.com>
- Signed-off-by: drew <me@andrinoff.com>
Diff stats
8 files+199 added−13 removed
- other:+199 added−13 removed
Provenance
- Commit
8b10e22- Tree
30c297a- Author
draw me an elephant <68925779+drawmeanelephant@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
657aaae
8 files changed+199 added−13 removed
modified:clipboard.go+4 added-2 removed
36 unmodified lines37 // using OSC52.38 type readClipboardMsg struct{}39 40 // ReadClipboard produces a command that reads the system clipboard using OSC52.41-// Note that OSC52 is not supported in all terminals.41+// Note that OSC52 is not supported in all terminals. Use [WithInput] to enable42+// input, since the reply cannot be read otherwise.43 func ReadClipboard() Msg {44 return readClipboardMsg{}45 }46 17 unmodified lines64 65 // ReadPrimaryClipboard produces a command that reads the primary clipboard66 // using OSC52. Primary clipboard selection is a feature present in X11 and67 // Wayland only.67-// Note that OSC52 is not supported in all terminals.68+// Note that OSC52 is not supported in all terminals. Use [WithInput] to enable69+// input, since the reply cannot be read otherwise.70 func ReadPrimaryClipboard() Msg {71 return readPrimaryClipboardMsg{}72 }modified:color.go+3 added
8 unmodified lines9 // backgroundColorMsg is a message that requests the terminal background color.10 type backgroundColorMsg struct{}11 12 // RequestBackgroundColor is a command that requests the terminal background color.13+// Use [WithInput] to enable input, since the reply cannot be read otherwise.14 func RequestBackgroundColor() Msg {15 return backgroundColorMsg{}16 }17 18 // foregroundColorMsg is a message that requests the terminal foreground color.19 type foregroundColorMsg struct{}20 21 // RequestForegroundColor is a command that requests the terminal foreground color.22+// Use [WithInput] to enable input, since the reply cannot be read otherwise.23 func RequestForegroundColor() Msg {24 return foregroundColorMsg{}25 }26 27 // cursorColorMsg is a message that requests the terminal cursor color.28 type cursorColorMsg struct{}29 30 // RequestCursorColor is a command that requests the terminal cursor color.31+// Use [WithInput] to enable input, since the reply cannot be read otherwise.32 func RequestCursorColor() Msg {33 return cursorColorMsg{}34 }35 59 unmodified linesmodified:cursor.go+1 added
21 unmodified lines22 type requestCursorPosMsg struct{}23 24 // RequestCursorPosition is a command that requests the cursor position.25 // The cursor position will be sent as a [CursorPositionMsg] message.26+// Use [WithInput] to enable input, since the reply cannot be read otherwise.27 func RequestCursorPosition() Msg {28 return requestCursorPosMsg{}29 }modified:options.go+7 added
35 unmodified lines36 // WithInput sets the input which, by default, is stdin. In most cases you37 // won't need to use this. To disable input entirely pass nil.38 //39 // p := NewProgram(model, WithInput(nil))40+//41+// Note that with input disabled, no terminal query is ever sent, since the42+// reply could not be read: commands that expect a response, such as43+// [RequestBackgroundColor], [RequestCursorPosition], [ReadClipboard], or44+// [RequestTerminalVersion], are skipped, as is the startup capability probe.45+// A model waiting on the reply message of any of those commands will never46+// receive it.47 func WithInput(input io.Reader) ProgramOption {48 return func(p *Program) {49 p.input = input50 p.disableInput = input == nil125 unmodified linesmodified:tea_test.go+155 added
9 unmodified lines10 "sync"11 "sync/atomic"12 "testing"13 "time"14+15+ "github.com/charmbracelet/x/ansi"16 )17 18 type ctxImplodeMsg struct {19 cancel context.CancelFunc651 unmodified lines671 _ = r.CloseWithError(io.EOF)672 }673 }674 675+// quitModel quits as soon as it starts.676+type quitModel struct{}677+678+func (quitModel) Init() Cmd { return Quit }679+func (quitModel) Update(Msg) (Model, Cmd) { return quitModel{}, nil }680+func (quitModel) View() View { return NewView("") }681+682+// TestTeaNoCapabilityQueryWithoutInput is a regression test for683+// https://github.com/charmbracelet/gum/issues/1118: programs without input684+// can't read the terminal's responses to capability queries, so the replies685+// leak into the shell after the program exits. Don't send the queries when686+// input is disabled.687+func TestTeaNoCapabilityQueryWithoutInput(t *testing.T) {688+ t.Parallel()689+690+ query := ansi.RequestModeSynchronizedOutput + ansi.RequestModeUnicodeCore691+ env := []string{"TERM=xterm-256color", "TERM_PROGRAM=ghostty"}692+693+ for _, tt := range []struct {694+ name string695+ input io.Reader696+ want bool697+ }{698+ {name: "input disabled", input: nil, want: false},699+ {name: "input enabled", input: bytes.NewReader(nil), want: true},700+ } {701+ t.Run(tt.name, func(t *testing.T) {702+ t.Parallel()703+704+ var buf bytes.Buffer705+ p := NewProgram(quitModel{},706+ WithInput(tt.input),707+ WithOutput(&buf),708+ WithEnvironment(env),709+ )710+ if _, err := p.Run(); err != nil {711+ t.Fatal(err)712+ }713+714+ // The queued output may not have been flushed if the program715+ // exited before the first tick, so inspect it too. Reading716+ // p.outputBuf here is deliberate: it checks the buffered bytes717+ // that would have been flushed, without depending on flush718+ // timing (and it ties the test to the renderer's buffer, which719+ // is an intentional trade-off).720+ got := buf.String() + p.outputBuf.String()721+ if strings.Contains(got, query) != tt.want {722+ t.Fatalf("capability query present = %v, want %v; output: %q", !tt.want, tt.want, got)723+ }724+ })725+ }726+}727+728+// terminalQueryCmds lists every command that sends a terminal query whose729+// reply must be read from the input reader.730+var terminalQueryCmds = []Cmd{731+ RequestBackgroundColor,732+ RequestForegroundColor,733+ RequestCursorColor,734+ ReadClipboard,735+ ReadPrimaryClipboard,736+ RequestTerminalVersion,737+ RequestCapability("TN"),738+ RequestCursorPosition,739+}740+741+// queryModel issues every terminal query that needs a reply on the input742+// reader, then quits once each one has been handled.743+type queryModel struct {744+ handled int745+}746+747+func (queryModel) Init() Cmd {748+ return Batch(terminalQueryCmds...)749+}750+751+func (m queryModel) Update(msg Msg) (Model, Cmd) {752+ switch msg.(type) {753+ case backgroundColorMsg, foregroundColorMsg, cursorColorMsg,754+ readClipboardMsg, readPrimaryClipboardMsg, terminalVersion,755+ requestCapabilityMsg, requestCursorPosMsg:756+ // Each query is handled by an intermediate reader that turns the757+ // terminal's reply into a message, so Update only sees the request758+ // messages because the event loop passes them through after the759+ // intermediate reads. If that pass-through ever changes, this test760+ // will hang instead of quitting.761+ m.handled++762+ if m.handled == len(terminalQueryCmds) {763+ return m, Quit764+ }765+ }766+ return m, nil767+}768+769+func (queryModel) View() View { return NewView("") }770+771+// TestTeaNoTerminalQueriesWithoutInput is a regression test for772+// https://github.com/charmbracelet/gum/issues/1118: programs without input773+// can't read the terminal's responses, so query replies leak into the shell774+// after the program exits. No input-dependent query should be sent when input775+// is disabled.776+func TestTeaNoTerminalQueriesWithoutInput(t *testing.T) {777+ t.Parallel()778+779+ queries := []string{780+ ansi.RequestSystemClipboard,781+ ansi.RequestPrimaryClipboard,782+ ansi.RequestBackgroundColor,783+ ansi.RequestForegroundColor,784+ ansi.RequestCursorColor,785+ ansi.RequestNameVersion,786+ ansi.RequestTermcap("TN"),787+ ansi.RequestCursorPositionReport,788+ }789+ env := []string{"TERM=xterm-256color", "TERM_PROGRAM=ghostty"}790+791+ for _, tt := range []struct {792+ name string793+ input io.Reader794+ want bool795+ }{796+ {name: "input disabled", input: nil, want: false},797+ {name: "input enabled", input: bytes.NewReader(nil), want: true},798+ } {799+ t.Run(tt.name, func(t *testing.T) {800+ t.Parallel()801+802+ var buf bytes.Buffer803+ p := NewProgram(queryModel{},804+ WithInput(tt.input),805+ WithOutput(&buf),806+ WithEnvironment(env),807+ )808+ if _, err := p.Run(); err != nil {809+ t.Fatal(err)810+ }811+812+ // The queued output may not have been flushed if the program813+ // exited before the first tick, so inspect it too. Reading814+ // p.outputBuf here is deliberate: it checks the buffered bytes815+ // that would have been flushed, without depending on flush816+ // timing (and it ties the test to the renderer's buffer, which817+ // is an intentional trade-off).818+ got := buf.String() + p.outputBuf.String()819+ for _, query := range queries {820+ if strings.Contains(got, query) != tt.want {821+ t.Errorf("query %q present = %v, want %v; output: %q", query, !tt.want, tt.want, got)822+ }823+ }824+ })825+ }826+}827+828 // TestProgressBarStateStringOutOfRange is a regression test for829 // https://github.com/charmbracelet/bubbletea/issues/1711: String panicked830 // with an index-out-of-range error for any ProgressBarState outside the831 // [ProgressBarNone, ProgressBarWarning] range. Since State is an exported15 unmodified linesmodified:tea.go+25 added-9 removed
814 unmodified lines815 }816 }817 818 case readClipboardMsg:819- p.execute(ansi.RequestSystemClipboard)819+ p.executeQuery(ansi.RequestSystemClipboard)820 821 case setClipboardMsg:822 p.execute(ansi.SetSystemClipboard(string(msg)))823 824 case readPrimaryClipboardMsg:825- p.execute(ansi.RequestPrimaryClipboard)825+ p.executeQuery(ansi.RequestPrimaryClipboard)826 827 case setPrimaryClipboardMsg:828 p.execute(ansi.SetPrimaryClipboard(string(msg)))829 830 case backgroundColorMsg:831- p.execute(ansi.RequestBackgroundColor)831+ p.executeQuery(ansi.RequestBackgroundColor)832 833 case foregroundColorMsg:834- p.execute(ansi.RequestForegroundColor)834+ p.executeQuery(ansi.RequestForegroundColor)835 836 case cursorColorMsg:837- p.execute(ansi.RequestCursorColor)837+ p.executeQuery(ansi.RequestCursorColor)838 839 case execMsg:840 // NB: this blocks.841 p.exec(msg.cmd, msg.fn)842 843 case terminalVersion:844- p.execute(ansi.RequestNameVersion)844+ p.executeQuery(ansi.RequestNameVersion)845 846 case requestCapabilityMsg:847- p.execute(ansi.RequestTermcap(string(msg)))847+ p.executeQuery(ansi.RequestTermcap(string(msg)))848 849 case BatchMsg:850 go p.execBatchMsg(msg)851 continue8 unmodified lines860 case windowSizeMsg:861 go p.checkResize()862 863 case requestCursorPosMsg:864- p.execute(ansi.RequestCursorPositionReport)864+ p.executeQuery(ansi.RequestCursorPositionReport)865 866 case RawMsg:867 p.execute(fmt.Sprint(msg.Msg))868 249 unmodified lines1118 if !p.disableRenderer && shouldQuerySynchronizedOutput(p.environ) {1119 // Query for synchronized updates support (mode 2026) and unicode core1120 // (mode 2027). If the terminal supports it, the renderer will enable1121 // it once we get the response.1122- p.execute(ansi.RequestModeSynchronizedOutput +1122+ p.executeQuery(ansi.RequestModeSynchronizedOutput +1123 ansi.RequestModeUnicodeCore)1124 }1125 1126 // Initialize the program.98 unmodified lines1225 _, _ = p.outputBuf.WriteString(seq)1226 p.mu.Unlock()1227 }1228 1229+// executeQuery writes a terminal query to the program output. Queries expect a1230+// reply on p.input, so when input is disabled the query is skipped: the1231+// program cannot read the response, and the terminal's reply would leak into1232+// the shell once the program exits (#1590).1233+//1234+// This covers every query that expects a reply, not just the startup1235+// capability probe: background, foreground, and cursor color requests, cursor1236+// position reports, clipboard reads, and terminal version and termcap1237+// queries.1238+func (p *Program) executeQuery(seq string) {1239+ if p.disableInput {1240+ return1241+ }1242+ p.execute(seq)1243+}1244+1245 // flush flushes the output buffer to the program output.1246 func (p *Program) flush() error {1247 p.mu.Lock()1248 defer p.mu.Unlock()216 unmodified linesmodified:termcap.go+2 added-1 removed
3 unmodified lines4 // send its Termcap/Terminfo response.5 type requestCapabilityMsg string6 7 // RequestCapability is a command that requests the terminal to send its8-// Termcap/Terminfo response for the given capability.8+// Termcap/Terminfo response for the given capability. Use [WithInput] to9+// enable input, since the reply cannot be read otherwise.10 //11 // Bubble Tea recognizes the following capabilities and will use them to12 // upgrade the program's color profile:13 // - "RGB" Xterm direct color36 unmodified linesmodified:xterm.go+2 added-1 removed
14 unmodified lines15 type terminalVersion struct{}16 17 // RequestTerminalVersion is a command that queries the terminal for its18 // version using XTVERSION. Note that some terminals may not support this19-// command.19+// command. Use [WithInput] to enable input, since the reply cannot be read20+// otherwise.21 func RequestTerminalVersion() Msg {22 return terminalVersion{}23 }