Files
pipelines/internal/server/chat_shell_supervise.go
alan 355b722a1d Run chat shell commands in a pseudo-terminal with typed input and resize
Commands start in a PTY (creack/pty; macOS and Linux) of the client's size
with TERM=xterm-256color in their own session. chat_shell_input writes typed
UTF-8 text in order through a bounded queue; chat_shell_resize sets the size.
Output stays the raw terminal stream with byte offsets as sequence numbers,
chat_shell_run_output resumes from an offset, and a plain-text rendering is
persisted for Copy output and Send to agent. Input is never stored or logged.
2026-11-09 19:57:46 +00:00

144 lines
4.0 KiB
Go

package server
import (
"context"
"errors"
"os"
"os/exec"
"syscall"
"time"
"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.
func (r *chatShellRunner) supervise(p *chatShellProcess, reader *os.File) {
defer r.wg.Done()
defer close(p.done)
readDone := make(chan struct{})
go func() {
defer close(readDone)
buffer := make([]byte, 32<<10)
for {
n, err := reader.Read(buffer)
if n > 0 {
p.mu.Lock()
if !p.closed {
p.out.write(buffer[:n])
}
p.mu.Unlock()
}
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 <-chan time.Time
exited, drained, shutdown := false, false, false
base := r.base.Done()
for !exited || !drained {
select {
case <-flush.C:
r.emitOutput(p, false)
if r.now().Sub(lastSaved) >= r.persist {
lastSaved = r.now()
r.save(p.snapshot(protocol.ChatShellRunRetained))
}
case waitErr = <-waitDone:
exited = true
// 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()
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
}
}
// emitOutput pushes the output written since the last frame.
func (r *chatShellRunner) emitOutput(p *chatShellProcess, final 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
}
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
// 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)
}