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

198 lines
6.9 KiB
Go

package server
import (
"context"
"errors"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// handleChatShellRunRequest answers the operator shell-command requests. Every
// one names an operator chat session the registry records: the command runs
// only in that chat's own directory on this server's machine, and a run is
// only readable, stoppable or typed into through the session that started it.
// Any authenticated client of that session may type into a running command,
// not only the one that started it.
func handleChatShellRunRequest(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, clientID string, write func(protocol.Message) error) {
fail := func(err error) { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) }
runner := hub.shellRunner()
if runner == nil {
fail(errors.New("shell commands are not configured on this server"))
return
}
var sessionID string
body := request.ChatShellRunRequest
switch {
case request.Type == protocol.ChatShellRuns && request.ChatQuery != nil:
sessionID = request.ChatQuery.SessionID
case body != nil:
sessionID = body.SessionID
}
if !validChatSessionID(sessionID) {
fail(errors.New("a valid chat session id is required"))
return
}
if registry == nil {
fail(errors.New("operator session registry is not configured on this server"))
return
}
session, found, err := registry.OperatorSession(ctx, sessionID)
if err != nil {
fail(err)
return
}
if !found {
fail(errors.New("operator session is not available"))
return
}
if request.Type != protocol.ChatShellRuns && body == nil {
fail(errors.New("a chat shell request body is required"))
return
}
switch request.Type {
case protocol.ChatShellRun:
record, err := runner.Start(ctx, sessionID, session.Directory, body.Command, body.Cols, body.Rows)
if err != nil {
fail(err)
return
}
runner.attachViewer(clientID, sessionID, record.ID, record.Cols, record.Rows)
_ = write(protocol.Message{Type: protocol.ChatShellRun, ID: request.ID, ChatShellRun: &record})
case protocol.ChatShellStop:
record, err := runner.Stop(sessionID, body.RunID)
if err != nil {
fail(err)
return
}
_ = write(protocol.Message{Type: protocol.ChatShellStop, ID: request.ID, ChatShellRun: &record})
case protocol.ChatShellRuns:
runs, err := runner.List(ctx, sessionID)
if err != nil {
fail(err)
return
}
dismissedRuns, dismissed, err := runner.Dismissed(ctx, sessionID)
if err != nil {
fail(err)
return
}
_ = write(protocol.Message{Type: protocol.ChatShellRuns, ID: request.ID, ChatShellRuns: runs,
ChatShellDismissed: dismissed, ChatShellDismissedRuns: dismissedRuns})
case protocol.ChatShellDismiss:
dismissed, err := runner.Dismiss(ctx, sessionID, body.RunIDs)
if err != nil {
fail(err)
return
}
_ = write(protocol.Message{Type: protocol.ChatShellDismiss, ID: request.ID, ChatShellDismissed: dismissed})
case protocol.ChatShellRestore:
runs, err := runner.Restore(ctx, sessionID, body.RunIDs)
if err != nil {
fail(err)
return
}
_ = write(protocol.Message{Type: protocol.ChatShellRestore, ID: request.ID, ChatShellRuns: runs})
case protocol.ChatShellInput:
if err := runner.ClientInput(clientID, sessionID, body.RunID, body.Data, body.Reply, body.Cols, body.Rows); err != nil {
fail(err)
return
}
_ = write(protocol.Message{Type: protocol.ChatShellInput, ID: request.ID})
case protocol.ChatShellResize:
record, err := runner.ClientResize(clientID, sessionID, body.RunID, body.Cols, body.Rows, body.Activate)
if err != nil {
fail(err)
return
}
_ = write(protocol.Message{Type: protocol.ChatShellResize, ID: request.ID, ChatShellRun: &record})
case protocol.ChatShellRunOutput:
record, err := runner.Read(ctx, sessionID, body.RunID)
if err != nil {
fail(err)
return
}
record = chatShellRecordAfter(record, body.After)
_ = write(protocol.Message{Type: protocol.ChatShellRunOutput, ID: request.ID, ChatShellRun: &record})
case protocol.ChatShellShare:
record, err := runner.Read(ctx, sessionID, body.RunID)
if err != nil {
fail(err)
return
}
if record.Status == protocol.ChatShellRunRunning {
fail(errors.New("wait for the command to finish before sending it to the agent"))
return
}
prompt := protocol.Message{Type: protocol.ChatPrompt, ID: request.ID, ChatPrompt: &protocol.ChatPromptRequest{
SessionID: sessionID, Text: chatShellSharePrompt(record), OperationID: body.OperationID,
}}
admitChatPrompt(ctx, prompt, broker, hub, registry, clientID, write, true)
}
}
// List is the session's recorded runs, oldest first. A running run carries
// its live output rather than the last periodic save; every run carries at
// most protocol.ChatShellRunListOutput bytes of its tail.
func (r *chatShellRunner) List(ctx context.Context, sessionID string) ([]protocol.ChatShellRunRecord, error) {
runs, err := r.store.ChatShellRuns(ctx, sessionID)
if err != nil {
return nil, err
}
for i, run := range runs {
if p := r.activeProcess(sessionID, run.ID); p != nil {
runs[i] = p.snapshot(protocol.ChatShellRunListOutput)
} else {
runs[i] = chatShellRecordTail(run, protocol.ChatShellRunListOutput)
}
runs[i].Text = ""
}
return runs, nil
}
// Read is one run of sessionID with its whole retained output.
func (r *chatShellRunner) Read(ctx context.Context, sessionID, runID string) (protocol.ChatShellRunRecord, error) {
if p := r.activeProcess(sessionID, runID); p != nil {
return p.snapshot(protocol.ChatShellRunRetained), nil
}
record, found, err := r.store.ChatShellRun(ctx, sessionID, runID)
if err != nil {
return protocol.ChatShellRunRecord{}, err
}
if !found {
return protocol.ChatShellRunRecord{}, errors.New("this chat has no such command")
}
if record.Text == "" && record.Output != "" {
// A run recorded before plain-text renderings were stored.
record.Text = chatShellPlainText(record.Output)
}
return record, nil
}
// chatShellRecordAfter keeps only the output from absolute byte after on; an
// offset before the retained tail keeps all of it (OutputStart says where it
// starts, so the reader sees the gap).
func chatShellRecordAfter(record protocol.ChatShellRunRecord, after int64) protocol.ChatShellRunRecord {
if after <= record.OutputStart {
return record
}
skip := min(after-record.OutputStart, int64(len(record.Output)))
cut := runeStartAfter([]byte(record.Output), int(skip))
record.Output = record.Output[cut:]
record.OutputStart += int64(cut)
return record
}
// chatShellRecordTail trims a stored record's output to its last max bytes.
func chatShellRecordTail(record protocol.ChatShellRunRecord, max int) protocol.ChatShellRunRecord {
if len(record.Output) <= max {
return record
}
out := newChatShellOutput(len(record.Output))
out.write([]byte(record.Output))
text, from := out.tail(max)
record.Output = text
record.OutputStart += from
record.Truncated = true
return record
}