Files
pipelines/internal/server/chat_shell_runner_test.go
T
alan 2332143e5b Fit chat terminals to their output, keep pastes and keys in the terminal
Finished terminals are sized synchronously from their rows at the view's
width (the post-frame fit made the transcript re-anchor forever); blank rows
xterm.dart keeps when rewrapping are dropped; desktop typing uses key events;
the composer leaves Cmd/Ctrl-V to a focused terminal; Ctrl-A reaches the
process. The probe fixture gains coloured terminal runs and an interactive
login. Notes record behaviour, protocol, security and verification.
2026-11-09 20:51:59 +00:00

153 lines
5.7 KiB
Go

package server
import (
"context"
"strings"
"sync"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// shellFrames records every frame a test runner publishes.
type shellFrames struct {
mu sync.Mutex
frames []protocol.ChatShellRunEventFrame
}
func (f *shellFrames) add(_ string, frame protocol.ChatShellRunEventFrame) {
f.mu.Lock()
f.frames = append(f.frames, frame)
f.mu.Unlock()
}
func (f *shellFrames) final(runID string) *protocol.ChatShellRunRecord {
f.mu.Lock()
defer f.mu.Unlock()
for _, frame := range f.frames {
if frame.RunID == runID && frame.Run != nil && frame.Run.Status != protocol.ChatShellRunRunning {
return frame.Run
}
}
return nil
}
func testShellRunner(t *testing.T, ctx context.Context) (*chatShellRunner, *shellFrames) {
t.Helper()
frames := &shellFrames{}
runner := newChatShellRunner(ctx, newOperatorStore(t), frames.add)
runner.grace = 200 * time.Millisecond
runner.flush = 10 * time.Millisecond
return runner, frames
}
func TestChatShellStopKillsAfterGrace(t *testing.T) {
runner, frames := testShellRunner(t, context.Background())
run, err := runner.Start(context.Background(), "ses_1", t.TempDir(), `trap "" INT; echo ready; while :; do sleep 0.05; done`, 0, 0)
if err != nil {
t.Fatal(err)
}
// The trap must be in place before the stop: wait for the command's
// output rather than a fixed delay (a login shell can be slow to start).
for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(10 * time.Millisecond) {
if record, err := runner.Read(context.Background(), "ses_1", run.ID); err == nil && strings.Contains(record.Output, "ready") {
break
}
if time.Now().After(deadline) {
t.Fatal("the command never printed ready")
}
}
if _, err := runner.Stop("ses_2", run.ID); err == nil {
t.Fatal("another session stopped this run")
}
if _, err := runner.Stop("ses_1", run.ID); err != nil {
t.Fatal(err)
}
runner.Wait()
final := frames.final(run.ID)
if final == nil || final.Status != protocol.ChatShellRunStopped || final.Signal != "killed" || final.DurationMS < 200 {
t.Fatalf("final = %+v", final)
}
}
func TestChatShellRetainsBoundedTail(t *testing.T) {
runner, frames := testShellRunner(t, context.Background())
total := protocol.ChatShellRunRetained + 200_000
run, err := runner.Start(context.Background(), "ses_1", t.TempDir(), `head -c 1248576 /dev/zero | tr '\0' a; printf END`, 0, 0)
if err != nil {
t.Fatal(err)
}
runner.Wait()
stored, err := runner.Read(context.Background(), "ses_1", run.ID)
if err != nil {
t.Fatal(err)
}
if stored.OutputBytes != int64(total+3) || len(stored.Output) != protocol.ChatShellRunRetained || !stored.Truncated || stored.OutputStart != stored.OutputBytes-int64(protocol.ChatShellRunRetained) || !strings.HasSuffix(stored.Output, "aEND") {
t.Fatalf("stored = bytes %d len %d start %d truncated %v", stored.OutputBytes, len(stored.Output), stored.OutputStart, stored.Truncated)
}
list, err := runner.List(context.Background(), "ses_1")
if err != nil || len(list) != 1 || len(list[0].Output) != protocol.ChatShellRunListOutput || list[0].OutputStart != stored.OutputBytes-protocol.ChatShellRunListOutput {
t.Fatalf("list = %d runs, err %v", len(list), err)
}
frames.mu.Lock()
defer frames.mu.Unlock()
for _, frame := range frames.frames {
if len(frame.Output) > protocol.ChatShellRunChunkLimit {
t.Fatalf("an output frame carried %d bytes", len(frame.Output))
}
}
}
func TestChatShellShutdownAndRestartInterrupt(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
runner, frames := testShellRunner(t, ctx)
run, err := runner.Start(context.Background(), "ses_1", t.TempDir(), "sleep 30", 0, 0)
if err != nil {
t.Fatal(err)
}
cancel()
runner.Wait()
if final := frames.final(run.ID); final == nil || final.Status != protocol.ChatShellRunInterrupted {
t.Fatalf("shutdown final = %+v", final)
}
if _, err := runner.Start(context.Background(), "ses_1", t.TempDir(), "true", 0, 0); err == nil {
t.Fatal("a stopping server started a command")
}
// A record a crashed process left running is interrupted on start.
store := runner.store
if err := store.SaveChatShellRun(context.Background(), protocol.ChatShellRunRecord{ID: "run_left", SessionID: "ses_1", Command: "sleep 1", Directory: "/", Status: protocol.ChatShellRunRunning, StartedAt: 1}, 0); err != nil {
t.Fatal(err)
}
next := newChatShellRunner(context.Background(), store, nil)
next.recover(context.Background())
left, err := next.Read(context.Background(), "ses_1", "run_left")
if err != nil || left.Status != protocol.ChatShellRunInterrupted || left.Error != chatShellInterruptedReason {
t.Fatalf("recovered = %+v, %v", left, err)
}
}
func TestChatShellOutputKeepsCharactersWhole(t *testing.T) {
out := newChatShellOutput(4)
out.write([]byte("ab\xc3"))
if text, offset, end, ok := out.pending(64, false); !ok || text != "ab" || offset != 0 || end != 2 {
t.Fatalf("partial character emitted: %q %d %d", text, offset, end)
}
out.write([]byte("\xa9cdefghij"))
text, offset, end, ok := out.pending(3, false)
if !ok || text != "hij" || offset != 9 || end != 12 {
t.Fatalf("bounded chunk = %q %d %d", text, offset, end)
}
if tail, start := out.tail(6); tail != "ghij" || start != 8 {
t.Fatalf("tail = %q at %d", tail, start)
}
}
func TestChatShellSharePromptFencesOutput(t *testing.T) {
code := 1
prompt := chatShellSharePrompt(protocol.ChatShellRunRecord{Command: "cat notes.md", Directory: "/w", Status: protocol.ChatShellRunExited, ExitCode: &code, DurationMS: 1500, Output: "```go\nx\n```\n", OutputBytes: 13})
if !strings.Contains(prompt, "````text\n```go\nx\n```\n````") || !strings.Contains(prompt, "exited with status 1 after 1.5s") {
t.Fatalf("prompt = %q", prompt)
}
}