gunk-dev/the-valley

dashboard_scroll_test.go

source60ad80d5a5a5main's published tip history
15.3 KiB
1package cmd
2
3import (
4 "fmt"
5 "regexp"
6 "strings"
7 "testing"
8 "time"
9
10 tea "github.com/charmbracelet/bubbletea"
11 "github.com/charmbracelet/x/ansi"
12 "the-valley/flow/internal/config"
13 gh "the-valley/flow/internal/github"
14 "the-valley/flow/internal/run"
15)
16
17// longSession returns runs resembling a long coordinator session (44 rows),
18// and the expected on-screen order of the rows shown by default and with
19// "show all". Each row is identified by its unique prompt, e.g. "attn 03".
20//
21// - 7 needing attention (yours), all over an hour old and cleaned up, never
22// hidden
23// - 4 active (agents): three bare agents and a PR with a CI-fix agent
24// running; one started 5h ago and must never be hidden
25// - 5 open PRs (pipeline), one 3h old
26// - 21 merged PRs: 6 within the hour, 15 older (hidden)
27// - 6 exited agents whose worktrees were cleaned up, all old (hidden)
28// - 1 exited agent whose worktree is still there (kept: not cleaned up)
29func longSession(now time.Time) (states []*run.State, shown, all []string) {
30 id := 0
31 add := func(s *run.State) *run.State {
32 id++
33 s.ID = fmt.Sprintf("20261004-1200-%04d", id)
34 s.Type = "launch"
35 s.TargetRepo = strPtr("testowner/testrepo")
36 if s.CreatedAt == "" {
37 s.CreatedAt = now.Format(time.RFC3339)
38 }
39 states = append(states, s)
40 return s
41 }
42 ago := func(d time.Duration) string { return now.Add(-d).Format(time.RFC3339) }
43 pr := func(n int) *string { return strPtr(fmt.Sprintf("https://github.com/testowner/testrepo/pull/%d", n)) }
44 cost := float64Ptr(1.25)
45
46 add(&run.State{Prompt: "active 01", TmuxPane: strPtr("%1"), CreatedAt: ago(2 * time.Minute), Worktree: "/wt"})
47 add(&run.State{Prompt: "active 02", PRURL: pr(500), CostUSD: cost, CreatedAt: ago(3 * time.Hour)})
48 add(&run.State{Prompt: "fix ci", PRURL: pr(500), TmuxPane: strPtr("%2"), CreatedAt: ago(5 * time.Minute)})
49 add(&run.State{Prompt: "active 03", TmuxPane: strPtr("%3"), CreatedAt: ago(20 * time.Minute), Worktree: "/wt"})
50 add(&run.State{Prompt: "active 04", TmuxPane: strPtr("%4"), CreatedAt: ago(5 * time.Hour), Worktree: "/wt"})
51 for i := 1; i <= 7; i++ {
52 add(&run.State{Prompt: fmt.Sprintf("attn %02d", i), CostUSD: cost, NeedsAttention: strPtr("agent/x"),
53 CreatedAt: ago(time.Hour + time.Duration(i)*30*time.Minute)})
54 }
55 for i := 1; i <= 5; i++ {
56 created := ago(time.Duration(i) * 10 * time.Minute)
57 if i == 5 {
58 created = ago(3 * time.Hour)
59 }
60 add(&run.State{Prompt: fmt.Sprintf("open %02d", i), PRURL: pr(600 + i), CostUSD: cost, CreatedAt: created, Worktree: "/wt"})
61 }
62 for i := 1; i <= 21; i++ {
63 merged := time.Duration(i) * 5 * time.Minute // 5m..30m
64 if i > 6 {
65 merged = 2*time.Hour + time.Duration(i)*5*time.Minute // 2h35m..3h45m
66 }
67 add(&run.State{Prompt: fmt.Sprintf("merged %02d", i), PRURL: pr(700 + i), CostUSD: cost,
68 CreatedAt: ago(merged + 30*time.Minute), MergedAt: strPtr(ago(merged))})
69 }
70 for i := 1; i <= 6; i++ {
71 add(&run.State{Prompt: fmt.Sprintf("exited %02d", i), CostUSD: cost, CreatedAt: ago(4*time.Hour + time.Duration(i)*10*time.Minute)})
72 }
73 add(&run.State{Prompt: "kept 01", CostUSD: cost, CreatedAt: ago(6 * time.Hour), Worktree: "/wt/kept"})
74
75 seq := func(prefix string, from, to int) []string {
76 var out []string
77 for i := from; i <= to; i++ {
78 out = append(out, fmt.Sprintf("%s %02d", prefix, i))
79 }
80 return out
81 }
82 var head []string
83 head = append(head, seq("attn", 1, 7)...)
84 head = append(head, seq("active", 1, 4)...)
85 head = append(head, seq("open", 1, 5)...)
86 shown = append(append(append([]string{}, head...), seq("merged", 1, 6)...), "kept 01")
87 all = append(append(append(append([]string{}, head...), seq("merged", 1, 21)...), seq("exited", 1, 6)...), "kept 01")
88 return states, shown, all
89}
90
91func newLongSessionModel(now time.Time, width, height int) (dashboardModel, []string, []string) {
92 states, shown, all := longSession(now)
93 m := dashboardModel{
94 states: states,
95 tmuxDeps: testDashboardTmuxDeps(),
96 ghStatus: map[string]*prStatus{},
97 hideAfter: defaultHideFinishedAfter,
98 }
99 m = send(m, tea.WindowSizeMsg{Width: width, Height: height})
100 return m, shown, all
101}
102
103// send runs one message through Update.
104func send(m dashboardModel, msg tea.Msg) dashboardModel {
105 next, _ := m.Update(msg)
106 return next.(dashboardModel)
107}
108
109func press(m dashboardModel, keys ...string) dashboardModel {
110 for _, k := range keys {
111 var msg tea.KeyMsg
112 switch k {
113 case "pgup":
114 msg = tea.KeyMsg{Type: tea.KeyPgUp}
115 case "pgdown":
116 msg = tea.KeyMsg{Type: tea.KeyPgDown}
117 case "tab":
118 msg = tea.KeyMsg{Type: tea.KeyTab}
119 case "enter":
120 msg = tea.KeyMsg{Type: tea.KeyEnter}
121 case "esc":
122 msg = tea.KeyMsg{Type: tea.KeyEsc}
123 default:
124 msg = tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(k)}
125 }
126 m = send(m, msg)
127 }
128 return m
129}
130
131var promptRe = regexp.MustCompile(`\b(active|attn|open|merged|exited|kept) \d\d\b`)
132
133// visibleRows returns the prompts of the rows visible in a rendered view, in
134// order, and the prompt of the selected row.
135func visibleRows(view string) (rows []string, selected string) {
136 for _, line := range strings.Split(ansi.Strip(view), "\n") {
137 p := promptRe.FindString(line)
138 if p == "" {
139 continue
140 }
141 rows = append(rows, p)
142 if strings.HasPrefix(line, "> ") {
143 selected = p
144 }
145 }
146 return rows, selected
147}
148
149var positionRe = regexp.MustCompile(`\d+–\d+ of \d+`)
150
151func position(view string) string {
152 return positionRe.FindString(ansi.Strip(view))
153}
154
155// assertFits fails if the view has more lines than the pane is tall or any
156// line is wider than the pane.
157func assertFits(t *testing.T, view string, width, height int) {
158 t.Helper()
159 lines := strings.Split(view, "\n")
160 if len(lines) > height {
161 t.Errorf("%dx%d: view has %d lines, more than the pane height", width, height, len(lines))
162 }
163 for _, l := range lines {
164 if w := ansi.StringWidth(l); w > width {
165 t.Errorf("%dx%d: line is %d wide: %q", width, height, w, ansi.Strip(l))
166 }
167 }
168}
169
170func TestDashboardLongListOrderingAndHiding(t *testing.T) {
171 m, shown, all := newLongSessionModel(time.Now(), 160, 100)
172
173 view := m.View()
174 assertFits(t, view, 160, 100)
175 rows, selected := visibleRows(view)
176 if strings.Join(rows, ",") != strings.Join(shown, ",") {
177 t.Errorf("visible rows:\n got %v\nwant %v", rows, shown)
178 }
179 if selected != "attn 01" {
180 t.Errorf("selected = %q, want the first row", selected)
181 }
182 plain := ansi.Strip(view)
183 for _, want := range []string{
184 "1–23 of 23", "21 hidden", "testowner/testrepo",
185 "7 yours · 4 agents · 5 pipeline · 28 done",
186 "4/45 agents running", "agent:0003 running", "h show all",
187 } {
188 if !strings.Contains(plain, want) {
189 t.Errorf("view missing %q:\n%s", want, plain)
190 }
191 }
192
193 // "h" shows everything, in the same order, with nothing hidden.
194 m = press(m, "h")
195 view = m.View()
196 rows, _ = visibleRows(view)
197 if strings.Join(rows, ",") != strings.Join(all, ",") {
198 t.Errorf("show-all rows:\n got %v\nwant %v", rows, all)
199 }
200 plain = ansi.Strip(view)
201 if !strings.Contains(plain, "1–44 of 44") || strings.Contains(plain, "hidden") || !strings.Contains(plain, "h hide old") {
202 t.Errorf("show-all header wrong:\n%s", plain)
203 }
204
205 // A negative threshold in config never hides anything.
206 cfg := config.Config{Dashboard: &config.DashboardConfig{HideFinishedAfterMinutes: -1}}
207 nm := newDashboardModel(run.NewGitDirStore(t.TempDir()), cfg, gh.NewGHCLIClient(""))
208 nm.tmuxDeps = testDashboardTmuxDeps()
209 nm.states = m.states
210 if v := nm.resolve(time.Now()); v.hidden != 0 || len(v.rows) != 44 {
211 t.Errorf("hide disabled: %d shown, %d hidden; want 44, 0", len(v.rows), v.hidden)
212 }
213}
214
215func TestDashboardScrollsInSmallPane(t *testing.T) {
216 m, shown, _ := newLongSessionModel(time.Now(), 60, 12)
217
218 // 12 lines: header, source, summary, blank, 6 rows, blank, footer.
219 steps := []struct {
220 keys []string
221 pos string
222 selected string
223 }{
224 {nil, "1–6 of 23", shown[0]},
225 {[]string{"k"}, "1–6 of 23", shown[0]}, // already at the top
226 {[]string{"j", "j", "j", "j", "j", "j", "j", "j", "j", "j"}, "6–11 of 23", shown[10]},
227 {[]string{"pgdown"}, "12–17 of 23", shown[16]},
228 {[]string{"G"}, "18–23 of 23", shown[22]},
229 {[]string{"j"}, "18–23 of 23", shown[22]}, // already at the bottom
230 {[]string{"pgup"}, "12–17 of 23", shown[16]},
231 {[]string{"g"}, "1–6 of 23", shown[0]},
232 }
233 for _, st := range steps {
234 m = press(m, st.keys...)
235 view := m.View()
236 assertFits(t, view, 60, 12)
237 rows, selected := visibleRows(view)
238 if got := position(view); got != st.pos {
239 t.Errorf("after %v: position %q, want %q", st.keys, got, st.pos)
240 }
241 if selected != st.selected {
242 t.Errorf("after %v: selected %q, want %q (visible %v)", st.keys, selected, st.selected, rows)
243 }
244 if len(rows) != 6 {
245 t.Errorf("after %v: %d rows visible, want 6", st.keys, len(rows))
246 }
247 }
248}
249
250func TestDashboardSelectionStaysVisibleWhenListChanges(t *testing.T) {
251 now := time.Now()
252 m, _, _ := newLongSessionModel(now, 60, 12)
253 m = press(m, strings.Split(strings.Repeat("j", 13), "")...)
254 if _, sel := visibleRows(m.View()); sel != "open 03" {
255 t.Fatalf("selected %q, want open 03", sel)
256 }
257
258 // Five new agents start: they sort above the selection, which must stay
259 // on "open 03" and scroll with it.
260 states := append([]*run.State{}, m.states...)
261 for i := 0; i < 5; i++ {
262 states = append(states, &run.State{
263 ID: fmt.Sprintf("20261004-1300-n%03d", i), Type: "launch", Prompt: fmt.Sprintf("active %02d", 50+i),
264 TargetRepo: strPtr("testowner/testrepo"), TmuxPane: strPtr("%9"), CreatedAt: now.Format(time.RFC3339),
265 })
266 }
267 m = send(m, statesLoadedMsg{states: states})
268 view := m.View()
269 if _, sel := visibleRows(view); sel != "open 03" {
270 t.Errorf("after new runs: selected %q, want open 03 still visible:\n%s", sel, ansi.Strip(view))
271 }
272 if got := position(view); got != "14–19 of 28" {
273 t.Errorf("after new runs: position %q, want 14–19 of 28", got)
274 }
275
276 // "open 03" merges: it moves to the finished group and stays selected.
277 for _, s := range states {
278 if s.Prompt == "open 03" {
279 s.MergedAt = strPtr(now.Format(time.RFC3339))
280 }
281 }
282 m = send(m, statesLoadedMsg{states: states})
283 view = m.View()
284 if _, sel := visibleRows(view); sel != "open 03" {
285 t.Errorf("after merge: selected %q, want open 03 still visible:\n%s", sel, ansi.Strip(view))
286 }
287 assertFits(t, view, 60, 12)
288}
289
290func TestDashboardKeepsPRMergedWhileWatchedVisible(t *testing.T) {
291 // "open 05" was created 3h ago. GitHub reports it merged, with no local
292 // merge time. A dashboard that watched it while open keeps it for the
293 // full threshold; one that only ever saw it merged hides it at once.
294 now := time.Now()
295 watching, _, _ := newLongSessionModel(now, 160, 100)
296 watching.ghStatus["https://github.com/testowner/testrepo/pull/605"] = &prStatus{PRNumber: "605", State: "MERGED"}
297 watching = send(watching, tickMsg{})
298
299 fresh, _, _ := newLongSessionModel(now, 160, 100)
300 fresh.ghStatus = watching.ghStatus
301 fresh.seenUnfinished = nil
302 fresh = send(fresh, tickMsg{})
303
304 isShown := func(m dashboardModel) bool {
305 rows, _ := visibleRows(m.View())
306 for _, r := range rows {
307 if r == "open 05" {
308 return true
309 }
310 }
311 return false
312 }
313 if !isShown(watching) {
314 t.Error("PR merged while watched should stay visible")
315 }
316 if isShown(fresh) {
317 t.Error("old PR first seen merged should be hidden")
318 }
319}
320
321func TestDashboardNarrowPaneTruncatesColumnsNotRows(t *testing.T) {
322 for _, width := range []int{30, 45} {
323 m, shown, _ := newLongSessionModel(time.Now(), width, 40)
324 view := m.View()
325 assertFits(t, view, width, 40)
326 n := 0
327 for _, line := range strings.Split(ansi.Strip(view), "\n") {
328 if regexp.MustCompile(`^(> | )(#\d|agent:\d{4})`).MatchString(line) {
329 n++
330 }
331 }
332 if n != len(shown) {
333 t.Errorf("width %d: %d rows visible, want all %d:\n%s", width, n, len(shown), ansi.Strip(view))
334 }
335 if !strings.Contains(ansi.Strip(view), "1–23 of 23") {
336 t.Errorf("width %d: position indicator missing:\n%s", width, ansi.Strip(view))
337 }
338 }
339}
340
341func TestDashboardTinyPanesNeverPanic(t *testing.T) {
342 for _, w := range []int{0, 1, 2, 5, 10, 20, 40} {
343 for _, h := range []int{0, 1, 2, 3, 4, 5, 8} {
344 m, _, _ := newLongSessionModel(time.Now(), w, h)
345 m.recentErrors = []dashboardError{{Time: time.Now(), Message: "boom\nwith a newline"}}
346 m.sandboxHosts = map[string]bool{"worker": true}
347 for _, keys := range [][]string{nil, {"j", "j"}, {"G"}, {"pgdown"}, {"h"}, {"pgup", "k", "g"}} {
348 m = press(m, keys...)
349 view := m.View()
350 if w == 0 || h == 0 {
351 continue // size unknown: no limit to check
352 }
353 assertFits(t, view, w, h)
354 if w >= 40 { // narrower panes drop the prompt column
355 rows, _ := visibleRows(view)
356 if want := min(h, 3); len(rows) < want {
357 t.Errorf("%dx%d after %v: %d rows visible, want at least %d:\n%s", w, h, keys, len(rows), want, ansi.Strip(view))
358 }
359 }
360 }
361 }
362 }
363}
364
365func TestDashboardEmptyAndAllHidden(t *testing.T) {
366 m := dashboardModel{states: []*run.State{}, tmuxDeps: testDashboardTmuxDeps(), width: 80, height: 24, hideAfter: time.Hour}
367 if view := ansi.Strip(m.View()); !strings.Contains(view, "No runs found") {
368 t.Errorf("empty list should say so:\n%s", view)
369 }
370
371 old := time.Now().Add(-3 * time.Hour).Format(time.RFC3339)
372 m.states = []*run.State{{ID: "20261004-1200-0001", Prompt: "merged", Type: "launch", CreatedAt: old, MergedAt: &old,
373 PRURL: strPtr("https://github.com/o/r/pull/1")}}
374 view := ansi.Strip(m.View())
375 if !strings.Contains(view, "1 done hidden (h to show all)") || !strings.Contains(view, "1 hidden") {
376 t.Errorf("all-hidden list should say how many are hidden:\n%s", view)
377 }
378}
379
380func TestDashboardRepoColumnForMultipleRepos(t *testing.T) {
381 now := time.Now().Format(time.RFC3339)
382 m := dashboardModel{
383 states: []*run.State{
384 {ID: "20261004-1200-0001", Prompt: "one", Type: "launch", CreatedAt: now, TargetRepo: strPtr("testowner/alpha"), PRURL: strPtr("https://github.com/testowner/alpha/pull/1")},
385 {ID: "20261004-1200-0002", Prompt: "two", Type: "launch", CreatedAt: now, TargetRepo: strPtr("testowner/beta"), PRURL: strPtr("https://github.com/testowner/beta/pull/2")},
386 },
387 tmuxDeps: testDashboardTmuxDeps(), width: 100, height: 24,
388 }
389 view := ansi.Strip(m.View())
390 for _, want := range []string{"2 repos", "alpha #1", "beta #2"} {
391 if !strings.Contains(view, want) {
392 t.Errorf("view missing %q:\n%s", want, view)
393 }
394 }
395}
396
397// A branch pushed without a PR (#281) waits for the operator to submit it:
398// it sorts with their rows as SUBMIT, shows its branch and short SHA, and is
399// never hidden as an old done row.
400func TestDashboardShowsBranchAwaitingIntegration(t *testing.T) {
401 old := time.Now().Add(-6 * time.Hour).Format(time.RFC3339)
402 branch := "agent/20261005-0300-0002"
403 m := dashboardModel{
404 states: []*run.State{
405 {ID: "20261005-0300-0001", Type: "launch", Prompt: "exited 01", CostUSD: float64Ptr(1), CreatedAt: old},
406 {ID: "20261005-0300-0002", Type: "launch", Prompt: "open 01", CostUSD: float64Ptr(2), CreatedAt: old,
407 Branch: branch, PushedBranch: strPtr(branch), PushedSHA: strPtr("0123456789abcdef0123456789abcdef01234567")},
408 },
409 tmuxDeps: testDashboardTmuxDeps(),
410 ghStatus: map[string]*prStatus{},
411 hideAfter: defaultHideFinishedAfter,
412 }
413 m = send(m, tea.WindowSizeMsg{Width: 160, Height: 30})
414
415 view := m.View()
416 if rows, _ := visibleRows(view); strings.Join(rows, ",") != "open 01" {
417 t.Errorf("visible rows = %v, want only the pushed branch", rows)
418 }
419 plain := ansi.Strip(view)
420 for _, want := range []string{"1 yours · 1 done", "1 hidden", "SUBMIT " + branch + "@0123456"} {
421 if !strings.Contains(plain, want) {
422 t.Errorf("view missing %q:\n%s", want, plain)
423 }
424 }
425}