gunk-dev/the-valley

dashboard_yours_test.go

source672eff5ffaecmain's published tip history
53.9 KiB
1package cmd
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "regexp"
10 "strings"
11 "testing"
12 "time"
13
14 tea "github.com/charmbracelet/bubbletea"
15 "github.com/charmbracelet/x/ansi"
16 "the-valley/flow/internal/config"
17 gh "the-valley/flow/internal/github"
18 "the-valley/flow/internal/integration"
19 "the-valley/flow/internal/pipeline"
20 "the-valley/flow/internal/run"
21)
22
23// TestClassifyByWhoseMoveItIs covers every category and the precedence
24// between them: a running agent wins, then done, then yours, then pipeline.
25func TestClassifyByWhoseMoveItIs(t *testing.T) {
26 now := time.Now()
27 n := 0
28 var states []*run.State
29 pr := func(num int) *string { return strPtr(fmt.Sprintf("https://github.com/o/r/pull/%d", num)) }
30 add := func(prompt string, s *run.State) *run.State {
31 n++
32 s.ID = fmt.Sprintf("20261012-1200-%04d", n)
33 s.Prompt = prompt
34 s.Type = "launch"
35 s.TargetRepo = strPtr("o/r")
36 s.CreatedAt = now.Add(-time.Duration(n) * time.Minute).Format(time.RFC3339)
37 if s.CostUSD == nil && s.TmuxPane == nil {
38 s.CostUSD = float64Ptr(1)
39 }
40 states = append(states, s)
41 return s
42 }
43 pushed := func(prompt string) *run.State {
44 branch := "agent/" + strings.ReplaceAll(prompt, " ", "-")
45 return add(prompt, &run.State{PushedBranch: &branch, PushedSHA: strPtr("0123456789abcdef0123456789abcdef01234567")})
46 }
47 approved := true
48
49 // yours
50 add("yours attn", &run.State{NeedsAttention: strPtr("agent/x")})
51 submit := pushed("yours submit")
52 add("yours ready", &run.State{PRURL: pr(1)})
53 add("yours stalled", &run.State{PRURL: pr(2)})
54 unknownCheck := pushed("yours unchecked")
55 // agents
56 add("agents bare", &run.State{TmuxPane: strPtr("%1")})
57 add("agents merged pr", &run.State{PRURL: pr(3), TmuxPane: strPtr("%2"), MergedAt: strPtr(now.Format(time.RFC3339))})
58 landedRunning := pushed("agents landed")
59 landedRunning.TmuxPane, landedRunning.CostUSD = strPtr("%3"), nil
60 // pipeline
61 add("pipeline pending", &run.State{PRURL: pr(4)})
62 add("pipeline failing", &run.State{PRURL: pr(5)})
63 add("pipeline conflicts", &run.State{PRURL: pr(6)})
64 add("pipeline behind", &run.State{PRURL: pr(7)})
65 add("pipeline approved", &run.State{PRURL: pr(8), Approved: &approved})
66 add("pipeline draft", &run.State{PRURL: pr(9)})
67 add("pipeline unfetched", &run.State{PRURL: pr(10)})
68 // done
69 add("done merged", &run.State{PRURL: pr(11), MergedAt: strPtr(now.Format(time.RFC3339))})
70 add("done closed", &run.State{PRURL: pr(12)})
71 add("done no access", &run.State{PRURL: pr(13), NeedsAttention: strPtr("agent/y")})
72 integrated := pushed("done integrated")
73 content := pushed("done content")
74 gone := pushed("done gone")
75 add("done exited", &run.State{Worktree: "/wt"})
76
77 ready := func() *prStatus {
78 return &prStatus{State: "OPEN", CI: "passing", Conflicts: "none", ReviewDecision: "APPROVED"}
79 }
80 status := map[int]*prStatus{
81 1: ready(),
82 2: {State: "OPEN", CI: "pending", Conflicts: "none"},
83 4: {State: "OPEN", CI: "pending", Conflicts: "none"},
84 5: {State: "OPEN", CI: "failing", Conflicts: "none"},
85 6: {State: "OPEN", CI: "passing", Conflicts: "yes"},
86 7: {State: "OPEN", CI: "passing", Conflicts: "none", BehindBy: 2},
87 8: ready(),
88 9: {State: "OPEN", CI: "passing", Conflicts: "none", Draft: true},
89 12: {State: "CLOSED"},
90 13: {State: gh.StateNoAccess},
91 }
92 m := dashboardModel{
93 states: states,
94 tmuxDeps: testDashboardTmuxDeps(),
95 ghStatus: map[string]*prStatus{},
96 pipelineStates: map[string]*pipeline.PRPipelineState{
97 "2": {PRNumber: "2", PRURL: *pr(2), Stage: pipeline.StageStalled},
98 },
99 integration: map[string]integration.Result{
100 submit.ID: {Verdict: integration.Awaiting},
101 unknownCheck.ID: {Verdict: integration.Unknown},
102 landedRunning.ID: {Verdict: integration.Integrated},
103 integrated.ID: {Verdict: integration.Integrated},
104 content.ID: {Verdict: integration.IntegratedContent},
105 gone.ID: {Verdict: integration.Gone},
106 },
107 hideAfter: defaultHideFinishedAfter,
108 }
109 for num, ps := range status {
110 m.ghStatus[*pr(num)] = ps
111 }
112
113 rows := m.buildRows()
114 var gotOrder []string
115 for _, r := range rows {
116 prompt := r.state().Prompt
117 gotOrder = append(gotOrder, prompt)
118 want := strings.Fields(prompt)[0]
119 if got := categoryNames[r.category]; got != want {
120 t.Errorf("%q: category %s, want %s", prompt, got, want)
121 }
122 }
123 // Within a category, most recent first: states were created a minute apart
124 // in the order added, and the merged PR's merge (now) is its latest
125 // activity.
126 wantOrder := []string{
127 "yours attn", "yours submit", "yours ready", "yours stalled", "yours unchecked",
128 "agents merged pr", "agents bare", "agents landed",
129 "pipeline pending", "pipeline failing", "pipeline conflicts", "pipeline behind", "pipeline approved", "pipeline draft", "pipeline unfetched",
130 "done merged", "done closed", "done no access", "done integrated", "done content", "done gone", "done exited",
131 }
132 if strings.Join(gotOrder, ",") != strings.Join(wantOrder, ",") {
133 t.Errorf("order:\n got %v\nwant %v", gotOrder, wantOrder)
134 }
135
136 for _, r := range rows {
137 if r.category != catDone {
138 continue
139 }
140 // An exited agent whose worktree is still there is kept; every other
141 // done row may be hidden once old.
142 if want := r.state().Prompt != "done exited"; r.hideable != want {
143 t.Errorf("%q: hideable = %v, want %v", r.state().Prompt, r.hideable, want)
144 }
145 }
146
147 m = send(m, tea.WindowSizeMsg{Width: 200, Height: 60})
148 plain := ansi.Strip(m.View())
149 if !strings.Contains(plain, "5 yours · 3 agents · 7 pipeline · 7 done") {
150 t.Errorf("summary should count each category:\n%s", plain)
151 }
152 for prompt, label := range map[string]string{
153 "yours submit": "SUBMIT",
154 "yours unchecked": "SUBMIT",
155 "done integrated": "INTEGRATED ",
156 "done content": "INTEGRATED~",
157 "done gone": "GONE",
158 "done no access": "NO ACCESS",
159 "yours stalled": "ATTN",
160 } {
161 if line := lineWith(plain, prompt); !strings.Contains(line, label) {
162 t.Errorf("%q row should show %s: %q", prompt, label, line)
163 }
164 }
165 if line := lineWith(plain, "done no access"); strings.Contains(line, "CI") {
166 t.Errorf("a PR we can't read shows no CI: %q", line)
167 }
168}
169
170// TestChangeRowsGroupRuns covers how runs without a PR group by change, as
171// runs on a PR share its row: one row per repo and change ID, judged by the
172// valley's view of the change's active version, wherever it was marked
173// ready, so earlier versions fold in and a running follow-up puts the row
174// with the agents and withholds the approve command. Salvaged work counts
175// unless a run that pushed took it on. A change no valley lists is judged by its
176// latest push. Runs without a change ID keep a row each.
177func TestChangeRowsGroupRuns(t *testing.T) {
178 now := time.Now()
179 n := 0
180 var states []*run.State
181 // add records a run made ago minutes ago, on change changeID.
182 add := func(prompt, changeID string, ago int, s *run.State) *run.State {
183 n++
184 s.ID = fmt.Sprintf("20261013-1200-%04d", n)
185 s.Prompt, s.Type, s.ChangeID = prompt, "launch", changeID
186 if s.TargetRepo == nil {
187 s.TargetRepo = strPtr("o/r")
188 }
189 s.CreatedAt = now.Add(-time.Duration(ago) * time.Minute).Format(time.RFC3339)
190 if s.TmuxPane == nil {
191 s.CostUSD = float64Ptr(1)
192 }
193 states = append(states, s)
194 return s
195 }
196 pushed := func(prompt, changeID string, ago int) *run.State {
197 sha := fmt.Sprintf("%040d", n+1)
198 return add(prompt, changeID, ago, &run.State{PushedBranch: strPtr("agent/" + strings.ReplaceAll(prompt, " ", "-")), PushedSHA: &sha})
199 }
200 chg := func(c byte) string { return strings.Repeat(string(c), 32) }
201 results := map[string]integration.Result{}
202 changes := map[integration.ChangeKey]integration.Result{}
203 // activeIs records the valley's view of a change's active version.
204 activeIs := func(changeID string, v integration.Verdict, version int, head string) {
205 changes[integration.ChangeKey{Repo: "r", ChangeID: changeID}] = integration.Result{Verdict: v, Change: &integration.Change{
206 Repo: "r", ChangeID: changeID, Handle: changeID[:4], Version: version, Head: head, Active: true}}
207 }
208 // valley records where a run's version stands; a version that isn't
209 // superseded is its change's active one.
210 valley := func(s *run.State, v integration.Verdict, version int) {
211 results[s.ID] = integration.Result{Verdict: v, Change: &integration.Change{Repo: "r", ChangeID: s.ChangeID,
212 Handle: s.ChangeID[:4], Version: version, Head: *s.PushedSHA, Active: v != integration.Superseded}}
213 if v != integration.Superseded {
214 activeIs(s.ChangeID, v, version, *s.PushedSHA)
215 }
216 }
217
218 // Two versions: the later one is active, the earlier folds in.
219 folded := pushed("folded v1", chg('k'), 30)
220 valley(folded, integration.Superseded, 1)
221 active := pushed("active v2", chg('k'), 20)
222 valley(active, integration.Ready, 2)
223 // The valley made an earlier run's version active again.
224 reactivated := pushed("reactivated v1", chg('q'), 30)
225 valley(reactivated, integration.Ready, 1)
226 newer := pushed("newer v2", chg('q'), 20)
227 valley(newer, integration.Superseded, 2)
228 // A ready version and a follow-up still running.
229 readied := pushed("readied v1", chg('l'), 30)
230 valley(readied, integration.Ready, 1)
231 follow := add("follow-up", chg('l'), 5, &run.State{TmuxPane: strPtr("%1")})
232 // The same change ID in another repo is another change.
233 elsewhere := pushed("elsewhere", chg('l'), 25)
234 elsewhere.TargetRepo = strPtr("o/other")
235 elsewhere.PushedSubject = "Port it elsewhere" // titles a change no valley knows
236 results[elsewhere.ID] = integration.Result{Verdict: integration.Awaiting}
237 // Salvaged work a run that pushed took on is continued; salvage after a
238 // push needs the operator.
239 salvage := add("continued salvage", chg('m'), 40, &run.State{NeedsAttention: strPtr("agent/x")})
240 continuing := pushed("continuing push", chg('m'), 30)
241 continuing.TookOver = []string{salvage.ID}
242 valley(continuing, integration.Ready, 1)
243 before := pushed("pushed first", chg('n'), 40)
244 valley(before, integration.Ready, 1)
245 add("salvaged later", chg('n'), 30, &run.State{NeedsAttention: strPtr("agent/y")})
246 landed := pushed("landed first", chg('r'), 40)
247 valley(landed, integration.Integrated, 1)
248 add("salvaged after landing", chg('r'), 30, &run.State{NeedsAttention: strPtr("agent/z")})
249 // Nothing pushed yet.
250 first := add("first run", chg('o'), 3, &run.State{TmuxPane: strPtr("%2")})
251 // A version that landed, then gave way, with the rest, to one marked
252 // ready elsewhere and awaiting approval.
253 landedOld := pushed("landed long ago", chg('s'), 46)
254 valley(landedOld, integration.Integrated, 1)
255 results[landedOld.ID].Change.Active = false
256 valley(pushed("gave way later", chg('s'), 45), integration.Superseded, 2)
257 elsewhereHead := strings.Repeat("e", 40)
258 activeIs(chg('s'), integration.Ready, 3, elsewhereHead)
259 // Every version replaced by one from elsewhere, which landed.
260 replaced := pushed("replaced", chg('p'), 50)
261 valley(replaced, integration.Superseded, 1)
262 activeIs(chg('p'), integration.Integrated, 2, strings.Repeat("f", 40))
263 // No change ID: a row each.
264 loneA := pushed("lone a", "", 10)
265 loneB := pushed("lone b", "", 11)
266 results[loneA.ID] = integration.Result{Verdict: integration.Awaiting}
267 results[loneB.ID] = integration.Result{Verdict: integration.Awaiting}
268
269 m := dashboardModel{
270 states: states,
271 tmuxDeps: testDashboardTmuxDeps(),
272 ghStatus: map[string]*prStatus{},
273 integration: results,
274 changes: changes,
275 hideAfter: defaultHideFinishedAfter,
276 approveTemplate: "valley approve {handle} --head {head}",
277 }
278 rows := m.buildRows()
279 type want struct {
280 key, id, category, label string
281 runs, running int
282 approve string
283 }
284 wants := map[string]want{
285 "active v2": {"change:o/r#" + chg('k'), "kkkk", "yours", "READY v2@", 2, 0, "valley approve kkkk --head " + *active.PushedSHA},
286 "readied v1": {"change:o/r#" + chg('l'), "llll", "agents", "READY agent:" + shortRunID(follow.ID) + " running v1@", 2, 1, ""},
287 "Port it elsewhere": {"change:o/other#" + chg('l'), "llllllll", "yours", "SUBMIT", 1, 0, ""},
288 "continuing push": {"change:o/r#" + chg('m'), "mmmm", "yours", "READY v1@", 2, 0, "valley approve mmmm --head " + *continuing.PushedSHA},
289 "pushed first": {"change:o/r#" + chg('n'), "nnnn", "yours", "ATTN v1@", 2, 0, ""},
290 "first run": {"change:o/r#" + chg('o'), "oooooooo", "agents", "agent:" + shortRunID(first.ID) + " running", 1, 1, ""},
291 "landed first": {"change:o/r#" + chg('r'), "rrrr", "yours", "ATTN v1@", 2, 0, ""},
292 "reactivated v1": {"change:o/r#" + chg('q'), "qqqq", "yours", "READY v1@", 2, 0, "valley approve qqqq --head " + *reactivated.PushedSHA},
293 "gave way later": {"change:o/r#" + chg('s'), "ssss", "yours", "READY v3@eeeeeee", 2, 0, "valley approve ssss --head " + elsewhereHead},
294 "replaced": {"change:o/r#" + chg('p'), "pppp", "done", "INTEGRATED v2@fffffff", 1, 0, ""},
295 "lone a": {"run:" + loneA.ID, "agent:" + shortRunID(loneA.ID), "yours", "SUBMIT", 1, 0, ""},
296 "lone b": {"run:" + loneB.ID, "agent:" + shortRunID(loneB.ID), "yours", "SUBMIT", 1, 0, ""},
297 }
298 if len(rows) != len(wants) {
299 t.Errorf("%d rows, want %d", len(rows), len(wants))
300 }
301 m = send(m, tea.WindowSizeMsg{Width: 200, Height: 40})
302 plain := ansi.Strip(m.View())
303 for _, r := range rows {
304 desc := r.description()
305 w, ok := wants[desc]
306 if !ok {
307 t.Errorf("unexpected row %q (%s)", desc, r.key)
308 continue
309 }
310 _, cmd := m.approveCommand(r)
311 if r.key != w.key || r.idLabel() != w.id || categoryNames[r.category] != w.category ||
312 len(r.runs) != w.runs || len(r.running) != w.running || cmd != w.approve {
313 t.Errorf("%q: %s %s %s, %d runs, %d running, command %q; want %+v",
314 desc, r.key, r.idLabel(), categoryNames[r.category], len(r.runs), len(r.running), cmd, w)
315 }
316 if line := lineWith(plain, desc); !strings.Contains(line, w.id+" ") || !strings.Contains(line, w.label) {
317 t.Errorf("%q row should show %s and %q: %q", desc, w.id, w.label, line)
318 }
319 }
320 if strings.Contains(plain, "SUPERSEDED") || strings.Count(plain, "INTEGRATED") != 1 {
321 t.Errorf("a change reads as its active version stands: none SUPERSEDED, and only the one landed elsewhere INTEGRATED:\n%s", plain)
322 }
323}
324
325// TestPipelineStateIsPerRepo: the pipeline keys PRs by number alone, so its
326// state for o/a#5 must not make o/b#5 the operator's or show its stage.
327func TestPipelineStateIsPerRepo(t *testing.T) {
328 now := time.Now()
329 pr := func(repo string) *run.State {
330 return &run.State{
331 ID: "20261012-1200-" + repo, Type: "launch", Prompt: "repo " + repo, CostUSD: float64Ptr(1),
332 TargetRepo: strPtr("o/" + repo), PRURL: strPtr("https://github.com/o/" + repo + "/pull/5"),
333 CreatedAt: now.Format(time.RFC3339),
334 }
335 }
336 a, b := pr("a"), pr("b")
337 m := dashboardModel{
338 states: []*run.State{a, b},
339 tmuxDeps: testDashboardTmuxDeps(),
340 ghStatus: map[string]*prStatus{
341 *a.PRURL: {State: "OPEN", CI: "failing", Conflicts: "none"},
342 *b.PRURL: {State: "OPEN", CI: "pending", Conflicts: "none"},
343 },
344 pipelineStates: map[string]*pipeline.PRPipelineState{
345 "5": {PRNumber: "5", PRURL: *a.PRURL, Stage: pipeline.StageStalled},
346 },
347 hideAfter: defaultHideFinishedAfter,
348 }
349 for _, r := range m.buildRows() {
350 want := map[string]rowCategory{"repo a": catYours, "repo b": catPipeline}[r.state().Prompt]
351 if r.category != want {
352 t.Errorf("%q: category %s, want %s", r.state().Prompt, categoryNames[r.category], categoryNames[want])
353 }
354 }
355
356 m = send(m, tea.WindowSizeMsg{Width: 200, Height: 20})
357 plain := ansi.Strip(m.View())
358 if line := lineWith(plain, "repo a"); !strings.Contains(line, "stalled") {
359 t.Errorf("o/a#5 should show its pipeline stage: %q", line)
360 }
361 if line := lineWith(plain, "repo b"); strings.Contains(line, "stalled") {
362 t.Errorf("o/b#5 should not show o/a#5's pipeline stage: %q", line)
363 }
364}
365
366// lineWith returns the first line of s that contains sub.
367func lineWith(s, sub string) string {
368 for _, line := range strings.Split(s, "\n") {
369 if strings.Contains(line, sub) {
370 return line
371 }
372 }
373 return ""
374}
375
376// TestSubmitThenIntegratedStaysVisible: a run the dashboard saw as SUBMIT
377// that then integrates stays visible for the full hide threshold, like a PR
378// it watched merge. One it only ever saw integrated is hidden when old.
379func TestSubmitThenIntegratedStaysVisible(t *testing.T) {
380 branch := "agent/20261012-0900-0001"
381 s := &run.State{
382 ID: "20261012-0900-0001", Type: "launch", Prompt: "pushed 01", CostUSD: float64Ptr(1),
383 CreatedAt: time.Now().Add(-6 * time.Hour).Format(time.RFC3339),
384 PushedBranch: &branch, PushedSHA: strPtr("0123456789abcdef0123456789abcdef01234567"),
385 }
386 newModel := func() dashboardModel {
387 m := dashboardModel{states: []*run.State{s}, tmuxDeps: testDashboardTmuxDeps(), ghStatus: map[string]*prStatus{},
388 hideAfter: defaultHideFinishedAfter}
389 return send(m, tea.WindowSizeMsg{Width: 160, Height: 20})
390 }
391 verdict := func(v integration.Verdict) integrationMsg {
392 return integrationMsg{results: map[string]integration.Result{s.ID: {Verdict: v}}}
393 }
394 shown := func(m dashboardModel) string {
395 return lineWith(ansi.Strip(m.View()), "pushed 01")
396 }
397
398 watching := send(newModel(), verdict(integration.Awaiting))
399 if line := shown(watching); !strings.Contains(line, "SUBMIT") {
400 t.Fatalf("awaiting run should show SUBMIT, got %q", line)
401 }
402 watching = send(watching, verdict(integration.Integrated))
403 if line := shown(watching); !strings.Contains(line, "INTEGRATED") {
404 t.Errorf("run seen as SUBMIT should stay visible as INTEGRATED, got %q", line)
405 }
406 if v := watching.resolve(time.Now().Add(59 * time.Minute)); len(v.rows) != 1 {
407 t.Errorf("still within the threshold of the transition: %d rows shown, want 1", len(v.rows))
408 }
409
410 // Never seen awaiting (the first check couldn't complete, then found it
411 // integrated): it's old, so it's hidden.
412 fresh := send(send(newModel(), verdict(integration.Unknown)), verdict(integration.Integrated))
413 if line := shown(fresh); line != "" {
414 t.Errorf("old run first seen integrated should be hidden, got %q", line)
415 }
416}
417
418// gitFixture is a bare origin with the run's clone (CloneDir) and an
419// operator clone that lands and deletes branches.
420type gitFixture struct {
421 t *testing.T
422 origin, clone, ops string
423}
424
425func newGitFixture(t *testing.T) *gitFixture {
426 t.Helper()
427 t.Setenv("GIT_CONFIG_GLOBAL", filepath.Join(t.TempDir(), "gitconfig"))
428 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
429 t.Setenv("GIT_AUTHOR_NAME", "test")
430 t.Setenv("GIT_AUTHOR_EMAIL", "test@example.com")
431 t.Setenv("GIT_COMMITTER_NAME", "test")
432 t.Setenv("GIT_COMMITTER_EMAIL", "test@example.com")
433 dir := t.TempDir()
434 f := &gitFixture{t: t, origin: filepath.Join(dir, "origin.git"), clone: filepath.Join(dir, "clone"), ops: filepath.Join(dir, "ops")}
435 f.git(dir, "init", "-q", "--bare", "-b", "main", f.origin)
436 f.git(dir, "clone", "-q", f.origin, f.ops)
437 f.commitFile(f.ops, "README", "init")
438 f.git(f.ops, "push", "-q", "origin", "HEAD:main")
439 f.git(dir, "clone", "-q", f.origin, f.clone)
440 return f
441}
442
443func (f *gitFixture) git(dir string, args ...string) string {
444 f.t.Helper()
445 cmd := exec.Command("git", args...)
446 cmd.Dir = dir
447 out, err := cmd.CombinedOutput()
448 if err != nil {
449 f.t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
450 }
451 return strings.TrimSpace(string(out))
452}
453
454func (f *gitFixture) commitFile(dir, name, msg string) {
455 f.t.Helper()
456 if err := os.WriteFile(filepath.Join(dir, name), []byte(msg+"\n"), 0o644); err != nil {
457 f.t.Fatal(err)
458 }
459 f.git(dir, "add", name)
460 f.git(dir, "commit", "-q", "-m", msg)
461}
462
463// push commits files on a new branch off origin's main and pushes it, the
464// way a direct-push agent finishes, and returns the run as finalize records it.
465func (f *gitFixture) push(id, prompt string, created time.Time, files ...string) *run.State {
466 f.t.Helper()
467 branch := "agent/" + id
468 f.git(f.clone, "fetch", "-q", "origin")
469 f.git(f.clone, "checkout", "-q", "-b", branch, "origin/main")
470 for _, name := range files {
471 f.commitFile(f.clone, name, name+" on "+branch)
472 }
473 f.git(f.clone, "push", "-q", "origin", branch)
474 sha := f.git(f.clone, "rev-parse", "HEAD")
475 f.git(f.clone, "checkout", "-q", "--detach")
476 f.git(f.clone, "branch", "-q", "-D", branch)
477 clone := f.clone
478 return &run.State{
479 ID: id, Type: "launch", Prompt: prompt, TargetRepo: strPtr("maintainer/site"), CloneDir: &clone,
480 Branch: branch, PushedBranch: &branch, PushedSHA: &sha, CostUSD: float64Ptr(1),
481 CreatedAt: created.Format(time.RFC3339),
482 }
483}
484
485func (f *gitFixture) advanceMain(name string) {
486 f.t.Helper()
487 f.git(f.ops, "fetch", "-q", "origin")
488 f.git(f.ops, "checkout", "-q", "-B", "main", "origin/main")
489 f.commitFile(f.ops, name, "unrelated "+name)
490 f.git(f.ops, "push", "-q", "origin", "main")
491}
492
493func (f *gitFixture) fastForward(sha string) {
494 f.t.Helper()
495 f.git(f.ops, "fetch", "-q", "origin")
496 f.git(f.ops, "push", "-q", "origin", sha+":refs/heads/main")
497}
498
499// integrate lands a branch as the valley's integrator does when it can't
500// fast-forward: one commit, parent main, tree from merge-tree.
501func (f *gitFixture) integrate(branch string) {
502 f.t.Helper()
503 f.git(f.ops, "fetch", "-q", "origin")
504 main := f.git(f.ops, "rev-parse", "origin/main")
505 tree := f.git(f.ops, "merge-tree", "--write-tree", main, f.git(f.ops, "rev-parse", "origin/"+branch))
506 commit := f.git(f.ops, "commit-tree", tree, "-p", main, "-m", "land "+branch)
507 f.git(f.ops, "push", "-q", "origin", commit+":refs/heads/main")
508}
509
510func (f *gitFixture) rebaseOntoMain(branch string) string {
511 f.t.Helper()
512 f.git(f.ops, "fetch", "-q", "origin")
513 f.git(f.ops, "checkout", "-q", "-B", branch, "origin/"+branch)
514 f.git(f.ops, "rebase", "-q", "origin/main")
515 f.git(f.ops, "push", "-q", "--force", "origin", branch)
516 tip := f.git(f.ops, "rev-parse", "HEAD")
517 f.git(f.ops, "checkout", "-q", "--detach")
518 return tip
519}
520
521func (f *gitFixture) deleteBranch(branch string) {
522 f.t.Helper()
523 f.git(f.ops, "push", "-q", "origin", "--delete", branch)
524}
525
526var octRowRe = regexp.MustCompile(`\b(waiting|landed|active) \d\d\b`)
527
528// TestDashboardOctober12 replays the situation of 2026-10-12: seven pushed
529// runs, six of which had already landed on main (by fast-forward, after a
530// rebase, or as an integrator commit; some with their branch deleted since),
531// one still waiting, and an agent running. The waiting branch is the
532// operator's one move and comes first; the six are done.
533func TestDashboardOctober12(t *testing.T) {
534 f := newGitFixture(t)
535 now := time.Now()
536 ago := func(d time.Duration) time.Time { return now.Add(-d) }
537
538 waiting := f.push("20261012-0700-0007", "waiting 01", ago(3*time.Hour), "w.txt")
539 ff := f.push("20261012-0900-0001", "landed 01", ago(50*time.Minute), "a.txt")
540 f.fastForward(*ff.PushedSHA)
541 ffDeleted := f.push("20261012-0900-0002", "landed 02", ago(45*time.Minute), "b.txt")
542 f.fastForward(*ffDeleted.PushedSHA)
543 f.deleteBranch(*ffDeleted.PushedBranch)
544 rebased := f.push("20261012-0900-0003", "landed 03", ago(40*time.Minute), "c.txt")
545 f.advanceMain("u1.txt")
546 f.fastForward(f.rebaseOntoMain(*rebased.PushedBranch))
547 content := f.push("20261012-0900-0004", "landed 04", ago(35*time.Minute), "d1.txt", "d2.txt")
548 f.advanceMain("u2.txt")
549 f.integrate(*content.PushedBranch)
550 contentDeleted := f.push("20261012-0900-0005", "landed 05", ago(30*time.Minute), "e1.txt", "e2.txt", "e3.txt")
551 f.advanceMain("u3.txt")
552 f.integrate(*contentDeleted.PushedBranch)
553 f.deleteBranch(*contentDeleted.PushedBranch)
554 ff2 := f.push("20261012-0900-0006", "landed 06", ago(25*time.Minute), "g.txt")
555 f.fastForward(*ff2.PushedSHA)
556 running := &run.State{ID: "20261012-1000-0008", Type: "launch", Prompt: "active 01", TargetRepo: strPtr("maintainer/site"),
557 TmuxPane: strPtr("%1"), Worktree: "/wt", CreatedAt: ago(5 * time.Minute).Format(time.RFC3339)}
558 states := []*run.State{waiting, ff, ffDeleted, rebased, content, contentDeleted, ff2, running}
559
560 newModel := func() dashboardModel {
561 m := dashboardModel{states: states, tmuxDeps: testDashboardTmuxDeps(), ghStatus: map[string]*prStatus{},
562 hideAfter: defaultHideFinishedAfter, checker: integration.NewGitChecker(nil)}
563 return send(m, tea.WindowSizeMsg{Width: 160, Height: 30})
564 }
565 check := func(m dashboardModel) dashboardModel {
566 t.Helper()
567 msg := checkIntegrationCmd(m.checker, m.states, nil, nil, false)()
568 if _, ok := msg.(integrationMsg); !ok {
569 t.Fatalf("integration check returned %T", msg)
570 }
571 return send(m, msg)
572 }
573 rowsOf := func(view string) []string {
574 var rows []string
575 for _, line := range strings.Split(ansi.Strip(view), "\n") {
576 if p := octRowRe.FindString(line); p != "" {
577 rows = append(rows, p)
578 }
579 }
580 return rows
581 }
582
583 m := check(newModel())
584 view := ansi.Strip(m.View())
585 want := []string{"waiting 01", "active 01", "landed 06", "landed 05", "landed 04", "landed 03", "landed 02", "landed 01"}
586 if got := rowsOf(view); strings.Join(got, ",") != strings.Join(want, ",") {
587 t.Errorf("rows:\n got %v\nwant %v\n%s", got, want, view)
588 }
589 if !strings.Contains(view, "1 yours · 1 agents · 6 done") {
590 t.Errorf("summary should show the one row that's yours:\n%s", view)
591 }
592 if line := lineWith(view, "waiting 01"); !strings.Contains(line, "SUBMIT") {
593 t.Errorf("the waiting branch should be SUBMIT: %q", line)
594 }
595 for _, p := range []string{"landed 01", "landed 02", "landed 03", "landed 06"} {
596 if line := lineWith(view, p); !strings.Contains(line, "INTEGRATED ") {
597 t.Errorf("%s landed by fast-forward: %q", p, line)
598 }
599 }
600 for _, p := range []string{"landed 04", "landed 05"} {
601 if line := lineWith(view, p); !strings.Contains(line, "INTEGRATED~") {
602 t.Errorf("%s landed as an integrator commit: %q", p, line)
603 }
604 }
605
606 // A dashboard opened two hours later never saw the six waiting: once the
607 // check has run, only the waiting branch and the running agent are shown.
608 later := check(newModel())
609 v := later.resolve(now.Add(2 * time.Hour))
610 var shown []string
611 for _, r := range v.rows {
612 shown = append(shown, r.state().Prompt)
613 }
614 if strings.Join(shown, ",") != "waiting 01,active 01" || v.hidden != 6 {
615 t.Errorf("two hours later: shown %v, %d hidden; want [waiting 01 active 01], 6 hidden", shown, v.hidden)
616 }
617}
618
619// fakeGHClient answers the dashboard's PR snapshot queries from a table
620// keyed by PR URL, and records which PRs were asked about.
621type fakeGHClient struct {
622 gh.Client
623 states map[string]string
624 asked map[string][]string // PR URL -> queries
625 pending map[string]bool // PR URLs whose CI is pending
626}
627
628func (f *fakeGHClient) record(ref, q string) { f.asked[ref] = append(f.asked[ref], q) }
629func (f *fakeGHClient) PRSnapshots(_ context.Context, slug string, numbers []int, _ bool) (map[int]*gh.PRSnapshot, error) {
630 out := make(map[int]*gh.PRSnapshot)
631 for _, n := range numbers {
632 ref := fmt.Sprintf("https://github.com/%s/pull/%d", slug, n)
633 f.record(ref, "snapshot")
634 s := &gh.PRSnapshot{Number: n, State: f.states[ref], CI: "passing", Conflicts: "none", ReviewDecision: "APPROVED"}
635 if f.pending[ref] {
636 s.CI = "pending"
637 }
638 out[n] = s
639 }
640 return out, nil
641}
642
643// TestDashboardNoAccessPRs: a PR the agent can't read shows NO ACCESS, is
644// done, is asked about once, and is re-queried every 30 minutes, not
645// every poll. Statuses are keyed by URL, so PR #5 in two repos doesn't
646// collide.
647func TestDashboardNoAccessPRs(t *testing.T) {
648 lost := "https://github.com/maintainer/site/pull/5"
649 readable := "https://github.com/maintainer/klaus/pull/5"
650 states := []*run.State{
651 {ID: "20261005-1000-0001", Type: "launch", Prompt: "site fix", TargetRepo: strPtr("maintainer/site"), PRURL: &lost,
652 CostUSD: float64Ptr(1), CreatedAt: time.Now().Add(-20 * time.Minute).Format(time.RFC3339)},
653 {ID: "20261012-1000-0002", Type: "launch", Prompt: "klaus fix", TargetRepo: strPtr("maintainer/klaus"), PRURL: &readable,
654 CostUSD: float64Ptr(1), CreatedAt: time.Now().Add(-10 * time.Minute).Format(time.RFC3339)},
655 }
656 client := &fakeGHClient{
657 states: map[string]string{lost: gh.StateNoAccess, readable: "OPEN"},
658 asked: map[string][]string{},
659 pending: map[string]bool{readable: true},
660 }
661 m := newDashboardModel(run.NewGitDirStore(t.TempDir()), config.Config{}, client)
662 m.states, m.tmuxDeps = states, testDashboardTmuxDeps()
663 m = send(m, tea.WindowSizeMsg{Width: 160, Height: 20})
664
665 poll := func() {
666 t.Helper()
667 m = send(m, m.fetchGHStatusCmd(m.states)())
668 }
669 poll()
670 if got := strings.Join(client.asked[lost], ","); got != "snapshot" {
671 t.Errorf("queries for the unreadable PR = %s, want one snapshot", got)
672 }
673 if got := strings.Join(client.asked[readable], ","); got != "snapshot" {
674 t.Errorf("the readable PR #5 in another repo should be queried, got %v", client.asked[readable])
675 }
676 view := ansi.Strip(m.View())
677 if line := lineWith(view, "site fix"); !strings.Contains(line, "NO ACCESS") {
678 t.Errorf("site #5 should show NO ACCESS: %q", line)
679 }
680 if line := lineWith(view, "klaus fix"); !strings.Contains(line, "OPEN") || !strings.Contains(line, "CI …") {
681 t.Errorf("klaus #5 keeps its own status: %q", line)
682 }
683 if !strings.Contains(view, "0 yours · 1 pipeline · 1 done") {
684 t.Errorf("the unreadable PR is done:\n%s", view)
685 }
686
687 // The next polls skip it...
688 client.asked = map[string][]string{}
689 poll()
690 if q := client.asked[lost]; len(q) != 0 {
691 t.Errorf("unreadable PR re-queried on the next poll: %v", q)
692 }
693 if line := lineWith(ansi.Strip(m.View()), "site fix"); !strings.Contains(line, "NO ACCESS") {
694 t.Errorf("skipped PR should keep NO ACCESS: %q", line)
695 }
696
697 // ...until 30 minutes have passed; then a fixed credential recovers it.
698 m.noAccessAt[lost] = time.Now().Add(-31 * time.Minute)
699 client.states[lost] = "OPEN"
700 poll()
701 if q := client.asked[lost]; len(q) != 1 {
702 t.Errorf("after 30 minutes the PR should be queried again, got %v", q)
703 }
704 if _, ok := m.noAccessAt[lost]; ok {
705 t.Error("a readable PR should be forgotten as unreadable")
706 }
707 if line := lineWith(ansi.Strip(m.View()), "site fix"); strings.Contains(line, "NO ACCESS") {
708 t.Errorf("recovered PR still shows NO ACCESS: %q", line)
709 }
710}
711
712// TestSubmitCommandInFooter: with dashboard.submit_command set, selecting a
713// SUBMIT row shows the expanded command; other rows don't.
714func TestSubmitCommandInFooter(t *testing.T) {
715 branch := "agent/20261012-0900-0001"
716 states := []*run.State{
717 {ID: "20261012-0900-0001", Type: "launch", Prompt: "pushed", TargetRepo: strPtr("maintainer/site"), CostUSD: float64Ptr(1),
718 CreatedAt: time.Now().Format(time.RFC3339), PushedBranch: &branch, PushedSHA: strPtr("0123456789abcdef0123456789abcdef01234567")},
719 {ID: "20261012-0800-0002", Type: "launch", Prompt: "exited", TargetRepo: strPtr("maintainer/site"), CostUSD: float64Ptr(1),
720 CreatedAt: time.Now().Add(-time.Minute).Format(time.RFC3339)},
721 }
722 m := dashboardModel{states: states, tmuxDeps: testDashboardTmuxDeps(), ghStatus: map[string]*prStatus{},
723 hideAfter: defaultHideFinishedAfter, approveTemplate: "cd ~/hack/{repo} && valley review {branch}"}
724 m = send(m, tea.WindowSizeMsg{Width: 200, Height: 20})
725
726 want := "submit: cd ~/hack/site && valley review " + branch
727 if view := ansi.Strip(m.View()); !strings.Contains(view, want) {
728 t.Errorf("footer should show %q with the SUBMIT row selected:\n%s", want, view)
729 }
730 m = press(m, "j")
731 if view := ansi.Strip(m.View()); strings.Contains(view, "submit:") {
732 t.Errorf("footer should not show a submit command for an exited row:\n%s", view)
733 }
734
735 // Integrated: nothing left to submit.
736 m = press(m, "k")
737 m = send(m, integrationMsg{results: map[string]integration.Result{states[0].ID: {Verdict: integration.Integrated}}})
738 if view := ansi.Strip(m.View()); strings.Contains(view, "submit:") {
739 t.Errorf("footer should not show a submit command once integrated:\n%s", view)
740 }
741}
742
743// TestApproveCommandQuotesValues runs the expanded approve command in a real
744// shell: values a shell would read as code (a branch an agent named, a
745// handle from the valley) arrive as the literal arguments, and plain values
746// stay unquoted.
747func TestApproveCommandQuotesValues(t *testing.T) {
748 pwn := filepath.Join(t.TempDir(), "pwn")
749 sha := "0123456789abcdef0123456789abcdef01234567"
750 for _, tc := range []struct{ branch, handle string }{
751 {"agent/x;touch${IFS}" + pwn, "nxvp"},
752 {"agent/it's-$(touch${IFS}" + pwn + ")", "nx'; touch " + pwn + "; '"},
753 {"agent/plain-1.2_x", "nxvp"},
754 } {
755 branch := tc.branch
756 s := &run.State{ID: "20261012-0900-0001", Type: "launch", Prompt: "pushed", TargetRepo: strPtr("maintainer/site"),
757 CostUSD: float64Ptr(1), CreatedAt: time.Now().Format(time.RFC3339), ChangeID: "nxvp-id",
758 PushedBranch: &branch, PushedSHA: &sha}
759 m := dashboardModel{states: []*run.State{s}, tmuxDeps: testDashboardTmuxDeps(), ghStatus: map[string]*prStatus{},
760 hideAfter: defaultHideFinishedAfter, approveTemplate: `printf '%s\n' {repo} {branch} {change} {handle} {head}`}
761 m = send(m, integrationMsg{results: map[string]integration.Result{s.ID: {Verdict: integration.Ready,
762 Change: &integration.Change{Repo: "site", ChangeID: "nxvp-id", Handle: tc.handle, Version: 1, Head: sha}}}})
763 v := m.resolve(time.Now())
764 verb, cmd := m.approveCommand(v.rows[v.cursor])
765 if verb != "approve" {
766 t.Fatalf("%s: verb %q, want approve", branch, verb)
767 }
768 out, err := exec.Command("sh", "-c", cmd).Output()
769 if err != nil {
770 t.Fatalf("%s: sh -c %q: %v", branch, cmd, err)
771 }
772 if want := strings.Join([]string{"site", branch, "nxvp-id", tc.handle, sha}, "\n") + "\n"; string(out) != want {
773 t.Errorf("sh -c %q printed %q, want %q", cmd, out, want)
774 }
775 if _, err := os.Stat(pwn); err == nil {
776 t.Fatalf("sh -c %q ran code from a value", cmd)
777 }
778 if branch == "agent/plain-1.2_x" && !strings.Contains(cmd, " site agent/plain-1.2_x nxvp-id nxvp "+sha) {
779 t.Errorf("plain values should stay unquoted: %q", cmd)
780 }
781 }
782}
783
784// TestValleyChangeOutlivesOutageAndDeletedBranch drives the dashboard with a
785// real ValleyChecker, a fake valley and real git: a change the valley holds
786// as uncertain stays yours through a valley outage and the deletion of its
787// branch, showing its last known verdict. A dashboard that never saw the
788// valley's view still doesn't count the deleted branch as done.
789func TestValleyChangeOutlivesOutageAndDeletedBranch(t *testing.T) {
790 f := newGitFixture(t)
791 bin := t.TempDir()
792 listing := filepath.Join(bin, "changes.json")
793 script := "#!/bin/sh\nif [ \"$1\" = changes ] && [ -f '" + listing + "' ]; then exec cat '" + listing + "'; fi\n" +
794 "echo 'valley: cannot reach valley-host' >&2\nexit 1\n"
795 if err := os.WriteFile(filepath.Join(bin, "valley"), []byte(script), 0o755); err != nil {
796 t.Fatal(err)
797 }
798 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
799
800 s := f.push("20261012-0900-0001", "tune the cache", time.Now().Add(-3*time.Hour), "cache.txt")
801 s.ChangeID = "uncrkkkkkkkkkkkkkkkkkkkkkkkkkkkk"
802 s.Valley = &run.Valley{Repo: "site", Handle: "uncr", Version: 1, Title: "Tune the cache"}
803 f.advanceMain("other.txt")
804 data := fmt.Sprintf(`{"schema":"valley-changes/v1","host":"valley-host","repos":[{"repo":"site","error":null,
805 "changes":[{"change_id":%q,"handle":"uncr","state":"ready","active":1,"versions":[{"n":1,"head":%q,
806 "title":"Tune the cache","landing":"uncertain","request":{"ref":"refs/valley/requests/uncr","commit":"r"}}]}]}]}`,
807 s.ChangeID, *s.PushedSHA)
808 if err := os.WriteFile(listing, []byte(data), 0o644); err != nil {
809 t.Fatal(err)
810 }
811
812 newModel := func() dashboardModel {
813 m := dashboardModel{states: []*run.State{s}, tmuxDeps: testDashboardTmuxDeps(), ghStatus: map[string]*prStatus{},
814 hideAfter: defaultHideFinishedAfter, checker: integration.NewValleyChecker(nil)}
815 return send(m, tea.WindowSizeMsg{Width: 160, Height: 20})
816 }
817 check := func(m dashboardModel) dashboardModel {
818 return send(m, checkIntegrationCmd(m.checker, m.states, nil, nil, false)())
819 }
820 expect := func(m dashboardModel, step string, want ...string) {
821 t.Helper()
822 v := m.resolve(time.Now())
823 if len(v.rows) != 1 || v.rows[0].category != catYours {
824 t.Fatalf("%s: the change should be yours: %+v", step, v.rows)
825 }
826 line := lineWith(ansi.Strip(m.View()), "uncr")
827 for _, w := range want {
828 if !strings.Contains(line, w) {
829 t.Errorf("%s: row should show %q: %q", step, w, line)
830 }
831 }
832 }
833
834 m := check(newModel())
835 expect(m, "uncertain", "UNCERTAIN", "Tune the cache")
836 if strings.Contains(ansi.Strip(m.View()), "(last known)") {
837 t.Error("a verdict the valley just gave isn't outdated")
838 }
839
840 if err := os.Remove(listing); err != nil { // the valley goes down
841 t.Fatal(err)
842 }
843 m = check(m)
844 expect(m, "outage", "UNCERTAIN", "(last known)")
845
846 f.git(f.ops, "push", "-q", "origin", "--delete", *s.PushedBranch)
847 m = check(m)
848 expect(m, "outage, branch deleted", "UNCERTAIN", "(last known)")
849
850 // Without the valley's earlier view, git alone can't settle it either.
851 fresh := check(newModel())
852 expect(fresh, "first check in the outage, branch deleted", "READY")
853 if line := lineWith(ansi.Strip(fresh.View()), "uncr"); strings.Contains(line, "GONE") {
854 t.Errorf("a deleted branch shouldn't read GONE for a valley change: %q", line)
855 }
856}
857
858// TestChangeRowShowsValleysActiveVersion drives the dashboard with a real
859// ValleyChecker and a fake valley: a change's row shows where the valley's
860// active version stands and approves that version's head, whichever local
861// run is newest. A newer push whose ready failed doesn't take the row over;
862// the footer notes it. An active version marked ready elsewhere holds the
863// row though no local run pushed it.
864func TestChangeRowShowsValleysActiveVersion(t *testing.T) {
865 bin := t.TempDir()
866 listing := filepath.Join(bin, "changes.json")
867 script := "#!/bin/sh\n[ \"$1\" = changes ] && exec cat '" + listing + "'\nexit 1\n"
868 if err := os.WriteFile(filepath.Join(bin, "valley"), []byte(script), 0o755); err != nil {
869 t.Fatal(err)
870 }
871 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
872 const changeID = "nxvpkkkkkkkkkkkkkkkkkkkkkkkkkkkk"
873 sha := func(c byte) string { return strings.Repeat(string(c), 40) }
874 // pushedRun is a run on the change that pushed head ago minutes ago, as
875 // finalize records it.
876 pushedRun := func(id string, ago int, head string, valley *run.Valley) *run.State {
877 branch := "agent/" + id
878 return &run.State{ID: id, Type: "launch", Prompt: "prompt " + id, TargetRepo: strPtr("acme/widget"),
879 ChangeID: changeID, ChangeRepo: "widget", PushedBranch: &branch, PushedSHA: &head, Valley: valley,
880 CostUSD: float64Ptr(1), CreatedAt: time.Now().Add(-time.Duration(ago) * time.Minute).Format(time.RFC3339)}
881 }
882 readied := func(version int) *run.Valley {
883 return &run.Valley{Repo: "widget", Handle: "nxvp", Version: version, Title: "Add a health check"}
884 }
885 version := func(n int, head, branch string) string {
886 return fmt.Sprintf(`{"n":%d,"head":%q,"branch":%q,"title":"Add a health check v%d","landing":"not-landed"}`, n, head, branch, n)
887 }
888 writeListing := func(active int, versions ...string) {
889 data := fmt.Sprintf(`{"schema":"valley-changes/v1","host":"valley-host","repos":[{"repo":"widget","error":null,
890 "changes":[{"change_id":%q,"handle":"nxvp","state":"ready","active":%d,"versions":[%s]}]}]}`,
891 changeID, active, strings.Join(versions, ","))
892 if err := os.WriteFile(listing, []byte(data), 0o644); err != nil {
893 t.Fatal(err)
894 }
895 }
896 // show checks the states as the dashboard would and returns its one row
897 // and its screen.
898 show := func(states ...*run.State) (dashRow, string, dashboardModel) {
899 t.Helper()
900 m := dashboardModel{states: states, tmuxDeps: testDashboardTmuxDeps(), ghStatus: map[string]*prStatus{},
901 hideAfter: defaultHideFinishedAfter, checker: integration.NewValleyChecker(nil),
902 approveTemplate: "valley approve {handle} --head {head} # {branch}"}
903 m = send(m, tea.WindowSizeMsg{Width: 200, Height: 20})
904 m = send(m, checkIntegrationCmd(m.checker, m.states, nil, nil, false)())
905 rows := m.buildRows()
906 if len(rows) != 1 {
907 t.Fatalf("%d rows, want the change's one", len(rows))
908 }
909 return rows[0], ansi.Strip(m.View()), m
910 }
911
912 t.Run("newer push not ready", func(t *testing.T) {
913 v1 := pushedRun("20261013-0900-0001", 30, sha('1'), readied(1))
914 newer := pushedRun("20261013-0900-0002", 5, sha('2'), &run.Valley{Error: "valley ready: refused"})
915 writeListing(1, version(1, sha('1'), *v1.PushedBranch))
916 r, screen, m := show(v1, newer)
917 if r.category != catYours || r.current != v1 {
918 t.Errorf("row %s, current %v; want yours, held by v1", categoryNames[r.category], r.current)
919 }
920 if line := lineWith(screen, "nxvp"); !strings.Contains(line, "READY v1@1111111") || strings.Contains(line, "SUBMIT") {
921 t.Errorf("the row should read v1 as the valley holds it: %q", line)
922 }
923 if _, cmd := m.approveCommand(r); cmd != "valley approve nxvp --head "+sha('1')+" # "+*v1.PushedBranch {
924 t.Errorf("approve command %q should bind v1's head and branch", cmd)
925 }
926 if !strings.Contains(screen, "approve: valley approve nxvp --head "+sha('1')) ||
927 !strings.Contains(screen, "a newer push 2222222 isn't ready") {
928 t.Errorf("the footer should offer v1's approval and note the newer push:\n%s", screen)
929 }
930 })
931
932 t.Run("active version readied elsewhere", func(t *testing.T) {
933 v1 := pushedRun("20261013-0900-0001", 30, sha('1'), readied(1))
934 v2 := pushedRun("20261013-0900-0002", 20, sha('2'), readied(2))
935 writeListing(3, version(1, sha('1'), *v1.PushedBranch), version(2, sha('2'), *v2.PushedBranch),
936 version(3, sha('3'), "agent/elsewhere"))
937 r, screen, m := show(v1, v2)
938 if r.category != catYours || r.current != nil {
939 t.Errorf("row %s, current %v; want yours, with no local run holding it", categoryNames[r.category], r.current)
940 }
941 if line := lineWith(screen, "nxvp"); !strings.Contains(line, "READY v3@3333333") || !strings.Contains(line, "Add a health check v3") {
942 t.Errorf("the row should read v3 as the valley holds it: %q", line)
943 }
944 if _, cmd := m.approveCommand(r); cmd != "valley approve nxvp --head "+sha('3')+" # agent/elsewhere" {
945 t.Errorf("approve command %q should bind v3's head and branch", cmd)
946 }
947 if strings.Contains(screen, "SUPERSEDED") || strings.Contains(screen, "isn't ready") {
948 t.Errorf("local versions fold into the row, and both are versions the valley holds:\n%s", screen)
949 }
950 })
951}
952
953// TestPRRowTakesItsChangesRunsWithoutAPR: a run that stopped at the usage
954// limit before opening its PR joins the row of its change's PR, behind the
955// PR's agent. Its attention stops counting only once a run records taking
956// its work on (TookOver) and is running or finished, whatever the creation
957// times say: then nothing reads ATTN, whether the PR is open or merged. A
958// successor that ended needing attention or failing carries the attention
959// itself, whatever became of its PR: merged, closed or out of reach. A
960// follow-up that only resumed it, on a fresh branch, or one that never
961// finished, hands nothing off. Salvage newer than a merged PR is
962// still the operator's, and a running follow-up without a PR runs on the
963// PR's row. A push without a PR after the PR keeps its change's own row
964// while it waits for integration, and folds into the PR's once it landed.
965func TestPRRowTakesItsChangesRunsWithoutAPR(t *testing.T) {
966 now := time.Now()
967 n := 0
968 var states []*run.State
969 chg := func(c byte) string { return strings.Repeat(string(c), 32) }
970 add := func(prompt, change string, minutesAgo int, s *run.State) *run.State {
971 n++
972 s.ID = fmt.Sprintf("20261020-1200-%04d", n)
973 s.Prompt, s.Type, s.ChangeID = prompt, "launch", change
974 s.TargetRepo = strPtr("o/r")
975 s.CreatedAt = now.Add(-time.Duration(minutesAgo) * time.Minute).Format(time.RFC3339)
976 if s.TmuxPane == nil {
977 s.CostUSD = float64Ptr(1)
978 }
979 states = append(states, s)
980 return s
981 }
982 salvaged := func(prompt, change string, minutesAgo int) *run.State {
983 branch := "agent/" + strings.ReplaceAll(prompt, " ", "-")
984 return add(prompt, change, minutesAgo, &run.State{
985 NeedsAttention: strPtr("session_limit; branch " + branch + " preserved (pushed)"),
986 PushedBranch: &branch, PushedSHA: strPtr(strings.Repeat("a", 40)),
987 })
988 }
989 pr := func(num int) *string { return strPtr(fmt.Sprintf("https://github.com/o/r/pull/%d", num)) }
990 open := &prStatus{State: "OPEN", CI: "pending", Conflicts: "none"}
991 status := map[string]*prStatus{}
992
993 a := salvaged("stopped before 335", chg('x'), 60)
994 status[*add("opened 335", chg('x'), 30, &run.State{PRURL: pr(335), TookOver: []string{a.ID}}).PRURL] = &prStatus{State: "MERGED"}
995 // Its successor's clock ran behind: created "before" it.
996 b := salvaged("stopped before 334", chg('y'), 60)
997 status[*add("opened 334", chg('y'), 90, &run.State{PRURL: pr(334), TookOver: []string{b.ID}}).PRURL] = open
998 add("opened 336", chg('z'), 60, &run.State{PRURL: pr(336), MergedAt: strPtr(now.Add(-time.Hour).Format(time.RFC3339))})
999 salvaged("stopped after 336 merged", chg('z'), 10)
1000 running := add("opened 337", chg('v'), 50, &run.State{PRURL: pr(337)})
1001 status[*running.PRURL] = open
1002 follow := add("following up 337", chg('v'), 5, &run.State{TmuxPane: strPtr("%1")})
1003 salvaged("stopped with no follow-up", chg('w'), 20)
1004 // Resumed on a fresh branch: the successor recorded no handoff.
1005 fresh := salvaged("stopped before 338", chg('u'), 40)
1006 status[*add("resumed it on a fresh branch", chg('u'), 15, &run.State{PRURL: pr(338), OriginalRunID: &fresh.ID}).PRURL] = open
1007 // Its successor took it on and was salvaged in turn, or failed.
1008 c := salvaged("stopped, taken on, stopped again", chg('t'), 40)
1009 add("took it on and stopped", chg('t'), 20, &run.State{TookOver: []string{c.ID},
1010 NeedsAttention: strPtr("session_limit; branch agent/t preserved (pushed)")})
1011 d := salvaged("stopped, taken on, crashed", chg('s'), 40)
1012 add("took it on and crashed", chg('s'), 20, &run.State{TookOver: []string{d.ID}, FailureReason: strPtr("error_during_execution")})
1013 // Its successor continued it under a PR and failed, and the PR merged,
1014 // closed or went out of reach: the attention it took on stays.
1015 var failedUnderPR []*run.State
1016 for i, st := range []string{"MERGED", "CLOSED", gh.StateNoAccess} {
1017 f := salvaged(fmt.Sprintf("stopped before %d", 341+i), chg(byte('l'+i)), 40)
1018 failedUnderPR = append(failedUnderPR, f)
1019 status[*add(fmt.Sprintf("took it on under %d and crashed", 341+i), chg(byte('l'+i)), 20, &run.State{PRURL: pr(341 + i),
1020 TookOver: []string{f.ID}, FailureReason: strPtr("error_during_execution")}).PRURL] = &prStatus{State: st}
1021 }
1022 // Its successor's pane is gone and it never finished.
1023 e := salvaged("stopped, taken on, vanished", chg('q'), 40)
1024 add("took it on and vanished", chg('q'), 20, &run.State{TookOver: []string{e.ID}, TmuxPane: strPtr("gone")})
1025 // A push after the PR waits on its own row until it lands; then it
1026 // folds into the PR's.
1027 status[*add("opened 339", chg('r'), 60, &run.State{PRURL: pr(339)}).PRURL] = &prStatus{State: "MERGED"}
1028 waiting := add("pushed after 339", chg('r'), 30, &run.State{PushedBranch: strPtr("agent/r"), PushedSHA: strPtr(strings.Repeat("b", 40))})
1029 status[*add("opened 340", chg('p'), 60, &run.State{PRURL: pr(340)}).PRURL] = &prStatus{State: "MERGED"}
1030 landed := add("pushed and landed after 340", chg('p'), 30, &run.State{PushedBranch: strPtr("agent/p"), PushedSHA: strPtr(strings.Repeat("c", 40))})
1031
1032 m := dashboardModel{states: states, tmuxDeps: testDashboardTmuxDeps(), ghStatus: status, hideAfter: defaultHideFinishedAfter,
1033 integration: map[string]integration.Result{waiting.ID: {Verdict: integration.Awaiting}, landed.ID: {Verdict: integration.Integrated}}}
1034 rows := m.buildRows()
1035 type want struct {
1036 key, category string
1037 attention bool
1038 runs, running int
1039 }
1040 wants := map[string]want{
1041 "opened 339": {"pr:o/r#339", "done", false, 1, 0},
1042 "pushed after 339": {"change:o/r#" + chg('r'), "yours", false, 1, 0},
1043 "opened 340": {"pr:o/r#340", "done", false, 2, 0},
1044 "opened 335": {"pr:o/r#335", "done", false, 2, 0},
1045 "opened 334": {"pr:o/r#334", "pipeline", false, 2, 0},
1046 "opened 336": {"pr:o/r#336", "yours", true, 2, 0},
1047 "opened 337": {"pr:o/r#337", "agents", false, 2, 1},
1048 "stopped with no follow-up": {"change:o/r#" + chg('w'), "yours", true, 1, 0},
1049 "resumed it on a fresh branch": {"pr:o/r#338", "yours", true, 2, 0},
1050 "took it on and stopped": {"change:o/r#" + chg('t'), "yours", true, 2, 0},
1051 "took it on and crashed": {"change:o/r#" + chg('s'), "yours", true, 2, 0},
1052 "took it on and vanished": {"change:o/r#" + chg('q'), "yours", true, 2, 0},
1053 "took it on under 341 and crashed": {"pr:o/r#341", "yours", true, 2, 0},
1054 "took it on under 342 and crashed": {"pr:o/r#342", "yours", true, 2, 0},
1055 "took it on under 343 and crashed": {"pr:o/r#343", "yours", true, 2, 0},
1056 }
1057 if len(rows) != len(wants) {
1058 t.Errorf("%d rows, want %d", len(rows), len(wants))
1059 }
1060 for _, r := range rows {
1061 prompt := r.state().Prompt
1062 w, ok := wants[prompt]
1063 if !ok {
1064 t.Errorf("unexpected row %q (%s)", prompt, r.key)
1065 continue
1066 }
1067 if r.key != w.key || categoryNames[r.category] != w.category || r.attention != w.attention ||
1068 len(r.runs) != w.runs || len(r.running) != w.running {
1069 t.Errorf("%q: %s %s, attention %v, %d runs, %d running; want %+v",
1070 prompt, r.key, categoryNames[r.category], r.attention, len(r.runs), len(r.running), w)
1071 }
1072 }
1073 superseded := supersededRuns(states, m.agentRunning)
1074 for _, s := range append([]*run.State{a, b, c, d}, failedUnderPR...) {
1075 if !superseded[s.ID] {
1076 t.Errorf("%q was taken on: it should be superseded", s.Prompt)
1077 }
1078 }
1079 for _, s := range []*run.State{fresh, e} {
1080 if superseded[s.ID] {
1081 t.Errorf("%q handed nothing off: it should still need attention", s.Prompt)
1082 }
1083 }
1084
1085 m = send(m, tea.WindowSizeMsg{Width: 200, Height: 30})
1086 plain := ansi.Strip(m.View())
1087 for _, num := range []string{"#335", "#334"} {
1088 if line := lineWith(plain, num+" "); line == "" || strings.Contains(line, "ATTN") {
1089 t.Errorf("%s should show, without ATTN: %q\n%s", num, line, plain)
1090 }
1091 }
1092 if line := lineWith(plain, "#336 "); !strings.Contains(line, "MERGED") || !strings.Contains(line, "ATTN") {
1093 t.Errorf("salvage after #336 merged should show ATTN on its row: %q", line)
1094 }
1095 for _, num := range []string{"#341", "#342", "#343"} {
1096 if line := lineWith(plain, num+" "); !strings.Contains(line, "ATTN") {
1097 t.Errorf("the attention %s's failed run took on should show ATTN on its row: %q\n%s", num, line, plain)
1098 }
1099 }
1100 if line := lineWith(plain, "#337 "); !strings.Contains(line, "agent:"+shortRunID(follow.ID)+" running") {
1101 t.Errorf("the follow-up should run on #337's row: %q", line)
1102 }
1103}
1104
1105// TestSameNamedReposAreDifferentChanges: the same change ID in alice/widget
1106// and bob/widget names two changes. bob's salvaged run doesn't join alice's
1107// PR, and alice's run recording it as taken on (it can't, in practice)
1108// doesn't supersede it. A run that knows its repo only by its short name
1109// joins the one owner its change's other runs are known by.
1110func TestSameNamedReposAreDifferentChanges(t *testing.T) {
1111 now := time.Now().Format(time.RFC3339)
1112 change := strings.Repeat("k", 32)
1113 branch, sha := "agent/x", strings.Repeat("a", 40)
1114 bob := &run.State{ID: "20261021-1200-0001", Type: "launch", Prompt: "bob's salvage", ChangeID: change,
1115 TargetRepo: strPtr("bob/widget"), RepoKey: "bob/widget", CreatedAt: now, CostUSD: float64Ptr(1),
1116 NeedsAttention: strPtr("session_limit"), PushedBranch: &branch, PushedSHA: &sha}
1117 alice := &run.State{ID: "20261021-1200-0002", Type: "launch", Prompt: "alice's PR", ChangeID: change,
1118 TargetRepo: strPtr("widget"), PRURL: strPtr("https://github.com/alice/widget/pull/7"),
1119 TookOver: []string{bob.ID}, CreatedAt: now, CostUSD: float64Ptr(1)}
1120 short := &run.State{ID: "20261021-1200-0003", Type: "launch", Prompt: "alice's salvage, by short name", ChangeID: change,
1121 TargetRepo: strPtr("widget"), CreatedAt: now, CostUSD: float64Ptr(1), NeedsAttention: strPtr("session_limit")}
1122 states := []*run.State{bob, alice}
1123
1124 changeOf := changeKeys(states)
1125 kb, _ := changeOf(bob)
1126 ka, _ := changeOf(alice)
1127 if kb == ka || kb.Repo != "bob/widget" || ka.Repo != "alice/widget" {
1128 t.Errorf("bob's change %+v and alice's %+v should differ, by owner", kb, ka)
1129 }
1130 if supersededRuns(states, func(*run.State) bool { return false })[bob.ID] {
1131 t.Error("a run in alice/widget can't take bob/widget's work on")
1132 }
1133 m := dashboardModel{states: states, tmuxDeps: testDashboardTmuxDeps(),
1134 ghStatus: map[string]*prStatus{*alice.PRURL: {State: "MERGED"}}, hideAfter: defaultHideFinishedAfter}
1135 for _, r := range m.buildRows() {
1136 if len(r.runs) != 1 {
1137 t.Errorf("row %s holds %d runs; each repo's run should have its own row", r.key, len(r.runs))
1138 }
1139 if r.state() == bob && (!r.attention || r.category != catYours) {
1140 t.Errorf("bob's salvage should read ATTN, yours: %s attention %v", categoryNames[r.category], r.attention)
1141 }
1142 }
1143
1144 // Known only by its short name, alice's salvage joins alice's change:
1145 // the one owner known for it among these runs.
1146 if k, _ := changeKeys([]*run.State{alice, short})(short); k != ka {
1147 t.Errorf("a run known by its short name should take the one known owner: %+v, want %+v", k, ka)
1148 }
1149 // With two owners known, it can't tell which, and joins neither.
1150 if k, _ := changeKeys([]*run.State{alice, bob, short})(short); k == ka || k == kb {
1151 t.Errorf("with two owners known, a run known by its short name should join neither: %+v", k)
1152 }
1153}
1154
1155// TestSameNumberedPRsInSameNamedRepos: alice/widget#7 and bob/widget#7 are
1156// two PRs, though their runs know the repo by its short name, as the
1157// project registry names a registered widget: each has its own row, with
1158// its own status. A run that names alice's repo in full shares alice's
1159// row, whatever the registry calls it.
1160func TestSameNumberedPRsInSameNamedRepos(t *testing.T) {
1161 now := time.Now()
1162 at := func(minutesAgo int) string {
1163 return now.Add(-time.Duration(minutesAgo) * time.Minute).Format(time.RFC3339)
1164 }
1165 alicePR, bobPR := "https://github.com/alice/widget/pull/7", "https://github.com/bob/widget/pull/7"
1166 states := []*run.State{
1167 {ID: "20261021-1200-0001", Type: "launch", Prompt: "alice's PR", TargetRepo: strPtr("widget"), PRURL: &alicePR, CreatedAt: at(30), CostUSD: float64Ptr(1)},
1168 {ID: "20261021-1200-0002", Type: "launch", Prompt: "bob's PR", TargetRepo: strPtr("widget"), PRURL: &bobPR, CreatedAt: at(20), CostUSD: float64Ptr(1)},
1169 {ID: "20261021-1200-0003", Type: "pr-fix", Prompt: "alice's fix", TargetRepo: strPtr("alice/widget"), PRURL: &alicePR, CreatedAt: at(10), CostUSD: float64Ptr(1)},
1170 }
1171 m := dashboardModel{states: states, tmuxDeps: testDashboardTmuxDeps(), hideAfter: defaultHideFinishedAfter,
1172 ghStatus: map[string]*prStatus{alicePR: {State: "MERGED"}, bobPR: {State: "OPEN", CI: "pending", Conflicts: "none"}}}
1173 rows := m.buildRows()
1174 got := make(map[string]string)
1175 for _, r := range rows {
1176 got[r.key] = fmt.Sprintf("%s, %d runs", categoryNames[r.category], len(r.runs))
1177 }
1178 want := map[string]string{"pr:alice/widget#7": "done, 2 runs", "pr:bob/widget#7": "pipeline, 1 runs"}
1179 if fmt.Sprint(got) != fmt.Sprint(want) {
1180 t.Errorf("rows %v, want %v", got, want)
1181 }
1182}