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

223 lines
11 KiB
Go

//go:build darwin || linux
package server
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"github.com/coder/websocket"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// terminalHome points the operator's home at a fresh directory, the login
// shell at /bin/sh (so tests never read the operator's own profile) and su
// at the fake below.
func terminalHome(t *testing.T) string {
t.Helper()
home, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatal(err)
}
original := operatorHomeDirectory
operatorHomeDirectory = func() (string, error) { return home, nil }
t.Cleanup(func() { operatorHomeDirectory = original })
t.Setenv("SHELL", "/bin/sh")
t.Setenv("ENV", "")
fakeTerminalSu(t)
return home
}
// fakeSuPassword is the only password the fake su accepts.
const fakeSuPassword = "test-password"
// fakeSuScript stands in for su on PATH, so tests never need a real
// password: `su -l <user> -c <script>` prints "Password:", reads a line with
// echo off, and runs the script in /bin/sh when it is fakeSuPassword.
// FAKE_SU_MODE=noprompt runs the script without asking, silent never
// prompts, notty fails as su does without a terminal.
const fakeSuScript = `#!/bin/sh
[ "$1" = -l ] && [ "$3" = -c ] || { echo "fake su: bad arguments: $*"; exit 2; }
case "$FAKE_SU_MODE" in
noprompt) SHELL=/bin/sh exec /bin/sh -c "$4" ;;
silent) exec sleep 30 ;;
notty) echo "su: must be run from a terminal"; exit 1 ;;
esac
stty -echo 2>/dev/null
printf 'Password:'
IFS= read -r password
stty echo 2>/dev/null
printf '\r\n'
[ "$password" = "` + fakeSuPassword + `" ] || { echo "su: Authentication failed"; exit 1; }
SHELL=/bin/sh exec /bin/sh -c "$4"
`
// fakeTerminalSu puts the fake su first on PATH.
func fakeTerminalSu(t *testing.T) {
t.Helper()
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "su"), []byte(fakeSuScript), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("FAKE_SU_MODE", "")
}
// terminalLogIn types the fake su's password into terminal id.
func terminalLogIn(t *testing.T, ctx context.Context, conn *websocket.Conn, id string) {
t.Helper()
terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalInput, "password", protocol.TerminalRequest{TerminalID: id, Data: fakeSuPassword + "\r"}))
}
func terminalRequest(kind, id string, body protocol.TerminalRequest) protocol.Message {
return protocol.Message{Type: kind, ID: id, TerminalRequest: &body}
}
// terminalReply sends request and returns its reply (skipping pushes).
func terminalReply(t *testing.T, ctx context.Context, conn *websocket.Conn, request protocol.Message) protocol.Message {
t.Helper()
writeChat(t, ctx, conn, request)
return readShellFrame(t, ctx, conn, func(m protocol.Message) bool { return m.ID == request.ID })
}
// readTerminalUntil reads output frames of id from end on, in order, until
// the collected text contains want; it returns the text and the new end.
func readTerminalUntil(t *testing.T, ctx context.Context, conn *websocket.Conn, id string, end int64, want string) (string, int64) {
t.Helper()
var seen strings.Builder
for !strings.Contains(seen.String(), want) {
frame := readShellFrame(t, ctx, conn, func(m protocol.Message) bool {
return m.Type == protocol.TerminalEvent && m.TerminalEvent.TerminalID == id && m.TerminalEvent.Terminal == nil
}).TerminalEvent
if frame.Offset != end {
t.Fatalf("frame at %d after %d", frame.Offset, end)
}
seen.WriteString(frame.Output)
end = frame.End
}
return seen.String(), end
}
// One client opens a shell, types into it, resizes it; a second client
// lists it, resumes its output by offset and closes it.
func TestTerminalOverWebsocket(t *testing.T) {
home := terminalHome(t)
ctx, _, conns := dialChatConns(t, Options{OperatorRegistry: newOperatorStore(t)}, 2)
opened := terminalReply(t, ctx, conns[0], terminalRequest(protocol.TerminalOpen, "open", protocol.TerminalRequest{Cols: 80, Rows: 24}))
term := opened.Terminal
if opened.Type != protocol.TerminalOpen || term == nil || term.Cwd != home || term.Status != protocol.TerminalRunning || term.Cols != 80 || !strings.HasSuffix(strings.Fields(term.Shell)[0], "/su") {
t.Fatalf("open reply = %+v", opened)
}
terminalLogIn(t, ctx, conns[0], term.ID)
if got := terminalReply(t, ctx, conns[0], terminalRequest(protocol.TerminalInput, "in", protocol.TerminalRequest{TerminalID: term.ID, Data: "pwd; echo sum-$((40+2))\r"})); got.Type != protocol.TerminalInput {
t.Fatalf("input reply = %+v", got)
}
_, end := readTerminalUntil(t, ctx, conns[0], term.ID, 0, "sum-42")
// The second client draws it larger; the opener stays the active client
// (terminal_active_test.go) until the second one types below.
resized := terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalResize, "size", protocol.TerminalRequest{TerminalID: term.ID, Cols: 120, Rows: 33}))
if resized.Type != protocol.TerminalResize || resized.Terminal.Cols != 80 || resized.Terminal.Rows != 24 {
t.Fatalf("resize reply = %+v", resized)
}
list := terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalList, "list", protocol.TerminalRequest{}))
if len(list.Terminals) != 1 || list.Terminals[0].ID != term.ID || list.Terminals[0].Cols != 80 || list.Terminals[0].Output != "" {
t.Fatalf("list = %+v", list.Terminals)
}
// The second client reads everything once, then only what follows.
all := terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalOutput, "all", protocol.TerminalRequest{TerminalID: term.ID})).Terminal
if all.OutputStart != 0 || !strings.Contains(all.Output, "Password:") || !strings.Contains(all.Output, home) || !strings.Contains(all.Output, "sum-42") ||
strings.Contains(all.Output, fakeSuPassword) {
t.Fatalf("output = %+v", all)
}
terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalInput, "in2", protocol.TerminalRequest{TerminalID: term.ID, Data: "stty size\r"}))
readTerminalUntil(t, ctx, conns[0], term.ID, end, "33 120")
resume := terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalOutput, "resume", protocol.TerminalRequest{TerminalID: term.ID, After: end})).Terminal
if resume.OutputStart != end || strings.Contains(resume.Output, "sum-42") || !strings.Contains(resume.Output, "33 120") {
t.Fatalf("resume = %+v", resume)
}
closed := terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalClose, "close", protocol.TerminalRequest{TerminalID: term.ID}))
if closed.Type != protocol.TerminalClose || closed.Terminal.Status != protocol.TerminalClosed {
t.Fatalf("close reply = %+v", closed)
}
// Every connection hears the close; the list forgets it.
event := readShellFrame(t, ctx, conns[0], func(m protocol.Message) bool {
return m.Type == protocol.TerminalEvent && m.TerminalEvent.Terminal != nil && m.TerminalEvent.Terminal.Status == protocol.TerminalClosed
})
if event.TerminalEvent.TerminalID != term.ID {
t.Fatalf("close event = %+v", event)
}
if list := terminalReply(t, ctx, conns[0], terminalRequest(protocol.TerminalList, "list2", protocol.TerminalRequest{})); len(list.Terminals) != 0 {
t.Fatalf("list after close = %+v", list.Terminals)
}
if got := terminalReply(t, ctx, conns[0], terminalRequest(protocol.TerminalInput, "late", protocol.TerminalRequest{TerminalID: term.ID, Data: "x"})); got.Type != protocol.Error {
t.Fatalf("late input = %+v", got)
}
}
// A shell that exits by itself is listed as exited with its status and
// keeps its output until it is closed.
func TestTerminalShellExit(t *testing.T) {
terminalHome(t)
ctx, _, conns := dialChatConns(t, Options{OperatorRegistry: newOperatorStore(t)}, 1)
term := terminalReply(t, ctx, conns[0], terminalRequest(protocol.TerminalOpen, "open", protocol.TerminalRequest{})).Terminal
terminalLogIn(t, ctx, conns[0], term.ID)
terminalReply(t, ctx, conns[0], terminalRequest(protocol.TerminalInput, "in", protocol.TerminalRequest{TerminalID: term.ID, Data: "echo bye; exit 3\r"}))
exited := readShellFrame(t, ctx, conns[0], func(m protocol.Message) bool {
return m.Type == protocol.TerminalEvent && m.TerminalEvent.Terminal != nil && m.TerminalEvent.Terminal.Status == protocol.TerminalExited
}).TerminalEvent.Terminal
if exited.ExitCode == nil || *exited.ExitCode != 3 || exited.EndedAt == 0 {
t.Fatalf("exited = %+v", exited)
}
out := terminalReply(t, ctx, conns[0], terminalRequest(protocol.TerminalOutput, "out", protocol.TerminalRequest{TerminalID: term.ID})).Terminal
if !strings.Contains(out.Output, "bye") || out.Status != protocol.TerminalExited {
t.Fatalf("output = %+v", out)
}
if got := terminalReply(t, ctx, conns[0], terminalRequest(protocol.TerminalClose, "close", protocol.TerminalRequest{TerminalID: term.ID})); got.Terminal == nil || got.Terminal.Status != protocol.TerminalClosed {
t.Fatalf("close = %+v", got)
}
}
// Requests outside the bounds are refused: directories outside home or
// missing, input bounds, unknown terminals, the open limit.
func TestTerminalLimitsAndValidation(t *testing.T) {
home := terminalHome(t)
ctx, _, conns := dialChatConns(t, Options{OperatorRegistry: newOperatorStore(t)}, 1)
conn := conns[0]
for i, cwd := range []string{"/", filepath.Join(home, "missing"), "relative", "~other"} {
if got := terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalOpen, "bad", protocol.TerminalRequest{Cwd: cwd})); got.Type != protocol.Error {
t.Fatalf("cwd %d %q = %+v", i, cwd, got)
}
}
if got := terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalOutput, "none", protocol.TerminalRequest{TerminalID: "term_nope"})); got.Type != protocol.Error {
t.Fatalf("unknown = %+v", got)
}
if got := terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalInput, "noid", protocol.TerminalRequest{Data: "x"})); got.Type != protocol.Error {
t.Fatalf("no id = %+v", got)
}
var ids []string
for i := 0; i < protocol.TerminalOpenLimit; i++ {
got := terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalOpen, "open", protocol.TerminalRequest{Cwd: "~"}))
if got.Terminal == nil {
t.Fatalf("open %d = %+v", i, got)
}
ids = append(ids, got.Terminal.ID)
}
over := terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalOpen, "over", protocol.TerminalRequest{}))
if over.Type != protocol.Error || !strings.Contains(over.Error, "8 open terminals") {
t.Fatalf("over limit = %+v", over)
}
for _, bad := range []string{"", strings.Repeat("x", protocol.ChatShellInputLimit+1)} {
if got := terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalInput, "bad-in", protocol.TerminalRequest{TerminalID: ids[0], Data: bad})); got.Type != protocol.Error {
t.Fatalf("input %q = %+v", bad[:min(len(bad), 4)], got)
}
}
terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalClose, "close", protocol.TerminalRequest{TerminalID: ids[0]}))
if got := terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalOpen, "again", protocol.TerminalRequest{})); got.Terminal == nil {
t.Fatalf("open after close = %+v", got)
}
}