Files
pipelines/internal/server/terminal_process.go
T
alan c3458d8a7f Terminals: one active client per terminal; keystrokes skip the request queue
Several clients drawing one terminal (machine terminal or chat terminal
command) no longer interfere. The server tracks, per terminal, the
connections drawing it, most recently active first: the active client
(the opener, then whoever last typed or focused it) owns the PTY size and
is the only one whose emulator's automatic query answers reach the
process; other clients' answers are acknowledged and dropped, and their
sizes recorded but not applied. When the active connection closes the next
most recent client's size is applied.

Protocol (backwards compatible; all new fields optional):
- terminal_input / chat_shell_input: reply (emulator answer), cols/rows
  (the typist's size, applied before the input).
- terminal_resize / chat_shell_resize: activate (the client focused it).

Latency: PipelinesClient sends terminal_input, terminal_resize,
chat_shell_input and chat_shell_resize at once rather than behind the
previous request's reply. The server reads those onto a per-connection
terminal lane handled in order beside the ordinary request loop, and
terminal_open (up to 5 s waiting for su) now runs off the read loop.

Client: ChatShellTerminalSession routes what the emulator emits while
drawing output to onReply and reports focus through activate();
ChatShellInputPipe keeps answers and typing in separate requests.

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

202 lines
5.1 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
// 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),
input: make(chan []byte, protocol.ChatShellInputQueue),
done: 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()
record := p.record
record.OutputEnd = p.out.total
if output {
text, start := p.out.tail(protocol.TerminalRetained)
if after > start {
skip := min(after-start, int64(len(text)))
cut := runeStartAfter([]byte(text), int(skip))
text, start = text[cut:], start+int64(cut)
}
record.Output, record.OutputStart = text, start
}
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 {
n, err := terminal.Read(buffer)
if n > 0 {
p.mu.Lock()
p.out.write(buffer[:n])
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()
_ = 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
}