gunk-dev/the-valley

transitions_test.go

sourcecfedff357a41main's published tip history
5.9 KiB
1//go:build e2e
2
3package e2e
4
5import (
6 "bufio"
7 "encoding/json"
8 "fmt"
9 "os"
10 "path/filepath"
11 "strings"
12 "testing"
13 "time"
14
15 "the-valley/flow/internal/event"
16 "the-valley/flow/internal/run"
17)
18
19// TestDashboardReportsEachPRTransitionOnce runs the real dashboard over a
20// session like the one of 2026-10-21: three PRs merged long ago, approved
21// through klaus, and three open, approved PRs. GitHub (a gh stub) goes
22// through outages in which `gh pr view --json state` fails as on a rate
23// limit while the other queries still answer. Through reloads, outages and
24// a restart, the old PRs report nothing, and each open PR reports its
25// approval once and its merge once, including the one that merges while
26// the dashboard is down.
27func TestDashboardReportsEachPRTransitionOnce(t *testing.T) {
28 t.Parallel()
29 h := NewHarness(t)
30
31 prs := filepath.Join(h.E2EDir, "gh-prs")
32 if err := os.MkdirAll(prs, 0o755); err != nil {
33 t.Fatal(err)
34 }
35 setPR := func(n int, state string) {
36 t.Helper()
37 if err := os.WriteFile(filepath.Join(prs, fmt.Sprint(n)), []byte(state+"\n"), 0o644); err != nil {
38 t.Fatal(err)
39 }
40 }
41 down := filepath.Join(h.E2EDir, "gh-down")
42 argv := filepath.Join(h.E2EDir, "gh.argv")
43 stateCalls := filepath.Join(h.E2EDir, "gh.state-calls")
44 h.WriteStub("gh", fmt.Sprintf(`#!/usr/bin/env bash
45dir=%q
46line=$(printf '%%s' "$*" | tr '\n' ' ')
47echo "$line" >> "$dir/gh.argv"
48if [[ "$line" == *graphql* ]]; then
49 if [ -e "$dir/gh-down" ]; then
50 echo "down" >> "$dir/gh.state-calls"
51 echo "error connecting to api.github.com" >&2
52 exit 1
53 fi
54 echo "up" >> "$dir/gh.state-calls"
55 printf 'HTTP/2.0 200 OK\r\n\r\n{"data": {"repository": {'
56 sep=""
57 for f in "$dir"/gh-prs/*; do
58 n=$(basename "$f")
59 printf '%%s"pr%%s": {"state": "%%s", "mergeable": "MERGEABLE", "reviewDecision": "APPROVED", "headRefOid": "h%%s", "commits": {"nodes": [{"commit": {"statusCheckRollup": {"state": "SUCCESS"}}}]}}' "$sep" "$n" "$(cat "$f")" "$n"
60 sep=","
61 done
62 printf '}}}'
63fi
64exit 0
65`, h.E2EDir))
66
67 strPtr := func(s string) *string { return &s }
68 approved := true
69 cost := 1.0
70 states := map[int]*run.State{}
71 for i, n := range []int{101, 102, 103, 104, 105, 106} {
72 st := &run.State{
73 ID: fmt.Sprintf("20261021-0100-p%03d", n), Type: "launch", Prompt: fmt.Sprintf("pr %d", n),
74 TargetRepo: strPtr("acme/widget"), PRURL: strPtr(fmt.Sprintf("https://github.com/acme/widget/pull/%d", n)),
75 CostUSD: &cost, CreatedAt: time.Now().Add(-time.Duration(10-i) * time.Hour).Format(time.RFC3339),
76 }
77 if n <= 103 {
78 st.Approved = &approved
79 setPR(n, "MERGED")
80 } else {
81 setPR(n, "OPEN")
82 }
83 states[n] = st
84 h.SeedState(st)
85 }
86
87 countLines := func(path, substr string) int {
88 data, _ := os.ReadFile(path)
89 n := 0
90 for _, line := range strings.Split(string(data), "\n") {
91 if line != "" && strings.Contains(line, substr) {
92 n++
93 }
94 }
95 return n
96 }
97 // pass waits for the dashboard to query GitHub, up or down, then for gh
98 // to go quiet.
99 pass := func(kind string, before int) {
100 t.Helper()
101 deadline := time.Now().Add(30 * time.Second)
102 for countLines(stateCalls, kind) < before+1 {
103 if time.Now().After(deadline) {
104 t.Fatalf("no %s pass: %d queries, want %d", kind, countLines(stateCalls, kind), before+1)
105 }
106 time.Sleep(100 * time.Millisecond)
107 }
108 for last := -1; ; time.Sleep(500 * time.Millisecond) {
109 n := countLines(argv, "")
110 if n == last {
111 return
112 }
113 last = n
114 }
115 }
116 // reload rewrites a run state; the dashboard reloads the runs and asks
117 // GitHub about every PR.
118 reload := func() { h.SeedState(states[106]) }
119 outage := func() {
120 t.Helper()
121 if err := os.WriteFile(down, nil, 0o644); err != nil {
122 t.Fatal(err)
123 }
124 before := countLines(stateCalls, "down")
125 reload()
126 pass("down", before)
127 if err := os.Remove(down); err != nil {
128 t.Fatal(err)
129 }
130 before = countLines(stateCalls, "up")
131 reload()
132 pass("up", before)
133 }
134
135 prEvents := func() []string {
136 f, err := os.Open(filepath.Join(h.Home, ".klaus", "sessions", h.SessionID, "events.jsonl"))
137 if os.IsNotExist(err) {
138 return nil
139 }
140 if err != nil {
141 t.Fatal(err)
142 }
143 defer f.Close()
144 var out []string
145 sc := bufio.NewScanner(f)
146 for sc.Scan() {
147 var e event.Event
148 if json.Unmarshal(sc.Bytes(), &e) == nil && (e.Type == event.PRApproved || e.Type == event.PRMerged) {
149 out = append(out, e.Type+" #"+e.RunID)
150 }
151 }
152 return out
153 }
154 waitEvent := func(want string) {
155 t.Helper()
156 for deadline := time.Now().Add(30 * time.Second); time.Now().Before(deadline); time.Sleep(100 * time.Millisecond) {
157 for _, e := range prEvents() {
158 if e == want {
159 return
160 }
161 }
162 }
163 t.Fatalf("no %s event; PR events: %q", want, prEvents())
164 }
165 startDashboard := func() {
166 h.tmux("new-session", "-d", "-s", "dash", "-x", "120", "-y", "24", "-c", h.RepoDir,
167 "env KLAUS_SESSION_ID="+h.SessionID+" klaus dashboard")
168 }
169
170 startDashboard()
171 waitEvent("pr:approved #106")
172 reload()
173 pass("up", countLines(stateCalls, "up"))
174 outage()
175 outage()
176 setPR(104, "MERGED")
177 reload()
178 // Events are written in the order the passes are handled, so once 104's
179 // merge is in, every earlier pass has been handled.
180 waitEvent("pr:merged #104")
181
182 h.tmux("kill-session", "-t", "dash")
183 setPR(105, "MERGED")
184 startDashboard()
185 waitEvent("pr:merged #105")
186 reload()
187 pass("up", countLines(stateCalls, "up"))
188 outage()
189 setPR(106, "MERGED")
190 reload()
191 waitEvent("pr:merged #106")
192
193 want := map[string]bool{}
194 for _, n := range []int{104, 105, 106} {
195 want[fmt.Sprintf("pr:approved #%d", n)] = true
196 want[fmt.Sprintf("pr:merged #%d", n)] = true
197 }
198 got := prEvents()
199 seen := map[string]int{}
200 for _, e := range got {
201 seen[e]++
202 if !want[e] || seen[e] > 1 {
203 t.Errorf("unexpected or repeated event %s; PR events: %q", e, got)
204 }
205 }
206 if len(seen) != len(want) {
207 t.Errorf("PR events = %q, want each of %v once", got, want)
208 }
209 if strings.Contains(h.GHArgv(), "pr merge") {
210 t.Errorf("the dashboard tried to merge a PR:\n%s", h.GHArgv())
211 }
212}