| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "os" |
| 10 | "os/exec" |
| 11 | "runtime" |
| 12 | "strings" |
| 13 | "sync" |
| 14 | "testing" |
| 15 | "time" |
| 16 | ) |
| 17 | |
| 18 | func (m *terminalManager) start(cmd *exec.Cmd, workspace, kind string) (*terminalSession, error) { |
| 19 | return m.startSession(cmd, workspace, kind, claudeSelection{}, nil) |
| 20 | } |
| 21 | |
| 22 | |
| 23 | func TestTerminalServiceChild(t *testing.T) { |
| 24 | if os.Getenv("CAGE_TERMINAL_SERVICE_CHILD") != "1" { |
| 25 | return |
| 26 | } |
| 27 | fmt.Println("terminal-ready") |
| 28 | if os.Getenv("CAGE_TERMINAL_SERVICE_MODE") == "blocked-input" { |
| 29 | time.Sleep(24 * time.Hour) |
| 30 | os.Exit(0) |
| 31 | } |
| 32 | input := bufio.NewScanner(os.Stdin) |
| 33 | for input.Scan() { |
| 34 | line := input.Text() |
| 35 | fmt.Println("child:" + line) |
| 36 | if line == "exit" { |
| 37 | os.Exit(0) |
| 38 | } |
| 39 | } |
| 40 | os.Exit(0) |
| 41 | } |
| 42 | |
| 43 | func terminalChildCommand(mode string) *exec.Cmd { |
| 44 | cmd := exec.Command(os.Args[0], "-test.run=^TestTerminalServiceChild$") |
| 45 | cmd.Env = append(os.Environ(), "CAGE_TERMINAL_SERVICE_CHILD=1", "CAGE_TERMINAL_SERVICE_MODE="+mode) |
| 46 | return cmd |
| 47 | } |
| 48 | |
| 49 | func terminalInputLine(text string) string { |
| 50 | if runtime.GOOS == "windows" { |
| 51 | return text + "\r" |
| 52 | } |
| 53 | return text + "\n" |
| 54 | } |
| 55 | |
| 56 | func awaitTerminalSignal(t *testing.T, done <-chan struct{}) { |
| 57 | t.Helper() |
| 58 | select { |
| 59 | case <-done: |
| 60 | case <-time.After(10 * time.Second): |
| 61 | t.Fatal("terminal did not finish") |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | func readTerminalUntil(t *testing.T, sub *terminalSubscription, needle string) string { |
| 66 | t.Helper() |
| 67 | text := string(sub.History) |
| 68 | sub.History = nil |
| 69 | deadline := time.After(10 * time.Second) |
| 70 | for !strings.Contains(text, needle) { |
| 71 | select { |
| 72 | case chunk, ok := <-sub.Output: |
| 73 | if !ok { |
| 74 | t.Fatalf("terminal ended before %q: %q", needle, text) |
| 75 | } |
| 76 | text += string(chunk) |
| 77 | case <-deadline: |
| 78 | t.Fatalf("terminal did not produce %q: %q", needle, text) |
| 79 | } |
| 80 | } |
| 81 | return text |
| 82 | } |
| 83 | |
| 84 | func TestTerminalServiceReconnectKeepsRealProcess(t *testing.T) { |
| 85 | var manager terminalManager |
| 86 | t.Cleanup(manager.close) |
| 87 | session, err := manager.start(terminalChildCommand("echo"), "/project", "shell") |
| 88 | if err != nil { |
| 89 | t.Fatal(err) |
| 90 | } |
| 91 | first := session.subscribe() |
| 92 | readTerminalUntil(t, first, "terminal-ready") |
| 93 | if _, err := io.WriteString(session.file, terminalInputLine("one")); err != nil { |
| 94 | t.Fatal(err) |
| 95 | } |
| 96 | readTerminalUntil(t, first, "child:one") |
| 97 | first.Close() |
| 98 | if !manager.hasLive() { |
| 99 | t.Fatal("detaching viewer ended terminal process") |
| 100 | } |
| 101 | if _, err := io.WriteString(session.file, terminalInputLine("two")); err != nil { |
| 102 | t.Fatal(err) |
| 103 | } |
| 104 | second := session.subscribe() |
| 105 | defer second.Close() |
| 106 | text := readTerminalUntil(t, second, "child:two") |
| 107 | if !strings.Contains(text, "child:one") { |
| 108 | t.Fatalf("reconnection lost history: %q", text) |
| 109 | } |
| 110 | if _, err := io.WriteString(session.file, terminalInputLine("exit")); err != nil { |
| 111 | t.Fatal(err) |
| 112 | } |
| 113 | awaitTerminalSignal(t, session.done) |
| 114 | if manager.hasLive() || !session.summary()["closed"].(bool) { |
| 115 | t.Fatal("process exit was not published") |
| 116 | } |
| 117 | if err := session.file.Wait(); err != nil { |
| 118 | t.Fatalf("child was killed instead of exiting normally: %v", err) |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | func TestTerminalCloseUnblocksRealPTYInput(t *testing.T) { |
| 123 | var manager terminalManager |
| 124 | t.Cleanup(manager.close) |
| 125 | session, err := manager.start(terminalChildCommand("blocked-input"), "/project", "shell") |
| 126 | if err != nil { |
| 127 | t.Fatal(err) |
| 128 | } |
| 129 | sub := session.subscribe() |
| 130 | defer sub.Close() |
| 131 | readTerminalUntil(t, sub, "terminal-ready") |
| 132 | if err := session.file.Resize(120, 40); err != nil { |
| 133 | t.Fatal(err) |
| 134 | } |
| 135 | writeStarted, writeDone := make(chan struct{}), make(chan struct{}) |
| 136 | go func() { |
| 137 | close(writeStarted) |
| 138 | _, _ = io.WriteString(session.file, strings.Repeat("input\n", 1<<20)) |
| 139 | close(writeDone) |
| 140 | }() |
| 141 | awaitTerminalSignal(t, writeStarted) |
| 142 | select { |
| 143 | case <-writeDone: |
| 144 | t.Fatal("PTY input unexpectedly drained without a reader") |
| 145 | case <-time.After(20 * time.Millisecond): |
| 146 | } |
| 147 | closed := make(chan struct{}) |
| 148 | go func() { manager.close(); close(closed) }() |
| 149 | awaitTerminalSignal(t, closed) |
| 150 | awaitTerminalSignal(t, writeDone) |
| 151 | awaitTerminalSignal(t, session.done) |
| 152 | if manager.hasLive() { |
| 153 | t.Fatal("close returned while terminal was live") |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | func TestTerminalManagerClosesConcurrentCreation(t *testing.T) { |
| 158 | var manager terminalManager |
| 159 | t.Cleanup(manager.close) |
| 160 | begin, created, closed := make(chan struct{}), make(chan struct{}), make(chan struct{}) |
| 161 | var session *terminalSession |
| 162 | var createErr error |
| 163 | go func() { |
| 164 | <-begin |
| 165 | session, createErr = manager.start(terminalChildCommand("blocked-input"), "/project", "shell") |
| 166 | close(created) |
| 167 | }() |
| 168 | go func() { <-begin; manager.close(); close(closed) }() |
| 169 | close(begin) |
| 170 | awaitTerminalSignal(t, created) |
| 171 | awaitTerminalSignal(t, closed) |
| 172 | if createErr != nil && !errors.Is(createErr, errTerminalsClosed) { |
| 173 | t.Fatal(createErr) |
| 174 | } |
| 175 | if session != nil { |
| 176 | awaitTerminalSignal(t, session.done) |
| 177 | } |
| 178 | if manager.hasLive() { |
| 179 | t.Fatal("concurrent create published a live session after close") |
| 180 | } |
| 181 | if _, err := manager.start(terminalChildCommand("echo"), "", "shell"); !errors.Is(err, errTerminalsClosed) { |
| 182 | t.Fatalf("closed manager accepted a process: %v", err) |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | func TestTerminalManagerStopAllowsLaterTerminals(t *testing.T) { |
| 187 | var manager terminalManager |
| 188 | t.Cleanup(manager.close) |
| 189 | first, err := manager.start(terminalChildCommand("blocked-input"), "/first", "shell") |
| 190 | if err != nil { |
| 191 | t.Fatal(err) |
| 192 | } |
| 193 | manager.closeAll() |
| 194 | awaitTerminalSignal(t, first.done) |
| 195 | if manager.get(first.id) != first || manager.hasLive() { |
| 196 | t.Fatal("stop discarded closed history or kept process alive") |
| 197 | } |
| 198 | second, err := manager.start(terminalChildCommand("blocked-input"), "/second", "claude") |
| 199 | if err != nil { |
| 200 | t.Fatal(err) |
| 201 | } |
| 202 | if second.title != "Claude 2" { |
| 203 | t.Fatalf("terminal numbering reset: %s", second.title) |
| 204 | } |
| 205 | manager.remove(second.id) |
| 206 | awaitTerminalSignal(t, second.done) |
| 207 | if manager.get(second.id) != nil { |
| 208 | t.Fatal("removed terminal remained visible") |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | type controlledTerminal struct { |
| 213 | reader *io.PipeReader |
| 214 | writer *io.PipeWriter |
| 215 | killed chan struct{} |
| 216 | waitStarted chan struct{} |
| 217 | waitRelease chan struct{} |
| 218 | killOnce sync.Once |
| 219 | } |
| 220 | |
| 221 | func newControlledSession() (*terminalSession, *controlledTerminal) { |
| 222 | reader, writer := io.Pipe() |
| 223 | file := &controlledTerminal{reader: reader, writer: writer, killed: make(chan struct{}), waitStarted: make(chan struct{}), waitRelease: make(chan struct{})} |
| 224 | session := newTerminalSession(file) |
| 225 | go session.run() |
| 226 | return session, file |
| 227 | } |
| 228 | func (f *controlledTerminal) Read(data []byte) (int, error) { return f.reader.Read(data) } |
| 229 | func (f *controlledTerminal) Write(data []byte) (int, error) { return len(data), nil } |
| 230 | func (f *controlledTerminal) Resize(uint16, uint16) error { return nil } |
| 231 | func (f *controlledTerminal) Kill() error { f.killOnce.Do(func() { close(f.killed) }); return nil } |
| 232 | func (f *controlledTerminal) Wait() error { close(f.waitStarted); <-f.waitRelease; return nil } |
| 233 | func (f *controlledTerminal) Close() error { _ = f.writer.Close(); return f.reader.Close() } |
| 234 | |
| 235 | func TestTerminalEOFReapsProcessBeforeSessionCompletes(t *testing.T) { |
| 236 | session, file := newControlledSession() |
| 237 | sub := session.subscribe() |
| 238 | _ = file.writer.Close() |
| 239 | awaitTerminalSignal(t, file.killed) |
| 240 | awaitTerminalSignal(t, file.waitStarted) |
| 241 | select { |
| 242 | case <-session.done: |
| 243 | t.Fatal("EOF completed session before process was reaped") |
| 244 | default: |
| 245 | } |
| 246 | closed := make(chan struct{}) |
| 247 | go func() { session.close(); close(closed) }() |
| 248 | select { |
| 249 | case <-closed: |
| 250 | t.Fatal("close returned before process Wait") |
| 251 | default: |
| 252 | } |
| 253 | close(file.waitRelease) |
| 254 | awaitTerminalSignal(t, closed) |
| 255 | if _, ok := <-sub.Output; ok { |
| 256 | t.Fatal("session completion did not close subscription") |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | func TestTerminalSlowSubscriberDoesNotBlockOutput(t *testing.T) { |
| 261 | session, file := newControlledSession() |
| 262 | t.Cleanup(func() { close(file.waitRelease); session.close() }) |
| 263 | slow := session.subscribe() |
| 264 | fast := session.subscribe() |
| 265 | defer fast.Close() |
| 266 | for i := 0; i < 66; i++ { |
| 267 | chunk := fmt.Sprintf("output-%02d\n", i) |
| 268 | if _, err := io.WriteString(file.writer, chunk); err != nil { |
| 269 | t.Fatal(err) |
| 270 | } |
| 271 | readTerminalUntil(t, fast, chunk) |
| 272 | } |
| 273 | count := 0 |
| 274 | for range slow.Output { |
| 275 | count++ |
| 276 | } |
| 277 | if count != 64 { |
| 278 | t.Fatalf("slow subscriber retained %d chunks", count) |
| 279 | } |
| 280 | fast.Close() |
| 281 | if session.summary()["closed"].(bool) { |
| 282 | t.Fatal("subscription closure ended session") |
| 283 | } |
| 284 | reconnected := session.subscribe() |
| 285 | defer reconnected.Close() |
| 286 | if !strings.Contains(string(reconnected.History), "output-65") { |
| 287 | t.Fatal("slow client prevented recording terminal history") |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | func TestTerminalQueuedInputKeepsAdmissionOrder(t *testing.T) { |
| 292 | var manager terminalManager |
| 293 | t.Cleanup(manager.close) |
| 294 | session, err := manager.start(terminalChildCommand("echo"), "/project", "shell") |
| 295 | if err != nil { |
| 296 | t.Fatal(err) |
| 297 | } |
| 298 | sub := session.subscribe() |
| 299 | defer sub.Close() |
| 300 | readTerminalUntil(t, sub, "terminal-ready") |
| 301 | for _, line := range []string{"first", "second", "third", "exit"} { |
| 302 | if err := session.enqueueInput(context.Background(), terminalInputLine(line)); err != nil { |
| 303 | t.Fatal(err) |
| 304 | } |
| 305 | } |
| 306 | awaitTerminalSignal(t, session.done) |
| 307 | reconnected := session.subscribe() |
| 308 | defer reconnected.Close() |
| 309 | text := string(reconnected.History) |
| 310 | previous := -1 |
| 311 | for _, line := range []string{"first", "second", "third", "exit"} { |
| 312 | index := strings.Index(text, "child:"+line) |
| 313 | if index <= previous { |
| 314 | t.Fatalf("queued input lost or reordered %s: %q", line, text) |
| 315 | } |
| 316 | previous = index |
| 317 | } |
| 318 | } |