//go:build darwin || linux package server import ( "context" "fmt" "strings" "testing" "time" "github.com/coder/websocket" "git.a-wan.net/alan/pipelines/internal/protocol" ) // readTerminalText reads conn's output frames of id, from wherever its // subscription started, until the text contains want. func readTerminalText(t *testing.T, ctx context.Context, conn *websocket.Conn, id, want string) string { t.Helper() var seen strings.Builder for !strings.Contains(seen.String(), want) { seen.WriteString(readShellFrame(t, ctx, conn, func(m protocol.Message) bool { return m.Type == protocol.TerminalEvent && m.TerminalEvent.TerminalID == id && m.TerminalEvent.Terminal == nil }).TerminalEvent.Output) } return seen.String() } // Two clients draw one terminal: only the active client's emulator answers // reach the shell, the terminal takes the active client's size, typing or // focusing makes a client active, and when the active client leaves the // next one's size comes back. func TestTerminalTwoClientsActiveClient(t *testing.T) { terminalHome(t) ctx, _, conns := dialChatConns(t, Options{OperatorRegistry: newOperatorStore(t)}, 2) a, b := conns[0], conns[1] term := terminalReply(t, ctx, a, terminalRequest(protocol.TerminalOpen, "open", protocol.TerminalRequest{Cols: 156, Rows: 37})).Terminal terminalLogIn(t, ctx, a, term.ID) terminalReply(t, ctx, b, terminalRequest(protocol.TerminalOutput, "read", protocol.TerminalRequest{TerminalID: term.ID})) // b draws it smaller; the opener is active and keeps its size. if got := terminalReply(t, ctx, b, terminalRequest(protocol.TerminalResize, "small", protocol.TerminalRequest{TerminalID: term.ID, Cols: 121, Rows: 11})); got.Terminal == nil || got.Terminal.Cols != 156 || got.Terminal.Rows != 37 { t.Fatalf("background resize = %+v", got) } // A query both emulators answer: only the active client's answer arrives. terminalReply(t, ctx, a, terminalRequest(protocol.TerminalInput, "ask", protocol.TerminalRequest{TerminalID: term.ID, Data: "read -r ans; echo got:$ans; stty size\r"})) if got := terminalReply(t, ctx, b, terminalRequest(protocol.TerminalInput, "b-reply", protocol.TerminalRequest{TerminalID: term.ID, Data: "b-answer\r", Reply: true})); got.Type != protocol.TerminalInput { t.Fatalf("dropped reply is acknowledged: %+v", got) } terminalReply(t, ctx, a, terminalRequest(protocol.TerminalInput, "a-reply", protocol.TerminalRequest{TerminalID: term.ID, Data: "a-answer\r", Reply: true})) text := readTerminalText(t, ctx, a, term.ID, "37 156") if !strings.Contains(text, "got:a-answer") || strings.Contains(text, "b-answer") { t.Fatalf("output = %q", text) } // b types: it becomes active at its own size, before its keystrokes. terminalReply(t, ctx, b, terminalRequest(protocol.TerminalInput, "b-type", protocol.TerminalRequest{TerminalID: term.ID, Data: "stty size\r"})) readTerminalText(t, ctx, a, term.ID, "11 121") // Now a's answers are the ones dropped. terminalReply(t, ctx, a, terminalRequest(protocol.TerminalInput, "a-late", protocol.TerminalRequest{TerminalID: term.ID, Data: "echo a-late-$((1+1))\r", Reply: true})) // a focuses its terminal: active again at its size. if got := terminalReply(t, ctx, a, terminalRequest(protocol.TerminalResize, "focus", protocol.TerminalRequest{TerminalID: term.ID, Cols: 150, Rows: 40, Activate: true})); got.Terminal.Cols != 150 || got.Terminal.Rows != 40 { t.Fatalf("activate = %+v", got) } terminalReply(t, ctx, a, terminalRequest(protocol.TerminalInput, "a-type", protocol.TerminalRequest{TerminalID: term.ID, Data: "stty size\r"})) if text := readTerminalText(t, ctx, a, term.ID, "40 150"); strings.Contains(text, "a-late-2") { t.Fatalf("a background answer reached the shell: %q", text) } // a leaves: b, the next most recent, has its size back. a.Close(websocket.StatusNormalClosure, "") deadline := time.Now().Add(5 * time.Second) for { list := terminalReply(t, ctx, b, terminalRequest(protocol.TerminalList, "list", protocol.TerminalRequest{})) if len(list.Terminals) == 1 && list.Terminals[0].Cols == 121 && list.Terminals[0].Rows == 11 { break } if time.Now().After(deadline) { t.Fatalf("size after the active client left = %+v", list.Terminals) } time.Sleep(20 * time.Millisecond) } // And b's emulator answers now reach the shell. terminalReply(t, ctx, b, terminalRequest(protocol.TerminalInput, "b-answers", protocol.TerminalRequest{TerminalID: term.ID, Data: "stty size\r", Reply: true})) readTerminalText(t, ctx, b, term.ID, "11 121") } // A chat's terminal command watched by two clients follows the same policy. func TestChatShellTerminalTwoClientsActiveClient(t *testing.T) { ctx, conns, _ := shellChat(t) a, b := conns[0], conns[1] start := shellRequest(protocol.ChatShellRun, "r1", "", `read -r first; echo got:$first; read -r second; stty size; echo done`) start.ChatShellRunRequest.Cols, start.ChatShellRunRequest.Rows = 100, 30 writeChat(t, ctx, a, start) run := readShellFrame(t, ctx, a, func(m protocol.Message) bool { return m.ID == "r1" }).ChatShellRun resize := shellRequest(protocol.ChatShellResize, "size", run.ID, "") resize.ChatShellRunRequest.Cols, resize.ChatShellRunRequest.Rows = 120, 33 writeChat(t, ctx, b, resize) if got := readShellFrame(t, ctx, b, func(m protocol.Message) bool { return m.ID == "size" }); got.ChatShellRun == nil || got.ChatShellRun.Cols != 100 { t.Fatalf("background resize = %+v", got) } send := func(conn *websocket.Conn, id, data string, reply bool, cols, rows int) { t.Helper() input := shellRequest(protocol.ChatShellInput, id, run.ID, "") input.ChatShellRunRequest.Data, input.ChatShellRunRequest.Reply = data, reply input.ChatShellRunRequest.Cols, input.ChatShellRunRequest.Rows = cols, rows writeChat(t, ctx, conn, input) if got := readShellFrame(t, ctx, conn, func(m protocol.Message) bool { return m.ID == id }); got.Type != protocol.ChatShellInput { t.Fatalf("input %s = %+v", id, got) } } send(b, "b-reply", "b-answer\r", true, 0, 0) send(a, "a-reply", "a-answer\r", true, 0, 0) // b types the second line carrying the size it now draws at: it becomes // active at that size before the keystrokes are written. send(b, "b-type", "next\r", false, 90, 20) _, output := finishedShell(t, ctx, a, run.ID) if !strings.Contains(output, "got:a-answer") || strings.Contains(output, "b-answer") || !strings.Contains(output, "20 90") { t.Fatalf("output = %q", output) } } // Keystrokes take their own lane: they are answered, in order, while an // ordinary request on the same connection is still being handled. func TestTerminalInputDoesNotWaitBehindSlowRequest(t *testing.T) { store := newOperatorStore(t) gate := make(chan struct{}) broker := scriptedChat() broker.block = true broker.createGate, broker.createStarted = gate, make(chan struct{}) ctx, _, conns := dialChatConns(t, Options{Chat: broker, OperatorRegistry: store}, 1) conn := conns[0] dir := t.TempDir() if err := store.RecordOperatorSession(ctx, "ses_1", dir, "Shell", protocol.ChatSessionTagOperator); err != nil { t.Fatal(err) } writeChat(t, ctx, conn, protocol.Message{Type: protocol.ChatSubscribe, ID: "sub", ChatSubscribe: &protocol.ChatQuery{SessionID: "ses_1"}}) readShellFrame(t, ctx, conn, func(m protocol.Message) bool { return m.ID == "sub" }) run := runShell(t, ctx, conn, "r1", `for i in $(seq 1 40); do read -r line; echo "seen:$line"; done`) defer close(gate) writeChat(t, ctx, conn, protocol.Message{Type: protocol.ChatCreate, ID: "slow", ChatCreate: &protocol.ChatCreateRequest{Title: "slow", Directory: dir, OperationID: "slow-op"}}) select { case <-broker.createStarted: case <-time.After(5 * time.Second): t.Fatal("chat_create never reached the broker") } // Forty keystroke requests, written without waiting for replies. started := time.Now() for i := 1; i <= 40; i++ { input := shellRequest(protocol.ChatShellInput, fmt.Sprintf("in-%d", i), run.ID, "") input.ChatShellRunRequest.Data = fmt.Sprintf("k%02d\r", i) writeChat(t, ctx, conn, input) } var output strings.Builder replies := 0 for replies < 40 || !strings.Contains(output.String(), "seen:k40") { m := readShellFrame(t, ctx, conn, func(m protocol.Message) bool { return strings.HasPrefix(m.ID, "in-") || m.ID == "slow" || m.Type == protocol.ChatShellRunEvent && m.ChatShellRunEvent.RunID == run.ID && m.ChatShellRunEvent.Run == nil }) switch { case m.ID == "slow": t.Fatal("the slow request answered first; it should still be waiting") case m.Type == protocol.Error: t.Fatalf("input refused: %+v", m) case strings.HasPrefix(m.ID, "in-"): replies++ if m.ID != fmt.Sprintf("in-%d", replies) { t.Fatalf("reply %d is %s", replies, m.ID) } default: output.WriteString(m.ChatShellRunEvent.Output) } } t.Logf("40 keystrokes answered and echoed in %s behind a blocked request", time.Since(started)) // The shell saw them in the order they were typed. var want strings.Builder for i := 1; i <= 40; i++ { fmt.Fprintf(&want, "seen:k%02d\r\n", i) } got := output.String() var seen strings.Builder for _, line := range strings.Split(got, "\r\n") { if strings.HasPrefix(line, "seen:") { seen.WriteString(line + "\r\n") } } if seen.String() != want.String() { t.Fatalf("order = %q", seen.String()) } }