MCPcopy Create free account
hub / github.com/charmbracelet/bubbletea / drainQueryReplies

Method drainQueryReplies

tty.go:178–231  ·  view source on GitHub ↗

drainQueryReplies reads the replies to terminal queries that may still be in flight after the input reader has stopped, and returns them. Otherwise they stay in the tty input queue for the next reader: a process started with [ExecProcess], or the shell once the program exits (#1590). It sends a Pri

(ctx context.Context)

Source from the content-addressed store, hash-verified

176// every earlier reply has been read. Nothing is drained when the last query
177// was sent long enough ago for its reply to have been read already.
178func (p *Program) drainQueryReplies(ctx context.Context) []Msg {
179 last := p.lastQuery.Swap(0)
180 if last == 0 || time.Since(time.Unix(0, last)) > queryReplyWindow ||
181 p.ttyInput == nil || p.ttyOutput == nil || p.input == nil {
182 return nil
183 }
184
185 // Make sure the pending queries themselves have been written, followed by
186 // the DA1 request that marks the end of their replies.
187 p.mu.Lock()
188 _, _ = p.outputBuf.WriteString(ansi.RequestPrimaryDeviceAttributes)
189 p.mu.Unlock()
190 if err := p.flush(); err != nil {
191 p.keepWriteErr(err)
192 return nil
193 }
194
195 cr, err := uv.NewCancelReader(p.input)
196 if err != nil {
197 return nil
198 }
199 defer cr.Close() //nolint:errcheck
200
201 // Stop reading once the DA1 reply arrives, the timeout expires, or ctx is
202 // done.
203 ctx, cancel := context.WithTimeout(ctx, queryDrainTimeout)
204 defer cancel()
205 context.AfterFunc(ctx, func() { cr.Cancel() })
206
207 drv := uv.NewTerminalReader(cr, p.environ.Getenv("TERM"))
208 drv.SetLogger(p.logger)
209
210 eventc := make(chan uv.Event)
211 done := make(chan struct{})
212 go func() {
213 defer close(done)
214 _ = drv.StreamEvents(ctx, eventc)
215 }()
216
217 var events []Msg
218 for {
219 select {
220 case ev := <-eventc:
221 if _, ok := ev.(uv.PrimaryDeviceAttributesEvent); ok {
222 // Every earlier reply has been read.
223 cancel()
224 continue
225 }
226 events = append(events, ev)
227 case <-done:
228 return events
229 }
230 }
231}
232
233const (
234 defaultWidth = 80

Callers 5

shutdownMethod · 0.95
releaseTerminalMethod · 0.95
TestDrainQueryRepliesFunction · 0.80

Calls 5

flushMethod · 0.95
keepWriteErrMethod · 0.95
CloseMethod · 0.80
CancelMethod · 0.80
GetenvMethod · 0.80

Tested by 3

TestDrainQueryRepliesFunction · 0.64