Files
pipelines/internal/server/chat_shell_supervise.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

255 lines
7.0 KiB
Go

package server
import (
"context"
"errors"
"os"
"os/exec"
"syscall"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Live output flow of a run: output is pushed as soon as it arrives, oldest
// first, while the session's watchers keep their queues short
// (chatShellBacklog frames). While chatShellWindow bytes wait unpushed the
// command's output is not read, so the command waits for its watchers. A
// watcher that has not drained for chatShellStall stops holding it: the
// output then skips to the newest chunk, a gap the client shows. While output
// streams, a frame waits up to chatShellRetry for more to join it.
const (
chatShellBacklog = 8
chatShellWindow = 256 << 10
chatShellStall = 3 * time.Second
chatShellRetry = 2 * time.Millisecond
)
// supervise reads one command's merged output (or terminal stream), streams
// it live, saves it periodically and records how the command ended. It owns
// the reader.
func (r *chatShellRunner) supervise(p *chatShellProcess, reader *os.File) {
defer r.wg.Done()
defer close(p.done)
readDone, exitedCh := make(chan struct{}), make(chan struct{})
go func() {
defer close(readDone)
buffer := make([]byte, 32<<10)
for {
p.awaitPushed(exitedCh)
n, err := reader.Read(buffer)
if n > 0 {
p.mu.Lock()
if !p.closed {
p.out.write(buffer[:n])
}
p.mu.Unlock()
signalChatShell(p.wake)
}
if err != nil {
return
}
}
}()
waitDone := make(chan error, 1)
go func() { waitDone <- p.cmd.Wait() }()
pid := p.cmd.Process.Pid
flush := time.NewTicker(r.flush)
defer flush.Stop()
lastSaved := r.now()
var waitErr error
var drainDone, retry <-chan time.Time
var flow chatShellFlow
exited, drained, shutdown := false, false, false
base := r.base.Done()
push := func() {
retry = nil
if r.pushOutput(p, &flow) {
retry = time.After(chatShellRetry)
}
}
for !exited || !drained {
select {
case <-p.wake:
push()
case <-retry:
push()
case <-flush.C:
push()
if r.now().Sub(lastSaved) >= r.persist {
lastSaved = r.now()
r.save(p.snapshot(protocol.ChatShellRunRetained))
}
case waitErr = <-waitDone:
exited = true
close(exitedCh)
// Descendants may hold the pipe or terminal open; read what
// they write briefly, then stop reading. A terminal may not
// support deadlines, so the timer also ends the wait.
_ = reader.SetReadDeadline(time.Now().Add(chatShellDrain))
drainDone = time.After(chatShellDrain + chatShellDrain/2)
case <-drainDone:
drained = true
readDone = nil
case <-readDone:
drained = true
readDone = nil
case <-base:
base = nil
shutdown = true
_ = syscall.Kill(-pid, syscall.SIGKILL)
}
}
// Nothing in the command's group outlives it.
_ = syscall.Kill(-pid, syscall.SIGKILL)
p.mu.Lock()
reader.Close()
p.closed = true
p.mu.Unlock()
for r.emitOutput(p, true) {
}
p.mu.Lock()
finishChatShellRecord(&p.record, waitErr, p.stopped, shutdown || r.base.Err() != nil, r.now())
p.mu.Unlock()
record := p.snapshot(protocol.ChatShellRunRetained)
r.save(record)
r.mu.Lock()
delete(r.active, p.record.ID)
r.mu.Unlock()
r.publishRun(record)
}
// finishChatShellRecord records how a command ended. A requested stop wins
// over the exit status it caused; a server shutdown marks it interrupted.
func finishChatShellRecord(record *protocol.ChatShellRunRecord, waitErr error, stopped, shutdown bool, now time.Time) {
record.EndedAt = now.UnixMilli()
record.DurationMS = max(record.EndedAt-record.StartedAt, 0)
var exitErr *exec.ExitError
switch {
case waitErr == nil:
code := 0
record.ExitCode = &code
case errors.As(waitErr, &exitErr):
if status, ok := exitErr.Sys().(syscall.WaitStatus); ok && status.Signaled() {
record.Signal = status.Signal().String()
} else {
code := exitErr.ExitCode()
record.ExitCode = &code
}
default:
record.Error = waitErr.Error()
}
switch {
case shutdown:
record.Status = protocol.ChatShellRunInterrupted
record.Error = chatShellInterruptedReason
case stopped:
record.Status = protocol.ChatShellRunStopped
case record.Error != "":
record.Status = protocol.ChatShellRunFailed
default:
record.Status = protocol.ChatShellRunExited
}
}
// chatShellFlow is one run's live push state: held is when its watchers
// were first found behind, paced when a stalled push last went out, last
// when a frame last went out.
type chatShellFlow struct {
held, paced, last time.Time
}
// pushOutput pushes the unpushed output, oldest first, while the session's
// watchers drain; it reports whether output still waits for them. Watchers
// behind for chatShellStall get the old pacing until they catch up: the
// newest chunk once per flush interval, the rest skipped (a gap).
func (r *chatShellRunner) pushOutput(p *chatShellProcess, flow *chatShellFlow) bool {
for {
if r.backlog != nil && r.backlog(p.sessionID()) >= chatShellBacklog {
now := time.Now()
if flow.held.IsZero() {
flow.held = now
}
if now.Sub(flow.held) < chatShellStall {
return true
}
p.mu.Lock()
p.out.skipUnemitted(protocol.ChatShellRunChunkLimit)
p.mu.Unlock()
signalChatShell(p.room)
if now.Sub(flow.paced) >= r.flush {
flow.paced = now
r.emitOutput(p, false)
}
return true
}
flow.held = time.Time{}
p.mu.Lock()
waiting := p.out.unemitted()
p.mu.Unlock()
if waiting > 0 && waiting < protocol.ChatShellRunChunkLimit && time.Since(flow.last) < chatShellRetry {
return true // streaming: let the rest gather into one frame
}
if !r.emitOutput(p, false) {
return false
}
flow.last = time.Now()
}
}
// emitOutput pushes the oldest output not pushed yet (one frame) and
// reports whether there was any.
func (r *chatShellRunner) emitOutput(p *chatShellProcess, final bool) bool {
p.mu.Lock()
text, offset, end, ok := p.out.pending(protocol.ChatShellRunChunkLimit, final)
sessionID, runID := p.record.SessionID, p.record.ID
p.mu.Unlock()
if !ok {
return false
}
signalChatShell(p.room)
if r.publish != nil {
r.publish(sessionID, protocol.ChatShellRunEventFrame{SessionID: sessionID, RunID: runID, Output: text, Offset: offset, End: end})
}
return true
}
func (p *chatShellProcess) sessionID() string {
p.mu.Lock()
defer p.mu.Unlock()
return p.record.SessionID
}
// awaitPushed holds the reader while chatShellWindow bytes wait unpushed,
// until the command exited (its output is then drained regardless).
func (p *chatShellProcess) awaitPushed(exited <-chan struct{}) {
for {
p.mu.Lock()
waiting := p.out.unemitted() >= chatShellWindow
p.mu.Unlock()
if !waiting {
return
}
select {
case <-p.room:
case <-exited:
return
}
}
}
func signalChatShell(ch chan struct{}) {
select {
case ch <- struct{}{}:
default:
}
}
// save persists a record; a shutdown's base context is already canceled, so
// it uses its own bounded context.
func (r *chatShellRunner) save(record protocol.ChatShellRunRecord) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = r.store.SaveChatShellRun(ctx, record, protocol.ChatShellRunHistory)
}