Files
pipelines/internal/server/terminal_process.go
T
alan e13cb99ade Terminals: keep screen state on the server; snapshot on reload and gaps
A headless xterm-compatible emulator (internal/termstate) follows each
machine terminal's PTY output under the same lock as the 1 MiB tail. A
terminal_output from before the retained tail (new page, reload, gap)
now gets output_snapshot: an escape stream that resets the client and
restores scrollback (1000 lines), main screen, the alternate screen when
in use (via ?1049h so the program's exit brings the shell back), saved
cursors, tabs, scroll region, cursor incl. pending wrap, modes (mouse
tracking/encoding, bracketed paste, DECCKM, keypad, autowrap, origin,
focus, ...), charsets, pen and title, as of output_end; frames continue
there. Reads inside the tail stay raw.

No Go library was adequate: charmbracelet/x/vt and vito/midterm scroll at
0.2-4 MB/s and hide modes/pen/region; vt10x is unmaintained. termstate
runs at 160-200 MB/s.

The app treats a snapshot reply as a replay without the dropped-output
line, and every replay now starts with RIS so stale modes end.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 00:56:49 +00:00

251 lines
6.9 KiB
Go

package server
import (
"crypto/rand"
"encoding/hex"
"errors"
"os"
"os/exec"
"sync"
"syscall"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/termstate"
)
// terminalProcess is one terminal this server process holds: running (its
// attachment is the login, then the shell it becomes) or ended with its
// output still retained.
type terminalProcess struct {
mu sync.Mutex
record protocol.TerminalRecord
out *chatShellOutput
// screen follows the output (terminal_screen.go).
screen *termstate.Terminal
titles terminalTitles
// login follows the output until the login completes; loginChanged is
// signalled when it changes.
login terminalLoginWatch
loginChanged chan struct{}
// cmd and pty are the running login or shell.
cmd *exec.Cmd
pty *os.File
input chan []byte
done chan struct{}
// closing is set by terminal_close: the end is a close, not an exit.
closing bool
// refused: the login never asked for a password; the terminal is
// forgotten without being listed.
refused bool
// views are the connections' subscriptions to the output
// (terminal_flow.go); room is signalled when one may have room again,
// exited is closed once the attachment exited, and outDone is set once
// its stream is fully read.
views map[*terminalView]struct{}
room chan struct{}
exited chan struct{}
outDone bool
// viewers are the connections drawing it (terminal_viewers.go).
viewers terminalViewers
}
func newTerminalProcess(record protocol.TerminalRecord) *terminalProcess {
var stream [6]byte
_, _ = rand.Read(stream[:])
record.Stream = hex.EncodeToString(stream[:])
return &terminalProcess{
record: record,
out: newChatShellOutput(protocol.TerminalRetained),
screen: termstate.New(record.Cols, record.Rows, termstate.DefaultScrollback),
input: make(chan []byte, protocol.ChatShellInputQueue),
done: make(chan struct{}),
views: map[*terminalView]struct{}{},
room: make(chan struct{}, 1),
exited: make(chan struct{}),
loginChanged: make(chan struct{}, 1),
}
}
// loginState is the login's progress and the output retained so far.
func (p *terminalProcess) loginState() (terminalLoginWatch, string) {
p.mu.Lock()
defer p.mu.Unlock()
text, _ := p.out.tail(terminalLoginScan)
return p.login, text
}
func (p *terminalProcess) running() bool {
p.mu.Lock()
defer p.mu.Unlock()
return p.record.Status == protocol.TerminalRunning
}
// snapshot is the current record; with output, the retained bytes from
// absolute byte after on.
func (p *terminalProcess) snapshot(output bool, after int64) protocol.TerminalRecord {
p.mu.Lock()
defer p.mu.Unlock()
return p.snapshotLocked(output, after)
}
// snapshotLocked is snapshot with p.mu held. The output ends at OutputEnd:
// an incomplete trailing character waits for the next frame. A read from
// before the retained tail gets the screen's snapshot instead of the tail
// (terminal_screen.go).
func (p *terminalProcess) snapshotLocked(output bool, after int64) protocol.TerminalRecord {
record := p.record
record.OutputEnd = p.out.total
if output && after < p.retainedFromLocked() {
p.screenLocked(&record)
return record
}
if output {
from := max(after, p.out.start)
text, start, end, ok := p.out.chunk(from, p.out.total, protocol.TerminalRetained, p.outDone)
if !ok {
// Nothing new (or only part of a character): the reply ends
// where the frames that follow it start.
from = min(from, p.out.total)
text, start, end = "", from, from
}
record.Output, record.OutputStart, record.OutputEnd = text, start, end
}
return record
}
// readFor is the record with its output from after on, read for
// subscription v (when set): v's frames continue where the output ends,
// once the reply is written (v.release).
func (p *terminalProcess) readFor(after int64, v *terminalView) protocol.TerminalRecord {
p.mu.Lock()
defer p.mu.Unlock()
record := p.snapshotLocked(true, after)
if v != nil && !v.gone {
v.resetLocked(record.OutputEnd)
if v.flow {
record.Window = protocol.TerminalFlowWindow
}
}
return record
}
// startAttachment starts cmd in a fresh pseudo-terminal at the record's
// size and makes it the current attachment.
func (p *terminalProcess) startAttachment(cmd *exec.Cmd) (*os.File, error) {
if !chatShellTerminals {
return nil, errors.New(protocol.ChatShellTerminalUnsupported)
}
p.mu.Lock()
cols, rows := p.record.Cols, p.record.Rows
p.mu.Unlock()
terminal, err := startChatShellTerminal(cmd, cols, rows)
if err != nil {
return nil, err
}
p.mu.Lock()
p.cmd, p.pty = cmd, terminal
p.mu.Unlock()
return terminal, nil
}
// read copies one attachment's stream into the retained output and follows
// the window title; it returns when the attachment's terminal is closed.
func (p *terminalProcess) read(terminal *os.File, titled func(string)) {
buffer := make([]byte, 32<<10)
for {
p.awaitRoom()
n, err := terminal.Read(buffer)
if n > 0 {
p.mu.Lock()
p.out.write(buffer[:n])
p.screen.Write(buffer[:n])
p.pokeViewsLocked()
if p.login.feed(buffer[:n]) {
select {
case p.loginChanged <- struct{}{}:
default:
}
}
title, changed := p.titles.feed(buffer[:n])
changed = changed && title != p.record.Title
if changed {
p.record.Title = title
}
p.mu.Unlock()
if changed {
titled(title)
}
}
if err != nil {
return
}
}
}
// pumpInput writes queued input to the terminal until it ends.
func (p *terminalProcess) pumpInput() {
for {
select {
case <-p.done:
return
case data := <-p.input:
p.mu.Lock()
terminal := p.pty
p.mu.Unlock()
if terminal != nil {
_, _ = terminal.Write(data)
}
}
}
}
// signal sends sig to the current attachment's process group.
func (p *terminalProcess) signal(sig syscall.Signal) {
p.mu.Lock()
cmd := p.cmd
p.mu.Unlock()
if cmd != nil && cmd.Process != nil {
_ = syscall.Kill(-cmd.Process.Pid, sig)
}
}
// waitAttachment waits for the attachment to exit and its stream to drain
// (a descendant holding the terminal is read briefly, then cut off), then
// kills its group and closes its terminal. It returns the exit error.
func (p *terminalProcess) waitAttachment(cmd *exec.Cmd, terminal *os.File, readDone <-chan struct{}) error {
err := cmd.Wait()
close(p.exited)
_ = terminal.SetReadDeadline(time.Now().Add(chatShellDrain))
select {
case <-readDone:
case <-time.After(chatShellDrain + chatShellDrain/2):
}
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
p.mu.Lock()
terminal.Close()
if p.pty == terminal {
p.pty = nil
}
p.mu.Unlock()
return err
}
// exitCode is the shell's exit status, when it exited by itself.
func terminalExitCode(err error) *int {
code := 0
var exitErr *exec.ExitError
switch {
case err == nil:
case errors.As(err, &exitErr):
if status, ok := exitErr.Sys().(syscall.WaitStatus); ok && status.Signaled() {
return nil
}
code = exitErr.ExitCode()
default:
return nil
}
return &code
}