Files
donlucasandClaude Fable 5.1 9711a9f7b4 The agent's erase-displays are counted into the event log
The filter counts every erase it confined to the band or dropped; the
host reads the count and the scape writes it on the event log's stats line
beside the bus's dropped and bad counts, whenever any of them changes. The
next blank row is attributed to a clear from the log instead of inferred
from a screenshot (his ruling, 2026-09-18).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-18 13:22:32 -07:00

782 lines
27 KiB
Go

package host
import (
"errors"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/donlucasx/xscapes/internal/envx"
"github.com/donlucasx/xscapes/internal/event"
)
// Host runs an agent inside the top rows of this terminal and paints the scape
// in the rows below it.
//
// It is not a terminal emulator. The agent's bytes go to the real terminal
// untouched but for one three-byte sequence (see Filter), which is what makes
// this safe: nothing the host fails to understand about Claude Code's output
// can be corrupted by it. What holds the two apart is the scroll region --
// the agent is told its window is band-sized, and DECSTBM stops it scrolling
// past the bottom of that band.
//
// Everything it relies on was measured rather than assumed; see
// notes/claude-terminal-emissions.md.
type Host struct {
// Cmd is the agent. Its stdio is replaced with the pty.
Cmd *exec.Cmd
// filter is the agent's output filter once Run has made it; AgentErases
// reads its count.
filter *Filter
// Size reports the real terminal's size. Injected rather than measured
// here so there is one TIOCGWINSZ in the project, not two.
Size func() (cols, rows int)
// Paint returns the scape's rows: exactly rows strings, each at most cols
// wide. Nil, or a nil return, paints nothing.
Paint func(cols, rows int) []string
// FPS is how often the scape repaints. The agent's output is never held
// up by it; it goes out the moment it arrives.
FPS float64
// ScapeRows fixes the scape's height. Zero takes the automatic split.
ScapeRows int
// AltScreen runs on the alternate screen, which has no history for the
// terminal to pull back in when the window grows. See Open.
AltScreen bool
// History mirrors every row that leaves the agent's band into the main
// buffer, where the terminal keeps its scrollback. See MirrorBatch. It
// needs the alternate screen: on the main screen the terminal keeps that
// history itself.
History bool
// Replay prints the mirrored rows once more after the alternate screen is
// given back. Terminal.app discards most of what scrolled into the main
// buffer while the alternate screen was up (4 of 30 rows survived,
// notes/mirrorprobe), so without this the transcript is gone the moment
// the session ends. An xterm-like terminal keeps it, and a replay there
// would duplicate every line; the launcher gates this on TERM_PROGRAM.
Replay bool
// Rules is what this terminal does to the alternate screen on a resize.
// The launcher picks them by TERM_PROGRAM (RulesFor); the zero value is
// the xterm-like set.
Rules Rules
// OnOutput sees every chunk the agent writes to its pty, and OnInput every
// chunk the user types, before either is forwarded. Both are optional and
// both are called from the host's own read goroutines, so a receiver
// locks. They exist for the generic adapter (internal/watch), which is
// how a program with no hooks still drives the scape.
OnOutput func(b []byte)
OnInput func(b []byte)
// model is the host's own copy of the screen when History is on: every
// byte sent to the terminal is fed through it, so the rows that leave the
// band -- by scrolling, or destroyed by a shrink -- are known, cells and
// rendition. Guarded by mu.
model *screen
// mirrored is what has been written to the main buffer so far, for Replay.
mirrored []string
// mainRow is where the next mirrored row goes in the main buffer.
mainRow int
// wantCPR is set while the host is waiting for the terminal to answer
// where the shell's cursor is; the key forwarder keeps that reply.
wantCPR atomic.Bool
// muted stops every write once the screen has been handed back and the
// replay printed: a forwarder that outlived its deadline (a grandchild
// holding the pty open) must not write into the shell's screen.
muted atomic.Bool
// trace, when XSCAPES_TRACE is set, records every byte sent to the
// terminal; traceLog records size changes against byte offsets so a replay
// can resize where the real terminal did.
trace *os.File
traceLog *os.File
traceN int64
// In and Out default to os.Stdin and os.Stdout. Overridable for tests.
In *os.File
Out *os.File
mu sync.Mutex // serialises writes to Out
out *os.File
}
// write is the only path to the terminal. Serialised, because a scape frame
// landing in the middle of a chunk of the agent's output would split an escape
// sequence in half and paint garbage into the agent's own window.
// AgentErases is how many erase-displays the agent has sent that the filter
// confined to its band or dropped, for the event log.
func (h *Host) AgentErases() int64 {
if h.filter == nil {
return 0
}
return h.filter.Erases.Load()
}
func (h *Host) write(s string) {
if s == "" || h.muted.Load() {
return
}
h.mu.Lock()
io.WriteString(h.out, s)
if h.trace != nil {
n, _ := h.trace.Write([]byte(s))
h.traceN += int64(n)
}
if h.model != nil {
h.model.feed(s)
}
h.mu.Unlock()
}
// traceSize records a window size against the byte offset it took effect at.
//
// Without it a replay has to feed the whole stream into one fixed-size screen,
// which misreconstructs everything written BEFORE the resize -- and the resize
// is the thing under investigation. The sidecar keeps the trace itself a pure
// byte stream, so it stays replayable by anything.
func (h *Host) traceSize(cols, rows, agentRows int) {
if h.trace == nil {
return
}
h.mu.Lock()
defer h.mu.Unlock()
if h.traceLog == nil {
f, err := os.OpenFile(h.trace.Name()+".log", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
if err != nil {
return
}
h.traceLog = f
}
fmt.Fprintf(h.traceLog, "%d %d %d %d\n", h.traceN, cols, rows, agentRows)
}
// openTrace tees everything the host sends the terminal into a file, when
// XSCAPES_TRACE names one.
//
// It exists because a screenshot is not evidence of what was SENT, and the
// difference between "the terminal moved it" and "we erased it" is not visible
// in a photograph. Replaying a trace through internal/host's screen model
// reconstructs the exact screen, which is the only way to argue about a
// resize that happened on someone else's machine.
//
// The agent's own bytes are in here too -- they pass through write on their
// way out -- so a trace CAN contain whatever the agent had on screen. It is a
// debugging tool that must be pointed at a file deliberately, never a default.
func (h *Host) openTrace() {
path := envx.Lookup("TRACE")
if path == "" {
return
}
// XSCAPES_TRACE=1 picks the path so there is none to get wrong.
//
// The path WAS the whole failure mode. On 2026-09-07 he started a session
// to trace the scrollback defect, the scape came up, the defect
// reproduced on screen -- and nothing was captured, because the open had
// failed and this function returned in silence. A debugging tool you point
// at a file deliberately has to say when it cannot write there.
if path == "1" || strings.EqualFold(path, "true") || strings.EqualFold(path, "yes") {
home, err := event.Home()
if err != nil {
traceOff(path, err)
return
}
path = filepath.Join(home, "traces", time.Now().Format("20060102-150405")+".bin")
}
// Make the parent, so a directory that does not exist yet cannot quietly
// turn tracing off.
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
traceOff(path, err)
return
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
if err != nil {
traceOff(path, err)
return
}
h.trace = f
// Said out loud, and before the band takes the screen, because the only
// way to know a trace is running was to go looking for the file.
fmt.Fprintf(os.Stderr, "xscapes: tracing to %s\n", path)
}
// traceOff reports that a trace was ASKED FOR and is not happening. It never
// stops the session: he asks for a trace mid-work and losing the agent over a
// bad path would be worse than losing the trace. But it is never silent again.
func traceOff(path string, err error) {
fmt.Fprintf(os.Stderr, "xscapes: XSCAPES_TRACE is set but TRACING IS OFF -- %s: %v\n", path, err)
}
func (h *Host) Run() error {
in, out := h.In, h.Out
if in == nil {
in = os.Stdin
}
if out == nil {
out = os.Stdout
}
h.out = out
h.openTrace()
if h.trace != nil {
defer h.trace.Close()
defer func() {
if h.traceLog != nil {
h.traceLog.Close()
}
}()
}
cols, rows := h.Size()
agentRows, scapeRows := BandWith(rows, h.ScapeRows)
h.traceSize(cols, rows, agentRows)
p, err := openPTY()
if err != nil {
return err
}
defer p.Close()
if err := p.SetSize(cols, agentRows); err != nil {
return fmt.Errorf("size the pty: %w", err)
}
// Raw mode, so every keystroke reaches the agent as typed -- including
// Ctrl-C, which Claude Code uses to interrupt a turn and which the host
// must not turn into a signal of its own.
saved, err := makeRaw(in.Fd())
if err != nil {
return fmt.Errorf("raw mode: %w", err)
}
if h.History && !h.AltScreen {
h.History = false // the terminal keeps the main screen's history itself
}
// One exit path, however the host ends: the child exiting, a signal, or an
// error. Once, because the signal handler and the deferred call race, and
// emitting the sequence twice repaints the shell's prompt over itself.
//
// It reads agentRows and rows as they are at the time, so a window resized
// during the session is cleared to its real size rather than its first one.
var leaving sync.Once
leave := func() {
leaving.Do(func() {
h.write(Close(h.AltScreen, agentRows, rows))
restoreTermios(in.Fd(), saved)
})
}
defer leave()
// A signal that kills the host must not leave the terminal in raw mode
// with a scroll region pinned to the top of the screen.
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGTERM, syscall.SIGHUP)
go func() {
<-sig
leave()
os.Exit(1)
}()
// Keystrokes, and the terminal's replies to the agent's startup queries
// (device attributes, the kitty keyboard protocol, synchronized output),
// which travel the same path and must arrive byte for byte. Started
// BEFORE the child, because the host has one question of its own to ask
// the terminal first and the answer arrives on this fd; the pty buffers
// anything typed meanwhile for the child.
var cpr chan int
waitDone := make(chan struct{})
if h.History {
h.mu.Lock()
// ⚠ This model deliberately does NOT take Rules.RetainsWidth, and it is
// the one line in the host that looks like an oversight and is not.
// Session 25 called it "a wiring gap and it is in the mirror path --
// the strongest lead yet" on the scrollback corruption. Wired and
// replayed against two independent windows of his own traces, it is
// the opposite of a fix: the mirror starts writing rows with a
// pre-resize fragment stitched onto the end, which is the corruption's
// own signature, and rows wider than the window, which wrap in the
// main buffer and take the row underneath. Terminal.app really does
// retain those cells; they are stale, and the mirror is a record of
// content, not a photograph of the glass. See
// TestTheMirrorDropsTheCellsTheTerminalRetains, and
// TestReplayTraceRetainDiff for the measurement.
h.model = newScreen(cols, rows)
h.model.capture = true
h.mu.Unlock()
cpr = make(chan int, 1)
h.wantCPR.Store(true)
}
go h.forwardKeys(in, p.master, cpr, waitDone)
// Where did the shell leave its cursor? That is where the mirrored
// transcript begins, right under the command he typed, with no blank
// gap. Asked with DSR before the child exists (Kimi F3): once Claude Code
// is up it asks the terminal questions of its own, and a reply meant for
// it must never be taken for this one. Without an answer the transcript
// starts at the bottom, which only costs the gap.
h.mainRow = rows
if h.History {
h.write("\x1b[6n")
select {
case r := <-cpr:
if r >= 1 && r <= rows {
h.mainRow = r
}
case <-time.After(300 * time.Millisecond):
}
h.wantCPR.Store(false)
}
// Either way the wait is over: anything typed during it goes to the agent
// now, not when the next key happens to arrive.
close(waitDone)
h.Cmd.Stdin, h.Cmd.Stdout, h.Cmd.Stderr = p.slave, p.slave, p.slave
if h.Cmd.SysProcAttr == nil {
h.Cmd.SysProcAttr = &syscall.SysProcAttr{}
}
h.Cmd.SysProcAttr.Setsid = true
h.Cmd.SysProcAttr.Setctty = true
if err := h.Cmd.Start(); err != nil {
return err
}
// The child owns the slave now. Holding it open here would hide the EOF
// when the child exits, and the output loop would never finish.
p.slave.Close()
p.slave = nil
// Take the screen and pin the band. On the main screen that means clearing
// first, because Claude Code never clears the display itself -- measured,
// it emits no ED at all -- so it would print over whatever was already
// there.
h.write(Open(h.AltScreen, agentRows, rows))
// Only what moved gets sent. See damage.
var dmg damage
// The agent's output, filtered and forwarded. Never buffered by the frame
// loop: a keystroke echoes at the speed the agent produces it. fwdDone
// closes when the pty runs dry, which is how the exit path knows the
// agent's last bytes are out before anything is printed after them.
fwdDone := make(chan struct{})
f := &Filter{}
f.Band.Store(int32(agentRows))
h.filter = f
go func() {
defer close(fwdDone)
buf := make([]byte, 8192)
for {
n, err := p.master.Read(buf)
if n > 0 {
if h.OnOutput != nil {
h.OnOutput(buf[:n])
}
h.write(string(f.Filter(buf[:n])))
}
if err != nil {
h.write(string(f.Flush()))
return
}
}
}()
done := make(chan error, 1)
go func() { done <- h.Cmd.Wait() }()
fps := h.FPS
if fps < 1 {
fps = 1
}
if fps > 120 {
fps = 120
}
tick := time.NewTicker(time.Duration(float64(time.Second) / fps))
defer tick.Stop()
for {
select {
case err := <-done:
if h.History && h.Replay {
// The forwarder is not joined anywhere else, and the agent's
// final bytes can still be in flight when the child's exit is
// seen (Kimi F4). Let them land before the screen is handed
// back, or they interleave with the replay.
select {
case <-fwdDone:
case <-time.After(500 * time.Millisecond):
}
// The rows that scrolled since the last tick, then the band
// as it stands: the answer he quit to read, and the same UI a
// plain session leaves on the screen when it ends.
h.mirror(rows, agentRows)
h.keepFinalScreen(agentRows)
}
leave()
if h.History && h.Replay {
h.write(h.replay())
// Nothing may write after this: a forwarder that outlived
// its deadline would land in the shell's screen.
h.muted.Store(true)
}
var ee *exec.ExitError
if errors.As(err, &ee) {
return nil // the agent exiting is not the host failing
}
return err
case <-tick.C:
nc, nr := h.Size()
if nc != cols || nr != rows {
oldAgent, oldRows, oldCols := agentRows, rows, cols
cols, rows = nc, nr
agentRows, scapeRows = BandWith(rows, h.ScapeRows)
// The terminal has already moved the rows; the model follows
// it, and on a shrink keeps the rows the terminal destroyed
// so they can still be mirrored.
h.mu.Lock()
if h.model != nil {
if h.AltScreen {
h.model.resizeAlt(cols, rows)
} else {
h.model.resize(cols, rows)
}
}
h.mu.Unlock()
// The MAIN buffer moves on a resize too, and the mirror's write
// row has to follow it. Measured 2026-09-03: with real
// scrollback above, a grow pulls history back in and pushes
// the rows DOWN by up to the delta (ten rows grown, eight
// pulled in); a shrink keeps the bottom and slides them UP by
// the rows lost. While the buffer is still filling, move the
// write row by the delta: exact when history is long, a gap
// rather than an overwrite when it is short. Once the buffer
// is full every row goes to the last row anyway.
if h.mainRow <= oldRows {
h.mainRow = clamp(h.mainRow+rows-oldRows, 1, rows+1)
} else {
h.mainRow = rows + 1
}
h.traceSize(cols, rows, agentRows)
h.write(resizeSequence(h.AltScreen, h.Rules, oldRows, rows, oldAgent, agentRows))
// A WIDTH change leaves Terminal.app holding each row's old
// cells past the new width, and erase cannot reach them -- the
// strip he has photographed at the frame's right edge. DL can:
// see reallocBand. Rows only, and nothing happens on a
// height-only resize.
if cols != oldCols && h.Rules.RetainsWidth {
h.write(reallocBand(agentRows+1, rows))
}
// The screen was just touched behind the tracker's back.
dmg.reset()
p.SetSize(cols, agentRows)
f.Band.Store(int32(agentRows))
}
h.mirror(rows, agentRows)
if scapeRows <= 0 || h.Paint == nil {
continue
}
lines := h.Paint(cols, scapeRows)
if len(lines) == 0 {
continue
}
if len(lines) > scapeRows {
lines = lines[:scapeRows]
}
dirty := dmg.changed(lines)
if len(dirty) == 0 {
continue
}
var b strings.Builder
b.WriteString(BeginPaint())
for _, i := range dirty {
fmt.Fprintf(&b, "\x1b[%d;1H", agentRows+1+i)
b.WriteString(lines[i])
}
b.WriteString(EndPaint(agentRows))
// One write, so the terminal sees a whole frame between the
// cursor save and its restore.
h.write(b.String())
}
}
}
// clearRows blanks rows first..last inclusive, in screen coordinates, and puts
// the cursor back where it was.
func clearRows(first, last int) string {
if first > last {
return ""
}
return saveCursor + clearRowsBare(first, last) + restoreCursor
}
// clearRowsBare is clearRows without the save and restore, for callers that
// own the cursor themselves. It still drops origin mode and the region,
// because rows outside the band cannot be addressed otherwise, and it leaves
// the cursor on the last row it cleared.
//
// ⚠ The SGR reset is not tidiness, it is the erase's argument. EL does not
// write spaces; it fills with the CURRENT background (BCE), and under reverse
// video that is the foreground. Every caller here clears on a timer -- the
// resize tick -- which fires with no relation to where the agent is in its
// output, and Claude Code paints backgrounds constantly: its input box, the
// context bar, a selection. So the colour in force is not the host's to assume,
// and a clear that inherited it turned the rows it touched into a solid band of
// whatever Claude happened to be drawing. Those rows then scroll out of the
// band into scrollback, which is the wall of black he hit scrolling up.
//
// Safe inside Rebind and clearRows because both bracket this with DECSC/DECRC,
// and DECRC restores the agent's SGR along with its cursor.
//
// That last clause was challenged as an unmeasured assumption about
// Terminal.app, and it cannot be measured directly -- Terminal.app does not
// answer DECRQSS (probed 2026-09-03; the probe's control asked with a known
// rendition in force and got nothing back, so this is "unsupported", not
// "default"). But the running system already settles it: BeginPaint/EndPaint
// bracket the scape's own writes the same way, and every scape line ends in
// ESC[0m, twelve times a second. If DECRC did not restore SGR, the agent's
// rendition would be reset 12x/s and Claude Code's UI would be colourless.
// It is not. The inference is from behaviour in hand rather than a spec.
func clearRowsBare(first, last int) string {
if first > last {
return ""
}
var b strings.Builder
b.WriteString(originOff + regionReset + "\x1b[0m")
for r := first; r <= last; r++ {
fmt.Fprintf(&b, "\x1b[%d;1H\x1b[2K", r)
}
return b.String()
}
// resizeSequence is what the host sends the terminal when the window changed
// size: it moves the band to its new geometry, undoes whatever the terminal did
// to the rows, clears the rows that changed hands, and leaves the agent's
// cursor where the agent believes it is. One function, so the tests feed the
// exact bytes production emits.
//
// Not the whole screen. Claude Code cannot redraw a transcript that has
// scrolled, so clearing the lot wiped the session's history off the screen
// until the next turn happened to redraw it. Measured both ways: whole-screen
// loses the transcript, this does not.
//
// The band is re-pinned BEFORE the pty is resized (see Run), because the
// child's repaint arrives with the SIGWINCH and has to land in the new region
// rather than the one it is leaving.
//
// ⚠ The clear has to allow for the TERMINAL having moved things. Measured by
// eye on 2026-09-03 with notes/contentprobe, in production's configuration,
// after two earlier readings got this backwards: **Terminal.app anchors
// content to the BOTTOM edge.** A shrink of N pulls every row UP by N and loses
// the top ones; a grow of N pushes every row DOWN by N and inserts blanks at
// the top. Both buffers, both directions. The CURSOR does not move either way
// -- the trap that cost this project most of a day: notes/anchorprobe parks the
// cursor and reads it back with DSR, so it reported "anchored top" for a screen
// whose content was anchored bottom.
func resizeSequence(alt bool, r Rules, oldRows, rows, oldAgent, agentRows int) string {
// So the clear range starts where the old scape's first row LANDS.
drop := oldRows - rows
if drop < 0 {
drop = 0
}
// And on a GROW the push is undone before anything is painted, because the
// rows it pushed down are the agent's and the scape is about to paint over
// the ones that crossed the boundary. Alt screen only: that is where it was
// measured, and the main screen's grow pulls real scrollback back in, which
// is content a scroll would push away again.
// Only where the terminal pushes (Terminal.app): Ghostty keeps the content
// at the top on a grow, and scrolling it up there loses the transcript's
// first rows and leaves the agent's box a tick above its cursor.
grow := 0
if alt && r.GrowPushesDown && rows > oldRows {
grow = rows - oldRows
}
from := oldAgent + 1 - drop
if from < 1 {
from = 1
}
to := min(agentRows, oldRows-drop)
// A SHRINK on the alternate screen is the one case where the cursor, not
// just the rows, has to be put back -- see RebindShrinkAlt.
if alt && rows < oldRows {
if r.ShrinkKeepsCursor {
return RebindShrinkAlt(oldRows-rows, oldAgent-agentRows, agentRows)
}
return RebindShrinkAltFollow(oldRows-rows, oldAgent-agentRows, agentRows)
}
return Rebind(grow, from, to, agentRows)
}
// maxMirrored caps what is kept for the replay. Terminal.app's own scrollback
// default is ten thousand rows; keeping more than that would replay rows the
// terminal then drops anyway.
const maxMirrored = 10000
// mirror sends the rows that left the band since the last tick to the main
// buffer. One batch per tick, so the screen switches at most FPS times a
// second; he watched four hundred a second and saw nothing.
func (h *Host) mirror(rows, agentRows int) {
if h.model == nil {
return
}
h.mu.Lock()
kept := h.model.takeScrolled()
h.mu.Unlock()
if len(kept) == 0 {
return
}
lines := make([]string, len(kept))
for i, row := range kept {
lines[i] = rowANSI(row)
}
h.mirrored = append(h.mirrored, lines...)
if len(h.mirrored) > maxMirrored {
h.mirrored = h.mirrored[len(h.mirrored)-maxMirrored:]
}
h.write(MirrorBatch(lines, &h.mainRow, rows, agentRows))
}
// replay is the mirrored transcript once more, for after the alternate screen
// is gone. Terminal.app keeps only the oldest few rows across 1049l, so the
// first lines here can repeat ones already on screen; a separator makes the
// seam visible rather than mysterious.
func (h *Host) replay() string {
if len(h.mirrored) == 0 {
return ""
}
// Every row is erased before it is written. Terminal.app keeps the rows
// that were still on the main screen at 1049l, and the replay starts
// where the shell's cursor was restored, which is ON those rows: a
// shorter line written over a longer survivor would leave the tail of
// the survivor showing (it did, in the first live run: "LIVE LINE 80").
// SGR reset first, because the erase fills with the current background.
//
// The header goes ON the row the cursor was restored to, so no survivor
// sits above it, and the screen below the last row is erased, so none
// sits under it either: what remains is the shell's own history, the
// transcript, the final screen, and then the prompt.
var b strings.Builder
fmt.Fprintf(&b, "\r\x1b[0m\x1b[2K\x1b[2mxscapes: the agent's transcript, %d rows\x1b[0m\r\n", len(h.mirrored))
for _, l := range h.mirrored {
b.WriteString("\x1b[0m\x1b[2K")
b.WriteString(l)
b.WriteString("\r\n")
}
b.WriteString("\x1b[0m\x1b[J")
return b.String()
}
// keepFinalScreen adds what is still in the band at exit to the rows that
// will be replayed: the last screenful never left the band by scrolling, so
// the mirror never saw it, and it is usually the reason he quit. Trailing
// blank rows are dropped.
func (h *Host) keepFinalScreen(agentRows int) {
if h.model == nil {
return
}
h.mu.Lock()
var lines []string
if h.model.alt {
for y := 0; y < agentRows && y < len(h.model.cells); y++ {
lines = append(lines, rowANSI(h.model.cells[y]))
}
}
h.mu.Unlock()
for len(lines) > 0 && lines[len(lines)-1] == "" {
lines = lines[:len(lines)-1]
}
h.mirrored = append(h.mirrored, lines...)
if len(h.mirrored) > maxMirrored {
h.mirrored = h.mirrored[len(h.mirrored)-maxMirrored:]
}
}
// forwardKeys copies the terminal's input to the agent, byte for byte, except
// for the one reply the host asked for itself: while wantCPR is set, the first
// cursor position report (ESC [ row ; col R) is taken out of the stream and
// its row sent on cpr. Keys typed during that wait are held, and released the
// moment the wait ends -- by the report arriving, or by waitDone closing on the
// timeout -- so a terminal that never answers costs nobody a keystroke.
// Everything else, including a reply that arrives after the host stopped
// waiting, goes to the agent untouched.
func (h *Host) forwardKeys(in io.Reader, master io.Writer, cpr chan<- int, waitDone <-chan struct{}) {
reads := make(chan []byte, 8)
go func() {
defer close(reads)
buf := make([]byte, 4096)
for {
n, err := in.Read(buf)
if n > 0 {
if h.OnInput != nil {
h.OnInput(buf[:n])
}
reads <- append([]byte(nil), buf[:n]...)
}
if err != nil {
return
}
}
}()
var held []byte
flush := func() {
if len(held) > 0 {
master.Write(held)
held = nil
}
}
for {
select {
case data, ok := <-reads:
if !ok {
flush()
return
}
if h.wantCPR.Load() {
held = append(held, data...)
if row, rest, ok := takeCPR(held); ok {
h.wantCPR.Store(false)
select {
case cpr <- row:
default:
}
held = rest
flush()
} else if len(held) > 64 {
// Nothing that long is a cursor report. Let it through.
flush()
}
continue
}
held = append(held, data...)
flush()
case <-waitDone:
waitDone = nil
flush()
}
}
}
// takeCPR finds a cursor position report in b and returns its row and the
// bytes around it, or false if there is none yet.
func takeCPR(b []byte) (row int, rest []byte, ok bool) {
s := string(b)
i := strings.Index(s, "\x1b[")
for i >= 0 {
j := i + 2
for j < len(s) && (s[j] >= '0' && s[j] <= '9' || s[j] == ';') {
j++
}
if j < len(s) && s[j] == 'R' {
var r, c int
if _, err := fmt.Sscanf(s[i+2:j], "%d;%d", &r, &c); err == nil {
rest = append([]byte(s[:i]), s[j+1:]...)
return r, rest, true
}
}
k := strings.Index(s[i+1:], "\x1b[")
if k < 0 {
break
}
i += 1 + k
}
return 0, nil, false
}