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