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>
This commit is contained in:
2026-11-25 23:57:18 +00:00
parent 5ab1ec9e00
commit 0963a071d0
30 changed files with 1958 additions and 182 deletions
+122 -11
View File
@@ -11,16 +11,32 @@ import (
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// supervise reads one command's merged output (or terminal stream), streams it in batches, saves
// it periodically and records how the command ended. It owns the reader.
// 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 := make(chan struct{})
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()
@@ -28,6 +44,7 @@ func (r *chatShellRunner) supervise(p *chatShellProcess, reader *os.File) {
p.out.write(buffer[:n])
}
p.mu.Unlock()
signalChatShell(p.wake)
}
if err != nil {
return
@@ -41,19 +58,31 @@ func (r *chatShellRunner) supervise(p *chatShellProcess, reader *os.File) {
defer flush.Stop()
lastSaved := r.now()
var waitErr error
var drainDone <-chan time.Time
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:
r.emitOutput(p, false)
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.
@@ -77,7 +106,8 @@ func (r *chatShellRunner) supervise(p *chatShellProcess, reader *os.File) {
reader.Close()
p.closed = true
p.mu.Unlock()
r.emitOutput(p, true)
for r.emitOutput(p, true) {
}
p.mu.Lock()
finishChatShellRecord(&p.record, waitErr, p.stopped, shutdown || r.base.Err() != nil, r.now())
p.mu.Unlock()
@@ -122,16 +152,97 @@ func finishChatShellRecord(record *protocol.ChatShellRunRecord, waitErr error, s
}
}
// emitOutput pushes the output written since the last frame.
func (r *chatShellRunner) emitOutput(p *chatShellProcess, final bool) {
// 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 || r.publish == nil {
return
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:
}
r.publish(sessionID, protocol.ChatShellRunEventFrame{SessionID: sessionID, RunID: runID, Output: text, Offset: offset, End: end})
}
// save persists a record; a shutdown's base context is already canceled, so