| 1 | //go:build e2e |
| 2 | |
| 3 | package e2e |
| 4 | |
| 5 | import ( |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "regexp" |
| 10 | "strings" |
| 11 | "syscall" |
| 12 | "testing" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | // newCoordinatorSession runs the real `klaus new --backend kind` with a stub |
| 17 | // coordinator that saves its system prompt and exits, points the harness at |
| 18 | // the new session, and returns the prompt. |
| 19 | func (h *Harness) newCoordinatorSession(kind string) string { |
| 20 | h.t.Helper() |
| 21 | promptFile := filepath.Join(h.E2EDir, kind+".prompt") |
| 22 | // Claude takes the prompt in --append-system-prompt, agy in |
| 23 | // --prompt-interactive, Codex in -c developer_instructions=. |
| 24 | h.WriteStub(kind, fmt.Sprintf(`#!/bin/sh |
| 25 | while [ $# -gt 0 ]; do |
| 26 | case "$1" in |
| 27 | --append-system-prompt|--prompt-interactive) printf '%%s' "$2" > %[1]q; shift ;; |
| 28 | developer_instructions=*) printf '%%s' "$1" > %[1]q ;; |
| 29 | esac |
| 30 | shift |
| 31 | done |
| 32 | `, promptFile)) |
| 33 | before := map[string]bool{} |
| 34 | if _, err := os.Stat(filepath.Join(h.Home, ".klaus", "sessions")); err == nil { |
| 35 | for _, id := range h.sessionIDs() { |
| 36 | before[id] = true |
| 37 | } |
| 38 | } |
| 39 | res := h.RunKlausIn(h.E2EDir, "new", "--backend", kind) |
| 40 | if res.ExitCode != 0 { |
| 41 | h.t.Fatalf("klaus new --backend %s exited %d\nstdout:\n%s\nstderr:\n%s", kind, res.ExitCode, res.Stdout, res.Stderr) |
| 42 | } |
| 43 | for _, id := range h.sessionIDs() { |
| 44 | if !before[id] { |
| 45 | h.SessionID = id |
| 46 | } |
| 47 | } |
| 48 | if before[h.SessionID] { |
| 49 | h.t.Fatalf("klaus new made no session (sessions: %v)", h.sessionIDs()) |
| 50 | } |
| 51 | prompt, err := os.ReadFile(promptFile) |
| 52 | if err != nil { |
| 53 | h.t.Fatalf("the %s coordinator got no prompt: %v", kind, err) |
| 54 | } |
| 55 | return string(prompt) |
| 56 | } |
| 57 | |
| 58 | func (h *Harness) eventsFile() string { |
| 59 | return filepath.Join(h.Home, ".klaus", "sessions", h.SessionID, "events.jsonl") |
| 60 | } |
| 61 | |
| 62 | // emitMerged appends a pr:merged event for PR n to the session's event log |
| 63 | // through the real binary. |
| 64 | func (h *Harness) emitMerged(n int) { |
| 65 | h.t.Helper() |
| 66 | res := h.RunKlaus("_event", "--run-id", fmt.Sprint(n), "--type", "pr:merged", "--data", fmt.Sprintf(`{"pr_number":"%d"}`, n)) |
| 67 | if res.ExitCode != 0 { |
| 68 | h.t.Fatalf("klaus _event exited %d: %s%s", res.ExitCode, res.Stdout, res.Stderr) |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | // exited reports whether p has exited. |
| 73 | func (p *klausProcess) exited() bool { |
| 74 | select { |
| 75 | case <-p.done: |
| 76 | return true |
| 77 | default: |
| 78 | return false |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | // waitOpened waits until p has path open, which a streaming watch does just |
| 83 | // before it seeks to the end of the file and starts following it. |
| 84 | func (p *klausProcess) waitOpened(path string) { |
| 85 | p.t.Helper() |
| 86 | real, err := filepath.EvalSymlinks(path) |
| 87 | if err != nil { |
| 88 | p.t.Fatal(err) |
| 89 | } |
| 90 | fdDir := fmt.Sprintf("/proc/%d/fd", p.cmd.Process.Pid) |
| 91 | p.waitFor(func() bool { |
| 92 | fds, _ := os.ReadDir(fdDir) |
| 93 | for _, fd := range fds { |
| 94 | if target, _ := os.Readlink(filepath.Join(fdDir, fd.Name())); target == real { |
| 95 | return true |
| 96 | } |
| 97 | } |
| 98 | return false |
| 99 | }, "open "+path) |
| 100 | time.Sleep(200 * time.Millisecond) |
| 101 | } |
| 102 | |
| 103 | // stop sends p SIGTERM and returns its outcome. |
| 104 | func (p *klausProcess) stop() RunResult { |
| 105 | p.t.Helper() |
| 106 | if err := p.cmd.Process.Signal(syscall.SIGTERM); err != nil { |
| 107 | p.t.Fatal(err) |
| 108 | } |
| 109 | return p.wait() |
| 110 | } |
| 111 | |
| 112 | // watchOnce runs a `klaus watch --once` command line as printed on a next: |
| 113 | // line, waits up to 30s for it to exit 0, and returns the PR numbers of the |
| 114 | // pr:merged events it printed and the command on its next: line. |
| 115 | func (h *Harness) watchOnce(cmdline string) (prs []string, next string) { |
| 116 | h.t.Helper() |
| 117 | p := h.startKlaus(nil, strings.Fields(strings.TrimPrefix(cmdline, "valley flow "))...) |
| 118 | p.waitFor(p.exited, "exit") |
| 119 | res := p.wait() |
| 120 | if res.ExitCode != 0 { |
| 121 | h.t.Fatalf("%s exited %d\nstdout:\n%s\nstderr:\n%s", cmdline, res.ExitCode, res.Stdout, res.Stderr) |
| 122 | } |
| 123 | return parseWatchBatch(h.t, cmdline, res.Stdout) |
| 124 | } |
| 125 | |
| 126 | var mergedLine = regexp.MustCompile(`pr:merged +PR #(\d+) merged$`) |
| 127 | |
| 128 | func parseWatchBatch(t *testing.T, cmdline, out string) (prs []string, next string) { |
| 129 | t.Helper() |
| 130 | lines := strings.Split(strings.TrimSuffix(out, "\n"), "\n") |
| 131 | last := lines[len(lines)-1] |
| 132 | if !strings.HasPrefix(last, "next: valley flow watch --once --after ") { |
| 133 | t.Fatalf("%s: last line %q is not a next: line\n%s", cmdline, last, out) |
| 134 | } |
| 135 | for _, l := range lines[:len(lines)-1] { |
| 136 | m := mergedLine.FindStringSubmatch(l) |
| 137 | if m == nil { |
| 138 | t.Fatalf("%s printed %q, not a pr:merged event\n%s", cmdline, l, out) |
| 139 | } |
| 140 | prs = append(prs, m[1]) |
| 141 | } |
| 142 | return prs, strings.TrimPrefix(last, "next: ") |
| 143 | } |
| 144 | |
| 145 | // TestOneShotWatchesDeliverEachEventOnce follows one-shot watches with the |
| 146 | // real binary, each started from the last one's next: line: an event that |
| 147 | // lands before the first watch starts, two that land between two watches, |
| 148 | // and one that lands while a watch waits are each printed once. |
| 149 | func TestOneShotWatchesDeliverEachEventOnce(t *testing.T) { |
| 150 | t.Parallel() |
| 151 | h := NewHarness(t) |
| 152 | h.newCoordinatorSession("agy") |
| 153 | |
| 154 | // No watch is running yet when PR 1 merges. |
| 155 | h.emitMerged(1) |
| 156 | prs, next := h.watchOnce("valley flow watch --once --after 0") |
| 157 | if strings.Join(prs, " ") != "1" { |
| 158 | t.Fatalf("the first watch printed PRs %v, want [1]", prs) |
| 159 | } |
| 160 | |
| 161 | // Two events between two watches: the next one prints both, and not PR 1. |
| 162 | h.emitMerged(2) |
| 163 | h.emitMerged(3) |
| 164 | prs, next = h.watchOnce(next) |
| 165 | if strings.Join(prs, " ") != "2 3" { |
| 166 | t.Fatalf("the second watch printed PRs %v, want [2 3]", prs) |
| 167 | } |
| 168 | |
| 169 | // The third waits: it has nothing to print until PR 4 merges. |
| 170 | p := h.startKlaus(nil, strings.Fields(strings.TrimPrefix(next, "valley flow "))...) |
| 171 | time.Sleep(time.Second) |
| 172 | if p.exited() { |
| 173 | res := p.wait() |
| 174 | t.Fatalf("%s exited before any new event\nstdout:\n%s\nstderr:\n%s", next, res.Stdout, res.Stderr) |
| 175 | } |
| 176 | h.emitMerged(4) |
| 177 | p.waitFor(p.exited, "exit") |
| 178 | res := p.wait() |
| 179 | if res.ExitCode != 0 { |
| 180 | t.Fatalf("%s exited %d: %s%s", next, res.ExitCode, res.Stdout, res.Stderr) |
| 181 | } |
| 182 | prs, next = parseWatchBatch(t, next, res.Stdout) |
| 183 | if strings.Join(prs, " ") != "4" { |
| 184 | t.Fatalf("the third watch printed PRs %v, want [4]", prs) |
| 185 | } |
| 186 | |
| 187 | // Its cursor is the end of the stream: a watch from it waits too, and |
| 188 | // interrupted, says to start the same command again. |
| 189 | p = h.startKlaus(nil, strings.Fields(strings.TrimPrefix(next, "valley flow "))...) |
| 190 | time.Sleep(500 * time.Millisecond) |
| 191 | res = p.stop() |
| 192 | if res.ExitCode != 0 || res.Stdout != "next: "+next+"\n" { |
| 193 | t.Fatalf("interrupted, %s exited %d with %q, want just %q", next, res.ExitCode, res.Stdout, "next: "+next+"\n") |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | // TestWatchBeforeTheFirstEvent: a coordinator arms klaus watch as its session |
| 198 | // starts, before any event. klaus new makes the events file, and a watch |
| 199 | // started then prints the first event (#345). |
| 200 | func TestWatchBeforeTheFirstEvent(t *testing.T) { |
| 201 | t.Parallel() |
| 202 | h := NewHarness(t) |
| 203 | h.newCoordinatorSession("claude") |
| 204 | if info, err := os.Stat(h.eventsFile()); err != nil || info.Size() != 0 { |
| 205 | t.Fatalf("klaus new should leave an empty events file: %v %v", info, err) |
| 206 | } |
| 207 | |
| 208 | w := h.startKlaus(nil, "watch") |
| 209 | w.waitOpened(h.eventsFile()) |
| 210 | h.emitMerged(7) |
| 211 | w.waitFor(func() bool { |
| 212 | out, _ := w.output() |
| 213 | return strings.Contains(out, "PR #7 merged") |
| 214 | }, "print PR #7's merge") |
| 215 | if res := w.stop(); res.ExitCode != 0 { |
| 216 | t.Fatalf("watch exited %d after SIGTERM: %s", res.ExitCode, res.Stderr) |
| 217 | } |
| 218 | |
| 219 | // Resuming a session that has no events file, as one from an older |
| 220 | // klaus, makes it too. |
| 221 | if err := os.Remove(h.eventsFile()); err != nil { |
| 222 | t.Fatal(err) |
| 223 | } |
| 224 | if res := h.RunKlausIn(h.E2EDir, "session"); res.ExitCode != 0 { |
| 225 | t.Fatalf("klaus session exited %d: %s%s", res.ExitCode, res.Stdout, res.Stderr) |
| 226 | } |
| 227 | if _, err := os.Stat(h.eventsFile()); err != nil { |
| 228 | t.Fatalf("resuming the session should make the events file: %v", err) |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | // TestWatchWaitsForTheEventsFile: in a session with no events file yet, as |
| 233 | // one from an older klaus, watch waits for the file as long as the session |
| 234 | // exists, well past the 10s it used to give up after, and prints the event |
| 235 | // that makes the file. An unknown session ID fails at once. |
| 236 | func TestWatchWaitsForTheEventsFile(t *testing.T) { |
| 237 | t.Parallel() |
| 238 | h := NewHarness(t) |
| 239 | h.newCoordinatorSession("claude") |
| 240 | if err := os.Remove(h.eventsFile()); err != nil { |
| 241 | t.Fatal(err) |
| 242 | } |
| 243 | |
| 244 | w := h.startKlaus(nil, "watch") |
| 245 | once := h.startKlaus(nil, "watch", "--once") |
| 246 | time.Sleep(11 * time.Second) |
| 247 | for _, p := range []*klausProcess{w, once} { |
| 248 | if p.exited() { |
| 249 | res := p.wait() |
| 250 | t.Fatalf("klaus %v gave up waiting for the events file: exit %d\n%s%s", p.cmd.Args[1:], res.ExitCode, res.Stdout, res.Stderr) |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | h.emitMerged(8) |
| 255 | w.waitFor(func() bool { |
| 256 | out, _ := w.output() |
| 257 | return strings.Contains(out, "PR #8 merged") |
| 258 | }, "print PR #8's merge") |
| 259 | if res := w.stop(); res.ExitCode != 0 { |
| 260 | t.Fatalf("watch exited %d after SIGTERM: %s", res.ExitCode, res.Stderr) |
| 261 | } |
| 262 | once.waitFor(once.exited, "exit") |
| 263 | res := once.wait() |
| 264 | if prs, _ := parseWatchBatch(t, "klaus watch --once", res.Stdout); res.ExitCode != 0 || strings.Join(prs, " ") != "8" { |
| 265 | t.Fatalf("watch --once exited %d with PRs %v, want 0 with [8]\n%s%s", res.ExitCode, prs, res.Stdout, res.Stderr) |
| 266 | } |
| 267 | |
| 268 | start := time.Now() |
| 269 | res = h.RunKlaus("watch", "--session-id", "session-unknown") |
| 270 | if res.ExitCode == 0 || !strings.Contains(res.Stderr, "unknown session session-unknown") || time.Since(start) > 5*time.Second { |
| 271 | t.Fatalf("watch on an unknown session exited %d after %s: %s", res.ExitCode, time.Since(start), res.Stderr) |
| 272 | } |
| 273 | } |