gunk-dev/the-valley

dashboard_jobs_test.go

source88a5a486b52fmain's published tip history
10.4 KiB
1package cmd
2
3import (
4 "os"
5 "path/filepath"
6 "strings"
7 "testing"
8 "time"
9
10 tea "github.com/charmbracelet/bubbletea"
11 "github.com/charmbracelet/x/ansi"
12 "github.com/fsnotify/fsnotify"
13 "the-valley/flow/internal/jobs"
14 "the-valley/flow/internal/run"
15)
16
17// sampleJobs returns a running threaded consult, a failed one, a succeeded
18// review whose answer is in its record, a succeeded consult with an answer
19// file, and one that finished too long ago to list.
20func sampleJobs(t *testing.T, now time.Time) []*jobs.Job {
21 t.Helper()
22 at := func(d time.Duration) *time.Time { x := now.Add(-d); return &x }
23 answer := filepath.Join(t.TempDir(), "answer")
24 if err := os.WriteFile(answer, []byte("first line of the answer\nsecond line of the answer\n"), 0o600); err != nil {
25 t.Fatal(err)
26 }
27 return []*jobs.Job{
28 {ID: "consult-20261017-1200-aaaa0001", Kind: "consult", Thread: "design", Backend: "codex", Model: "gpt-9",
29 Prompt: "Design the jobs table", Status: jobs.Running, StartedAt: now.Add(-12 * time.Minute)},
30 {ID: "consult-20261017-1150-bbbb0002", Kind: "consult", Backend: "claude", Prompt: "Why did it break",
31 Status: jobs.Failed, Error: "consult claude: exit status 7", RawOutput: "/tmp/consult-0002.raw",
32 StartedAt: now.Add(-6 * time.Minute), FinishedAt: at(5 * time.Minute)},
33 {ID: "review-20261017-1140-cccc0003", Kind: "review", PR: "acme/widget#7", Backend: "agy",
34 Status: jobs.Succeeded, StartedAt: now.Add(-23 * time.Minute), FinishedAt: at(20 * time.Minute),
35 Review: &jobs.Review{Verdict: "Does what it says.", Findings: nil}},
36 {ID: "consult-20261017-1130-dddd0004", Kind: "consult", Backend: "codex", Prompt: "Answer me",
37 Status: jobs.Succeeded, AnswerFile: answer, StartedAt: now.Add(-41 * time.Minute), FinishedAt: at(40 * time.Minute)},
38 {ID: "consult-20261017-0100-eeee0005", Kind: "consult", Backend: "codex", Prompt: "Long ago",
39 Status: jobs.Succeeded, StartedAt: now.Add(-11 * time.Hour), FinishedAt: at(10 * time.Hour)},
40 }
41}
42
43func newJobsModel(t *testing.T, width, height int) dashboardModel {
44 t.Helper()
45 now := time.Now()
46 m := dashboardModel{
47 states: []*run.State{{ID: "20261017-1200-0001", Type: "launch", Prompt: "active 01", TmuxPane: strPtr("%1"),
48 CreatedAt: now.Format(time.RFC3339), Worktree: "/wt", TargetRepo: strPtr("testowner/testrepo")}},
49 tmuxDeps: testDashboardTmuxDeps(),
50 ghStatus: map[string]*prStatus{},
51 hideAfter: defaultHideFinishedAfter,
52 }
53 m = send(m, tea.WindowSizeMsg{Width: width, Height: height})
54 return send(m, jobsLoadedMsg{jobs: sampleJobs(t, now)})
55}
56
57func TestDashboardJobsSection(t *testing.T) {
58 m := newJobsModel(t, 140, 30)
59 view := ansi.Strip(m.View())
60 lines := strings.Split(view, "\n")
61 find := func(s string) int {
62 for i, l := range lines {
63 if strings.Contains(l, s) {
64 return i
65 }
66 }
67 return -1
68 }
69 row, header := find("active 01"), find("jobs · 1 running · 3 finished")
70 if row < 0 || header <= row {
71 t.Fatalf("jobs section should follow the run rows:\n%s", view)
72 }
73 for i, want := range [][]string{
74 {"consult:0001", "design", "codex gpt-9", "RUNNING", "12m", "Design the jobs table"},
75 {"consult:0002", "-", "claude", "FAILED", "1m", "Why did it break"},
76 {"review:0003", "acme/widget#7", "agy", "SUCCEEDED", "3m"},
77 {"consult:0004", "-", "codex", "SUCCEEDED", "1m", "Answer me"},
78 } {
79 line := lines[header+1+i]
80 for _, w := range want {
81 if !strings.Contains(line, w) {
82 t.Errorf("job line %d %q missing %q", i, line, w)
83 }
84 }
85 }
86 if strings.Contains(view, "Long ago") {
87 t.Errorf("a job that finished 10h ago is listed:\n%s", view)
88 }
89 if !strings.Contains(view, "o open · tab jobs") {
90 t.Errorf("footer should offer tab:\n%s", view)
91 }
92 // The jobs don't join the run rows.
93 if !strings.Contains(view, "1 agents") || strings.Contains(view, "1 done") {
94 t.Errorf("summary counts jobs as rows:\n%s", view)
95 }
96}
97
98// On a short pane the jobs lines go after the spacing and source lines and
99// before the errors, the footer and any run row; their header goes last.
100func TestDashboardFitLayoutDropsJobsBeforeRows(t *testing.T) {
101 m := dashboardModel{recentErrors: []dashboardError{{Time: time.Now(), Message: "boom"}}}
102 const rows, nJobs = 10, 3
103 prevJobs := nJobs
104 for h := 30; h >= 1; h-- {
105 m.height = h
106 items, bodyH := m.fitLayout(rows, nJobs)
107 count := map[chromeKind]int{}
108 for _, it := range items {
109 count[it.kind]++
110 }
111 shown := count[chromeJob]
112 if shown > prevJobs {
113 t.Errorf("height %d: %d job lines, more than at a taller pane", h, shown)
114 }
115 prevJobs = shown
116 if bodyH < min(3, h) && len(items) > 0 {
117 t.Errorf("height %d: %d rows while %d chrome lines are kept", h, bodyH, len(items))
118 }
119 if shown < nJobs && (count[chromeBlank] > 0 || count[chromeSource] > 0) {
120 t.Errorf("height %d: a job line went before the spacing and source lines: %+v", h, count)
121 }
122 if shown > 0 && (count[chromeError] == 0 || count[chromeFooter] == 0 || count[chromeJobs] == 0) {
123 t.Errorf("height %d: the errors, footer or jobs header went before a job line: %+v", h, count)
124 }
125 }
126
127 // The rendered view fits, and names the jobs it had no room for.
128 view := newJobsModel(t, 80, 7).View()
129 assertFits(t, view, 80, 7)
130 if plain := ansi.Strip(view); !strings.Contains(plain, "active 01") || !strings.Contains(plain, "not shown") {
131 t.Errorf("short pane should keep the row and count the hidden jobs:\n%s", plain)
132 }
133}
134
135func TestDashboardSelectJobAndReadIt(t *testing.T) {
136 m := newJobsModel(t, 140, 30)
137 selected := func(view string) string {
138 for _, l := range strings.Split(ansi.Strip(view), "\n") {
139 if strings.HasPrefix(l, "> ") {
140 return l
141 }
142 }
143 return ""
144 }
145 if sel := selected(m.View()); !strings.Contains(sel, "active 01") {
146 t.Fatalf("the run row starts selected, got %q", sel)
147 }
148
149 m = press(m, "tab")
150 view := ansi.Strip(m.View())
151 if sel := selected(view); !strings.Contains(sel, "consult:0001") || strings.Count(view, "\n> ") != 1 {
152 t.Errorf("tab should select the top job, and only it: %q\n%s", sel, view)
153 }
154 if !strings.Contains(view, "consult:0001 running for 12m | enter read") {
155 t.Errorf("footer should say how the running job stands:\n%s", view)
156 }
157
158 // The footer of a failed job says why, and where its raw output is.
159 m = press(m, "j")
160 view = ansi.Strip(m.View())
161 if sel := selected(view); !strings.Contains(sel, "consult:0002") ||
162 !strings.Contains(view, "failed: consult claude: exit status 7 · raw output: /tmp/consult-0002.raw") {
163 t.Errorf("failed job selection %q:\n%s", sel, view)
164 }
165
166 // a and d act on PRs, not jobs; q still quits from the jobs.
167 m = press(m, "a")
168 if view := ansi.Strip(m.View()); !strings.Contains(view, "a job has no PR") {
169 t.Errorf("approve on a job should say why it can't:\n%s", view)
170 }
171
172 // enter reads a review's answer, its findings, in place of the list; q
173 // closes it rather than quitting.
174 m = press(m, "j", "enter")
175 view = ansi.Strip(m.View())
176 if !strings.Contains(view, "Verdict: Does what it says.") || !strings.Contains(view, "pr: acme/widget#7") || strings.Contains(view, "active 01") {
177 t.Errorf("review detail:\n%s", view)
178 }
179 m = press(m, "q")
180 if sel := selected(m.View()); !strings.Contains(sel, "review:0003") {
181 t.Fatalf("q should close the detail back onto the job, got %q", sel)
182 }
183
184 // A consult's answer, scrolled with j/k; esc goes back, and again to
185 // the runs.
186 m = press(m, "G", "enter")
187 view = ansi.Strip(m.View())
188 for _, want := range []string{"job consult-20261017-1130-dddd0004", "status: succeeded", "second line of the answer", "esc back"} {
189 if !strings.Contains(view, want) {
190 t.Errorf("detail missing %q:\n%s", want, view)
191 }
192 }
193 m = press(m, "esc", "esc")
194 if sel := selected(m.View()); !strings.Contains(sel, "active 01") {
195 t.Errorf("esc should go back to the runs, got %q", sel)
196 }
197}
198
199// The dashboard follows job records through its fsnotify watcher: a job
200// appears when its record is written, and changes when it finishes.
201func TestDashboardReloadsJobsOnRecordChange(t *testing.T) {
202 dir := t.TempDir()
203 store := run.NewHomeDirStoreFromPath(dir)
204 jobStore := jobs.NewStore(dir)
205
206 // A run's record is told apart from a job's.
207 w, ok := startWatcherCmd(store, jobStore.Dir)().(*fsnotify.Watcher)
208 if !ok {
209 t.Fatal("watcher didn't start")
210 }
211 if err := store.Save(&run.State{ID: "20261017-1200-0001", Type: "launch", CreatedAt: time.Now().Format(time.RFC3339)}); err != nil {
212 t.Fatal(err)
213 }
214 if msg := awaitCmd(t, watchFSCmd(w, jobStore.Dir)); msg != (fsEventMsg{}) {
215 t.Errorf("a run's record gave %T, want fsEventMsg", msg)
216 }
217 w.Close()
218
219 w, ok = startWatcherCmd(store, jobStore.Dir)().(*fsnotify.Watcher)
220 if !ok {
221 t.Fatal("watcher didn't start")
222 }
223 defer w.Close()
224 l := &teaLoop{t: t, msgs: make(chan tea.Msg, 64), m: dashboardModel{
225 store: store, jobsDir: jobStore.Dir, states: []*run.State{},
226 tmuxDeps: testDashboardTmuxDeps(), ghStatus: map[string]*prStatus{}, width: 120, height: 30,
227 }}
228 l.deliver(w)
229
230 job := &jobs.Job{ID: "consult-20261017-1200-abcd0001", Kind: "consult", Backend: "codex", Prompt: "watch me"}
231 if err := jobStore.Start(job); err != nil { // by this test process, so it reads as running
232 t.Fatal(err)
233 }
234 l.until("watch me", "RUNNING")
235 if err := jobStore.Finish(job, jobs.TimedOut, "timeout after 1s"); err != nil {
236 t.Fatal(err)
237 }
238 l.until("watch me", "TIMED OUT")
239}
240
241// awaitCmd runs cmd, failing the test if it doesn't return promptly.
242func awaitCmd(t *testing.T, cmd tea.Cmd) tea.Msg {
243 t.Helper()
244 ch := make(chan tea.Msg, 1)
245 go func() { ch <- cmd() }()
246 select {
247 case msg := <-ch:
248 return msg
249 case <-time.After(10 * time.Second):
250 t.Fatal("command didn't return")
251 }
252 return nil
253}
254
255// teaLoop runs a dashboard model's commands and feeds their messages back
256// through Update, as bubbletea does.
257type teaLoop struct {
258 t *testing.T
259 m dashboardModel
260 msgs chan tea.Msg
261}
262
263func (l *teaLoop) start(c tea.Cmd) {
264 if c != nil {
265 go func() { l.msgs <- c() }()
266 }
267}
268
269func (l *teaLoop) deliver(msg tea.Msg) {
270 switch msg := msg.(type) {
271 case nil:
272 case tea.BatchMsg:
273 for _, c := range msg {
274 l.start(c)
275 }
276 default:
277 next, c := l.m.Update(msg)
278 l.m = next.(dashboardModel)
279 l.start(c)
280 }
281}
282
283// until delivers messages until the view shows every one of want.
284func (l *teaLoop) until(want ...string) {
285 l.t.Helper()
286 deadline := time.After(10 * time.Second)
287 for {
288 view := ansi.Strip(l.m.View())
289 ok := true
290 for _, w := range want {
291 ok = ok && strings.Contains(view, w)
292 }
293 if ok {
294 return
295 }
296 select {
297 case msg := <-l.msgs:
298 l.deliver(msg)
299 case <-deadline:
300 l.t.Fatalf("view never showed %q:\n%s", want, view)
301 }
302 }
303}