0963a071d0
Machine terminals no longer skip output for live viewers. Each connection's subscription is a cursor into the 1 MiB retained tail, drained by the connection's writer as soon as the PTY reader writes (no 50 ms tick; a streaming frame gathers for at most 2 ms). A subscription opened with flow: true gets window (256 KiB) in its reply and acknowledges drawn output with terminal_ack; while one is full the reader stops reading the PTY, so the program waits. A subscription full for 3 s without acking stops holding the terminal and later sees a gap; a gone connection drops its subscriptions. Clients that never ask for flow keep the old pacing (newest 64 KiB per 50 ms). terminal_open/terminal_output replies precede the frames that follow them, which start exactly at the reply's output_end. Chat shell runs share the buffer code: output is pushed as it arrives, oldest first, while the chat's watchers keep short queues; 256 KiB unpushed stops the reader, and watchers behind for 3 s get the old pacing. The app asks for flow, takes offsets from the server (frame end, reply output_end) instead of re-encoded text length, acks per quarter window, and writes replays and bursts into the emulator in slices that yield to the event loop (ChatShellTerminalFeed, shared with chat shells). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
181 lines
7.0 KiB
Go
181 lines
7.0 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"))
|
|
// The oldest retained bytes go first; the dropped ones are a gap.
|
|
text, offset, end, ok := out.pending(3, false)
|
|
if !ok || text != "ghi" || offset != 8 || end != 11 {
|
|
t.Fatalf("bounded chunk = %q %d %d", text, offset, end)
|
|
}
|
|
if text, offset, end, ok := out.pending(3, false); !ok || text != "j" || offset != 11 || end != 12 {
|
|
t.Fatalf("next 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)
|
|
}
|
|
}
|
|
|
|
// A chunk never ends inside a character, whether a size bound or a limit
|
|
// (a flow window) cuts it; invalid bytes keep their exact offsets.
|
|
func TestChatShellOutputChunkBounds(t *testing.T) {
|
|
out := newChatShellOutput(1 << 10)
|
|
out.write([]byte("a\xe2\x82\xacb\xff\xfec"))
|
|
if text, offset, end, ok := out.chunk(0, 3, 64, false); !ok || text != "a" || offset != 0 || end != 1 {
|
|
t.Fatalf("limit inside the euro sign = %q %d %d", text, offset, end)
|
|
}
|
|
if _, _, _, ok := out.chunk(1, 3, 64, false); ok {
|
|
t.Fatal("a chunk of only part of a character was sent")
|
|
}
|
|
if text, offset, end, ok := out.chunk(0, 9, 3, false); !ok || text != "a" || end != 1 || offset != 0 {
|
|
t.Fatalf("size bound inside the euro sign = %q %d %d", text, offset, end)
|
|
}
|
|
text, offset, end, ok := out.chunk(1, 9, 64, false)
|
|
if !ok || text != "\u20acb\ufffdc" || offset != 1 || end != 8 {
|
|
t.Fatalf("rest = %q %d %d", text, offset, end)
|
|
}
|
|
out.skipUnemitted(2)
|
|
if text, offset, end, ok := out.pending(64, false); !ok || text != "\ufffdc" || offset != 6 || end != 8 {
|
|
t.Fatalf("after skipping = %q %d %d", text, offset, end)
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|