Files
pipelines/internal/server/terminal_process.go
T
alan 0963a071d0 Terminals: flow-controlled output, immediate echo, sliced emulator writes
Machine terminals no longer skip output for live viewers. Each connection's
subscription is a cursor into the 1 MiB retained tail, drained by the
connection's writer as soon as the PTY reader writes (no 50 ms tick; a
streaming frame gathers for at most 2 ms). A subscription opened with
flow: true gets window (256 KiB) in its reply and acknowledges drawn output
with terminal_ack; while one is full the reader stops reading the PTY, so
the program waits. A subscription full for 3 s without acking stops holding
the terminal and later sees a gap; a gone connection drops its
subscriptions. Clients that never ask for flow keep the old pacing (newest
64 KiB per 50 ms). terminal_open/terminal_output replies precede the frames
that follow them, which start exactly at the reply's output_end.

Chat shell runs share the buffer code: output is pushed as it arrives,
oldest first, while the chat's watchers keep short queues; 256 KiB unpushed
stops the reader, and watchers behind for 3 s get the old pacing.

The app asks for flow, takes offsets from the server (frame end, reply
output_end) instead of re-encoded text length, acks per quarter window, and
writes replays and bursts into the emulator in slices that yield to the
event loop (ChatShellTerminalFeed, shared with chat shells).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 23:57:18 +00:00

238 lines
6.4 KiB
Go

package server
import (
"crypto/rand"
"encoding/hex"
"errors"
"os"
"os/exec"
"sync"
"syscall"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// 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
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
}
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),
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.
func (p *terminalProcess) snapshotLocked(output bool, after int64) protocol.TerminalRecord {
record := p.record
record.OutputEnd = p.out.total
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.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
}