| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "os" |
| 6 | "path/filepath" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | "time" |
| 10 | |
| 11 | tea "github.com/charmbracelet/bubbletea" |
| 12 | "the-valley/flow/internal/config" |
| 13 | "the-valley/flow/internal/event" |
| 14 | gh "the-valley/flow/internal/github" |
| 15 | "the-valley/flow/internal/integration" |
| 16 | "the-valley/flow/internal/pipeline" |
| 17 | "the-valley/flow/internal/project" |
| 18 | "the-valley/flow/internal/run" |
| 19 | "the-valley/flow/internal/webhook" |
| 20 | ) |
| 21 | |
| 22 | // testDashboardTmuxDeps returns TmuxDeps for dashboard tests: |
| 23 | // panes starting with "%" exist, all are idle (finalized), none dead. |
| 24 | func testDashboardTmuxDeps() run.TmuxDeps { |
| 25 | return run.TmuxDeps{ |
| 26 | PaneExists: func(paneID string) bool { |
| 27 | return strings.HasPrefix(paneID, "%") |
| 28 | }, |
| 29 | PaneIsIdle: func(string) bool { return true }, |
| 30 | PaneIsDead: func(string) bool { return false }, |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | func TestGroupByRepo(t *testing.T) { |
| 35 | states := []*run.State{ |
| 36 | {ID: "1", TargetRepo: strPtr("owner/repoA"), Type: "launch"}, |
| 37 | {ID: "2", TargetRepo: strPtr("owner/repoB"), Type: "launch"}, |
| 38 | {ID: "3", TargetRepo: strPtr("owner/repoA"), Type: "launch"}, |
| 39 | {ID: "4", Type: "session"}, // sessions should be excluded |
| 40 | } |
| 41 | |
| 42 | groups := groupByRepo(states) |
| 43 | if len(groups) != 2 { |
| 44 | t.Fatalf("expected 2 groups, got %d", len(groups)) |
| 45 | } |
| 46 | if groups[0].Repo != "owner/repoA" { |
| 47 | t.Errorf("first group repo = %q, want %q", groups[0].Repo, "owner/repoA") |
| 48 | } |
| 49 | if len(groups[0].Runs) != 2 { |
| 50 | t.Errorf("repoA runs = %d, want 2", len(groups[0].Runs)) |
| 51 | } |
| 52 | if groups[1].Repo != "owner/repoB" { |
| 53 | t.Errorf("second group repo = %q, want %q", groups[1].Repo, "owner/repoB") |
| 54 | } |
| 55 | if len(groups[1].Runs) != 1 { |
| 56 | t.Errorf("repoB runs = %d, want 1", len(groups[1].Runs)) |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | func TestGroupByRepo_SessionsExcluded(t *testing.T) { |
| 61 | states := []*run.State{ |
| 62 | {ID: "1", Type: "session"}, |
| 63 | {ID: "2", Type: "session"}, |
| 64 | } |
| 65 | groups := groupByRepo(states) |
| 66 | if len(groups) != 0 { |
| 67 | t.Fatalf("expected 0 groups for session-only states, got %d", len(groups)) |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | func TestGroupByRepo_Empty(t *testing.T) { |
| 72 | groups := groupByRepo(nil) |
| 73 | if len(groups) != 0 { |
| 74 | t.Fatalf("expected 0 groups for nil states, got %d", len(groups)) |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | func TestGroupByRepo_PRURLFallback(t *testing.T) { |
| 79 | states := []*run.State{ |
| 80 | {ID: "1", Type: "launch", PRURL: strPtr("https://github.com/owner/repo/pull/42")}, |
| 81 | } |
| 82 | groups := groupByRepo(states) |
| 83 | if len(groups) != 1 { |
| 84 | t.Fatalf("expected 1 group, got %d", len(groups)) |
| 85 | } |
| 86 | if groups[0].Repo != "owner/repo" { |
| 87 | t.Errorf("repo = %q, want %q", groups[0].Repo, "owner/repo") |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | func TestRepoFromPRURL(t *testing.T) { |
| 92 | tests := []struct { |
| 93 | url string |
| 94 | want string |
| 95 | }{ |
| 96 | {"https://github.com/owner/repo/pull/42", "owner/repo"}, |
| 97 | {"https://github.com/maintainer/klaus/pull/1", "maintainer/klaus"}, |
| 98 | {"http://github.com/a/b/pull/99", "a/b"}, |
| 99 | {"notaurl", "(unknown)"}, |
| 100 | {"https://github.com/solo", "(unknown)"}, |
| 101 | } |
| 102 | for _, tt := range tests { |
| 103 | t.Run(tt.url, func(t *testing.T) { |
| 104 | got := repoFromPRURL(tt.url) |
| 105 | if got != tt.want { |
| 106 | t.Errorf("repoFromPRURL(%q) = %q, want %q", tt.url, got, tt.want) |
| 107 | } |
| 108 | }) |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | func TestRepoFromState(t *testing.T) { |
| 113 | tests := []struct { |
| 114 | name string |
| 115 | s *run.State |
| 116 | want string |
| 117 | }{ |
| 118 | { |
| 119 | name: "uses TargetRepo when set", |
| 120 | s: &run.State{TargetRepo: strPtr("owner/repo")}, |
| 121 | want: "owner/repo", |
| 122 | }, |
| 123 | { |
| 124 | name: "falls back to PR URL", |
| 125 | s: &run.State{PRURL: strPtr("https://github.com/owner/repo2/pull/1")}, |
| 126 | want: "owner/repo2", |
| 127 | }, |
| 128 | { |
| 129 | name: "local when nothing set", |
| 130 | s: &run.State{}, |
| 131 | want: "(local)", |
| 132 | }, |
| 133 | } |
| 134 | for _, tt := range tests { |
| 135 | t.Run(tt.name, func(t *testing.T) { |
| 136 | got := repoFromState(tt.s, nil) |
| 137 | if got != tt.want { |
| 138 | t.Errorf("repoFromState() = %q, want %q", got, tt.want) |
| 139 | } |
| 140 | }) |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | func TestRepoFromState_WithRegistry(t *testing.T) { |
| 145 | reg := &project.Registry{ |
| 146 | Projects: map[string]string{ |
| 147 | "site": "/home/user/src/site", |
| 148 | }, |
| 149 | } |
| 150 | |
| 151 | tests := []struct { |
| 152 | name string |
| 153 | s *run.State |
| 154 | want string |
| 155 | }{ |
| 156 | { |
| 157 | name: "owner/repo normalizes to project name", |
| 158 | s: &run.State{TargetRepo: strPtr("maintainer/site")}, |
| 159 | want: "site", |
| 160 | }, |
| 161 | { |
| 162 | name: "project name stays as-is", |
| 163 | s: &run.State{TargetRepo: strPtr("site")}, |
| 164 | want: "site", |
| 165 | }, |
| 166 | { |
| 167 | name: "unregistered owner/repo stays as-is", |
| 168 | s: &run.State{TargetRepo: strPtr("maintainer/other")}, |
| 169 | want: "maintainer/other", |
| 170 | }, |
| 171 | { |
| 172 | name: "PRURL fallback normalizes to project name", |
| 173 | s: &run.State{PRURL: strPtr("https://github.com/maintainer/site/pull/42")}, |
| 174 | want: "site", |
| 175 | }, |
| 176 | { |
| 177 | name: "local when nothing set", |
| 178 | s: &run.State{}, |
| 179 | want: "(local)", |
| 180 | }, |
| 181 | } |
| 182 | for _, tt := range tests { |
| 183 | t.Run(tt.name, func(t *testing.T) { |
| 184 | got := repoFromState(tt.s, reg) |
| 185 | if got != tt.want { |
| 186 | t.Errorf("repoFromState() = %q, want %q", got, tt.want) |
| 187 | } |
| 188 | }) |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | func TestComputeTotalCost(t *testing.T) { |
| 193 | c1, c2 := 1.50, 3.25 |
| 194 | states := []*run.State{ |
| 195 | {CostUSD: &c1}, |
| 196 | {CostUSD: &c2}, |
| 197 | {}, // no cost |
| 198 | } |
| 199 | got := computeTotalCost(states) |
| 200 | if got != 4.75 { |
| 201 | t.Errorf("computeTotalCost() = %f, want 4.75", got) |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | func TestComputeTotalCost_Empty(t *testing.T) { |
| 206 | got := computeTotalCost(nil) |
| 207 | if got != 0 { |
| 208 | t.Errorf("computeTotalCost(nil) = %f, want 0", got) |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | func TestFooterCountsRunningAgents(t *testing.T) { |
| 213 | m := dashboardModel{tmuxDeps: testDashboardTmuxDeps()} |
| 214 | states := []*run.State{ |
| 215 | {ID: "1", Type: "launch"}, // not running (no pane) |
| 216 | {ID: "2", Type: "launch", TmuxPane: strPtr("%2"), CostUSD: float64Ptr(1.0)}, // finished |
| 217 | {ID: "3", Type: "pr-fix", TmuxPane: strPtr("%3")}, // running |
| 218 | {ID: "4", Type: "session"}, // excluded |
| 219 | {ID: "5", Type: "launch", TmuxPane: strPtr("%5"), DurationMS: int64Ptr(5000)}, // finished |
| 220 | {ID: "6", Type: "launch", TmuxPane: strPtr("%6")}, // running |
| 221 | } |
| 222 | m.states = states |
| 223 | if footer := m.renderFooter(m.resolve(time.Now()), 200); !strings.Contains(footer, "2/5 agents running") { |
| 224 | t.Errorf("footer = %q, want 2/5 agents running", footer) |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | func TestIsAgentRunning(t *testing.T) { |
| 229 | m := &dashboardModel{tmuxDeps: testDashboardTmuxDeps()} |
| 230 | tests := []struct { |
| 231 | name string |
| 232 | s *run.State |
| 233 | want bool |
| 234 | }{ |
| 235 | {"no pane", &run.State{}, false}, |
| 236 | {"pane but finalized with cost", &run.State{TmuxPane: strPtr("%1"), CostUSD: float64Ptr(1.0)}, false}, |
| 237 | {"pane but finalized with duration", &run.State{TmuxPane: strPtr("%1"), DurationMS: int64Ptr(1000)}, false}, |
| 238 | {"pane and not finalized", &run.State{TmuxPane: strPtr("%1")}, true}, |
| 239 | } |
| 240 | for _, tt := range tests { |
| 241 | t.Run(tt.name, func(t *testing.T) { |
| 242 | got := m.isAgentRunning(tt.s) |
| 243 | if got != tt.want { |
| 244 | t.Errorf("isAgentRunning() = %v, want %v", got, tt.want) |
| 245 | } |
| 246 | }) |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | func TestComputeSessionDuration(t *testing.T) { |
| 251 | now := time.Now() |
| 252 | past := now.Add(-2 * time.Hour) |
| 253 | states := []*run.State{ |
| 254 | {CreatedAt: now.Format(time.RFC3339)}, |
| 255 | {CreatedAt: past.Format(time.RFC3339)}, |
| 256 | } |
| 257 | dur := computeSessionDuration(states) |
| 258 | if dur < 1*time.Hour { |
| 259 | t.Errorf("duration = %v, want >= 1h", dur) |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | func TestComputeSessionDuration_Empty(t *testing.T) { |
| 264 | dur := computeSessionDuration(nil) |
| 265 | if dur != 0 { |
| 266 | t.Errorf("duration = %v, want 0", dur) |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | func TestShortRunID(t *testing.T) { |
| 271 | tests := []struct { |
| 272 | id string |
| 273 | want string |
| 274 | }{ |
| 275 | {"20260307-0913-3db3", "3db3"}, |
| 276 | {"ab", "ab"}, |
| 277 | {"abcd", "abcd"}, |
| 278 | {"", ""}, |
| 279 | } |
| 280 | for _, tt := range tests { |
| 281 | t.Run(tt.id, func(t *testing.T) { |
| 282 | got := shortRunID(tt.id) |
| 283 | if got != tt.want { |
| 284 | t.Errorf("shortRunID(%q) = %q, want %q", tt.id, got, tt.want) |
| 285 | } |
| 286 | }) |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | func TestFormatDuration(t *testing.T) { |
| 291 | tests := []struct { |
| 292 | dur time.Duration |
| 293 | want string |
| 294 | }{ |
| 295 | {0, "0m"}, |
| 296 | {5 * time.Minute, "5m"}, |
| 297 | {90 * time.Minute, "1h 30m"}, |
| 298 | {2*time.Hour + 5*time.Minute, "2h 05m"}, |
| 299 | } |
| 300 | for _, tt := range tests { |
| 301 | t.Run(tt.want, func(t *testing.T) { |
| 302 | got := formatDuration(tt.dur) |
| 303 | if got != tt.want { |
| 304 | t.Errorf("formatDuration(%v) = %q, want %q", tt.dur, got, tt.want) |
| 305 | } |
| 306 | }) |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | func TestPluralS(t *testing.T) { |
| 311 | if pluralS(1) != "" { |
| 312 | t.Error("pluralS(1) should be empty") |
| 313 | } |
| 314 | if pluralS(0) != "s" { |
| 315 | t.Error("pluralS(0) should be 's'") |
| 316 | } |
| 317 | if pluralS(5) != "s" { |
| 318 | t.Error("pluralS(5) should be 's'") |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | func TestAgentStatusLabel(t *testing.T) { |
| 323 | pushed := &run.State{PushedBranch: strPtr("agent/x"), PushedSHA: strPtr("0123456789abcdef0123456789abcdef01234567")} |
| 324 | tests := []struct { |
| 325 | name string |
| 326 | s *run.State |
| 327 | want string |
| 328 | }{ |
| 329 | {"with PR", &run.State{PRURL: strPtr("https://github.com/o/r/pull/1")}, "PR"}, |
| 330 | {"no PR", &run.State{}, "EXITED"}, |
| 331 | {"needs attention", &run.State{NeedsAttention: strPtr("no_pr"), PRURL: strPtr("https://github.com/o/r/pull/1")}, "ATTN"}, |
| 332 | {"pushed, not yet checked", pushed, "SUBMIT"}, |
| 333 | {"pushed, awaiting", pushed, "SUBMIT"}, |
| 334 | {"pushed, landed by ancestry", pushed, "INTEGRATED"}, |
| 335 | {"pushed, landed by content", pushed, "INTEGRATED~"}, |
| 336 | {"pushed, branch deleted", pushed, "GONE"}, |
| 337 | {"valley, not yet checked", pushed, "READY"}, |
| 338 | {"valley, check fell back to git", pushed, "READY"}, |
| 339 | {"valley, ready", pushed, "READY"}, |
| 340 | {"valley, landed", pushed, "INTEGRATED"}, |
| 341 | {"valley, superseded", pushed, "OLDER VERSION"}, |
| 342 | } |
| 343 | verdicts := map[string]integration.Verdict{ |
| 344 | "pushed, awaiting": integration.Awaiting, |
| 345 | "pushed, landed by ancestry": integration.Integrated, |
| 346 | "pushed, landed by content": integration.IntegratedContent, |
| 347 | "pushed, branch deleted": integration.Gone, |
| 348 | "valley, check fell back to git": integration.Awaiting, |
| 349 | "valley, ready": integration.Ready, |
| 350 | "valley, landed": integration.Integrated, |
| 351 | "valley, superseded": integration.Superseded, |
| 352 | } |
| 353 | for _, tt := range tests { |
| 354 | t.Run(tt.name, func(t *testing.T) { |
| 355 | got := agentStatusLabel(tt.s, verdicts[tt.name], strings.HasPrefix(tt.name, "valley")) |
| 356 | if got != tt.want { |
| 357 | t.Errorf("agentStatusLabel() = %q, want %q", got, tt.want) |
| 358 | } |
| 359 | }) |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | func TestClamp(t *testing.T) { |
| 364 | tests := []struct { |
| 365 | v, lo, hi, want int |
| 366 | }{ |
| 367 | {5, 0, 10, 5}, |
| 368 | {-1, 0, 10, 0}, |
| 369 | {15, 0, 10, 10}, |
| 370 | } |
| 371 | for _, tt := range tests { |
| 372 | got := clamp(tt.v, tt.lo, tt.hi) |
| 373 | if got != tt.want { |
| 374 | t.Errorf("clamp(%d, %d, %d) = %d, want %d", tt.v, tt.lo, tt.hi, got, tt.want) |
| 375 | } |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | func TestLoadStatesFromDir(t *testing.T) { |
| 380 | tmpDir := t.TempDir() |
| 381 | stateDir := filepath.Join(tmpDir, "klaus", "runs") |
| 382 | if err := os.MkdirAll(stateDir, 0o755); err != nil { |
| 383 | t.Fatal(err) |
| 384 | } |
| 385 | |
| 386 | // Write sample state files |
| 387 | states := []run.State{ |
| 388 | { |
| 389 | ID: "20260307-0900-aaaa", |
| 390 | Prompt: "fix tests", |
| 391 | Branch: "fix-tests", |
| 392 | Worktree: "/tmp/worktree1", |
| 393 | CreatedAt: "2026-03-07T09:00:00Z", |
| 394 | Type: "launch", |
| 395 | PRURL: strPtr("https://github.com/owner/repo/pull/30"), |
| 396 | }, |
| 397 | { |
| 398 | ID: "20260307-0901-bbbb", |
| 399 | Prompt: "add feature", |
| 400 | Branch: "add-feature", |
| 401 | Worktree: "/tmp/worktree2", |
| 402 | CreatedAt: "2026-03-07T09:01:00Z", |
| 403 | Type: "launch", |
| 404 | }, |
| 405 | } |
| 406 | |
| 407 | for _, s := range states { |
| 408 | data, err := json.MarshalIndent(s, "", " ") |
| 409 | if err != nil { |
| 410 | t.Fatal(err) |
| 411 | } |
| 412 | if err := os.WriteFile(filepath.Join(stateDir, s.ID+".json"), data, 0o644); err != nil { |
| 413 | t.Fatal(err) |
| 414 | } |
| 415 | } |
| 416 | |
| 417 | store := run.NewGitDirStore(filepath.Join(tmpDir, "klaus")) |
| 418 | loaded, err := store.List() |
| 419 | if err != nil { |
| 420 | t.Fatal(err) |
| 421 | } |
| 422 | if len(loaded) != 2 { |
| 423 | t.Fatalf("loaded %d states, want 2", len(loaded)) |
| 424 | } |
| 425 | |
| 426 | // Verify newest first ordering |
| 427 | if loaded[0].ID != "20260307-0901-bbbb" { |
| 428 | t.Errorf("first state ID = %q, want newest first", loaded[0].ID) |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | func TestDashboardViewRender(t *testing.T) { |
| 433 | cost := 5.50 |
| 434 | // Use a repo name unlikely to be in any real registry to keep the test |
| 435 | // independent of the user's ~/.klaus/projects.json. |
| 436 | states := []*run.State{ |
| 437 | { |
| 438 | ID: "20260307-0900-aaaa", |
| 439 | Prompt: "tests requirement", |
| 440 | Type: "launch", |
| 441 | CreatedAt: time.Now().Add(-1 * time.Hour).Format(time.RFC3339), |
| 442 | TargetRepo: strPtr("testowner/testrepo"), |
| 443 | PRURL: strPtr("https://github.com/testowner/testrepo/pull/30"), |
| 444 | CostUSD: &cost, |
| 445 | }, |
| 446 | { |
| 447 | ID: "20260307-0901-bbbb", |
| 448 | Prompt: "add dashboard", |
| 449 | Type: "launch", |
| 450 | CreatedAt: time.Now().Format(time.RFC3339), |
| 451 | TargetRepo: strPtr("testowner/testrepo"), |
| 452 | TmuxPane: strPtr("%5"), |
| 453 | }, |
| 454 | } |
| 455 | |
| 456 | m := dashboardModel{ |
| 457 | states: states, |
| 458 | tmuxDeps: testDashboardTmuxDeps(), |
| 459 | ghStatus: map[string]*prStatus{}, |
| 460 | width: 80, |
| 461 | height: 24, |
| 462 | } |
| 463 | |
| 464 | view := m.View() |
| 465 | |
| 466 | // Verify key elements are present |
| 467 | if !strings.Contains(view, "flow dashboard") { |
| 468 | t.Error("view should contain 'flow dashboard' header") |
| 469 | } |
| 470 | if !strings.Contains(view, "testowner/testrepo") { |
| 471 | t.Error("view should contain repo name") |
| 472 | } |
| 473 | if !strings.Contains(view, "#30") { |
| 474 | t.Error("view should contain PR number") |
| 475 | } |
| 476 | if !strings.Contains(view, "bbbb") { |
| 477 | t.Error("view should contain short run ID for bare agent") |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | func TestDashboardViewNoRuns(t *testing.T) { |
| 482 | m := dashboardModel{ |
| 483 | states: []*run.State{}, |
| 484 | tmuxDeps: testDashboardTmuxDeps(), |
| 485 | ghStatus: map[string]*prStatus{}, |
| 486 | width: 80, |
| 487 | height: 24, |
| 488 | } |
| 489 | view := m.View() |
| 490 | if !strings.Contains(view, "No runs found") { |
| 491 | t.Error("empty state should show 'No runs found'") |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | func TestDashboardViewLoading(t *testing.T) { |
| 496 | m := dashboardModel{ |
| 497 | tmuxDeps: testDashboardTmuxDeps(), |
| 498 | ghStatus: map[string]*prStatus{}, |
| 499 | width: 80, |
| 500 | height: 24, |
| 501 | } |
| 502 | view := m.View() |
| 503 | if !strings.Contains(view, "Loading") { |
| 504 | t.Error("nil states should show 'Loading'") |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | func TestStateLabel(t *testing.T) { |
| 509 | tests := []struct { |
| 510 | state string |
| 511 | color string // just check the text content, not ANSI codes |
| 512 | }{ |
| 513 | {"MERGED", "MERGED"}, |
| 514 | {"CLOSED", "CLOSED"}, |
| 515 | {"OPEN", "OPEN"}, |
| 516 | {"", "OPEN"}, |
| 517 | } |
| 518 | for _, tt := range tests { |
| 519 | t.Run(tt.state, func(t *testing.T) { |
| 520 | got := stateLabel(tt.state) |
| 521 | if !strings.Contains(got, tt.color) { |
| 522 | t.Errorf("stateLabel(%q) = %q, should contain %q", tt.state, got, tt.color) |
| 523 | } |
| 524 | }) |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | func TestCILabel(t *testing.T) { |
| 529 | tests := []struct { |
| 530 | ci string |
| 531 | want string |
| 532 | }{ |
| 533 | {"passing", "CI ✓"}, |
| 534 | {"failing", "CI ✗"}, |
| 535 | {"pending", "CI …"}, |
| 536 | {"unknown", "CI ?"}, |
| 537 | } |
| 538 | for _, tt := range tests { |
| 539 | t.Run(tt.ci, func(t *testing.T) { |
| 540 | got := ciLabel(tt.ci) |
| 541 | if !strings.Contains(got, tt.want) { |
| 542 | t.Errorf("ciLabel(%q) = %q, should contain %q", tt.ci, got, tt.want) |
| 543 | } |
| 544 | }) |
| 545 | } |
| 546 | } |
| 547 | |
| 548 | // renderOnlyRow builds the dashboard rows for states (which must form exactly |
| 549 | // one row) and renders that row. |
| 550 | func renderOnlyRow(t *testing.T, m dashboardModel, states []*run.State, selected bool) string { |
| 551 | t.Helper() |
| 552 | m.states = states |
| 553 | rows := m.buildRows() |
| 554 | if len(rows) != 1 { |
| 555 | t.Fatalf("got %d rows, want 1", len(rows)) |
| 556 | } |
| 557 | return m.renderRow(rows[0], selected, newRowLayout(rows, 80), time.Now()) |
| 558 | } |
| 559 | |
| 560 | func TestRenderPRLine(t *testing.T) { |
| 561 | m := dashboardModel{width: 80, tmuxDeps: testDashboardTmuxDeps(), ghStatus: map[string]*prStatus{}} |
| 562 | s := &run.State{ |
| 563 | ID: "20260307-0900-aaaa", |
| 564 | Prompt: "fix bug", |
| 565 | Type: "launch", |
| 566 | PRURL: strPtr("https://github.com/o/r/pull/42"), |
| 567 | } |
| 568 | |
| 569 | // Without GitHub status |
| 570 | line := renderOnlyRow(t, m, []*run.State{s}, false) |
| 571 | if !strings.Contains(line, "#42") { |
| 572 | t.Error("should contain PR number") |
| 573 | } |
| 574 | if !strings.Contains(line, "fix bug") { |
| 575 | t.Error("should contain prompt") |
| 576 | } |
| 577 | if !strings.Contains(line, "OPEN") { |
| 578 | t.Error("should show OPEN by default") |
| 579 | } |
| 580 | |
| 581 | // With GitHub status showing passing CI and conflicts |
| 582 | ps := &prStatus{ |
| 583 | PRNumber: "42", |
| 584 | State: "OPEN", |
| 585 | CI: "passing", |
| 586 | Conflicts: "yes", |
| 587 | } |
| 588 | m.ghStatus["https://github.com/o/r/pull/42"] = ps |
| 589 | line = renderOnlyRow(t, m, []*run.State{s}, false) |
| 590 | if !strings.Contains(line, "CI ✓") { |
| 591 | t.Error("should show passing CI") |
| 592 | } |
| 593 | if !strings.Contains(line, "conflicts") { |
| 594 | t.Error("should show conflicts") |
| 595 | } |
| 596 | |
| 597 | // Merged PR |
| 598 | ps.State = "MERGED" |
| 599 | line = renderOnlyRow(t, m, []*run.State{s}, false) |
| 600 | if !strings.Contains(line, "MERGED") { |
| 601 | t.Error("should show MERGED") |
| 602 | } |
| 603 | } |
| 604 | |
| 605 | func TestRenderPRLineHyperlink(t *testing.T) { |
| 606 | m := dashboardModel{width: 80, tmuxDeps: testDashboardTmuxDeps(), ghStatus: map[string]*prStatus{}} |
| 607 | |
| 608 | // The PR number is wrapped in an OSC 8 hyperlink; the padding sits inside |
| 609 | // the link so the escape bytes don't throw off column alignment. |
| 610 | withURL := &run.State{ |
| 611 | ID: "20260307-0900-aaaa", |
| 612 | Prompt: "fix bug", |
| 613 | Type: "launch", |
| 614 | PRURL: strPtr("https://github.com/o/r/pull/42"), |
| 615 | } |
| 616 | line := renderOnlyRow(t, m, []*run.State{withURL}, false) |
| 617 | want := hyperlink("https://github.com/o/r/pull/42", "#42 ") |
| 618 | if !strings.Contains(line, want) { |
| 619 | t.Errorf("expected OSC 8 hyperlink %q in line %q", want, line) |
| 620 | } |
| 621 | |
| 622 | // A run without a PR URL is a bare agent row: no escape sequence. |
| 623 | noURL := &run.State{ID: "id", Prompt: "fix bug", Type: "launch"} |
| 624 | line = renderOnlyRow(t, m, []*run.State{noURL}, false) |
| 625 | if strings.Contains(line, "\x1b]8;;") { |
| 626 | t.Errorf("expected no OSC 8 hyperlink when PRURL is nil, got %q", line) |
| 627 | } |
| 628 | } |
| 629 | |
| 630 | func TestRenderPRLineSelectedWithHyperlink(t *testing.T) { |
| 631 | m := dashboardModel{width: 80, tmuxDeps: testDashboardTmuxDeps(), ghStatus: map[string]*prStatus{}} |
| 632 | s := &run.State{ |
| 633 | ID: "20260307-0900-aaaa", |
| 634 | Prompt: "fix bug", |
| 635 | Type: "launch", |
| 636 | PRURL: strPtr("https://github.com/o/r/pull/42"), |
| 637 | } |
| 638 | |
| 639 | // A selected row must show BOTH the selection gutter marker and keep the |
| 640 | // OSC 8 hyperlink on the PR number intact (lipgloss styling must not strip |
| 641 | // the hyperlink escape). |
| 642 | line := renderOnlyRow(t, m, []*run.State{s}, true) |
| 643 | if !strings.Contains(line, "> ") { |
| 644 | t.Errorf("selected row should show the '> ' gutter marker, got %q", line) |
| 645 | } |
| 646 | if !strings.Contains(line, "\x1b]8;;https://github.com/o/r/pull/42\x1b\\") { |
| 647 | t.Errorf("selected row should preserve the OSC 8 hyperlink, got %q", line) |
| 648 | } |
| 649 | } |
| 650 | |
| 651 | func TestHyperlinkSanitizesURL(t *testing.T) { |
| 652 | // A clean URL is wrapped in the OSC 8 escape sequence. |
| 653 | if got := hyperlink("https://example.com/pull/1", "#1"); !strings.Contains(got, "\x1b]8;;") { |
| 654 | t.Errorf("clean URL should be wrapped, got %q", got) |
| 655 | } |
| 656 | |
| 657 | // URLs with control characters must not be embedded; the plain text is |
| 658 | // returned to prevent terminal escape sequence injection. |
| 659 | for _, bad := range []string{ |
| 660 | "https://x\x1b]8;;evil\x1b\\.com", |
| 661 | "https://x\nfoo.com", |
| 662 | "https://x\rfoo.com", |
| 663 | "https://x\x07.com", |
| 664 | "", // empty URL |
| 665 | } { |
| 666 | if got := hyperlink(bad, "#1"); got != "#1" { |
| 667 | t.Errorf("hyperlink(%q) = %q, want plain text %q", bad, got, "#1") |
| 668 | } |
| 669 | } |
| 670 | } |
| 671 | |
| 672 | func TestRenderPRLineApproval(t *testing.T) { |
| 673 | m := dashboardModel{ |
| 674 | width: 80, |
| 675 | tmuxDeps: testDashboardTmuxDeps(), |
| 676 | pipelineStates: map[string]*pipeline.PRPipelineState{}, |
| 677 | } |
| 678 | |
| 679 | approved := true |
| 680 | notApproved := false |
| 681 | |
| 682 | base := &run.State{ |
| 683 | ID: "run-1", |
| 684 | Prompt: "fix bug", |
| 685 | Branch: "fix-bug", |
| 686 | Type: "launch", |
| 687 | PRURL: strPtr("https://github.com/o/r/pull/10"), |
| 688 | } |
| 689 | |
| 690 | m.ghStatus = map[string]*prStatus{"https://github.com/o/r/pull/10": {State: "OPEN"}} |
| 691 | |
| 692 | // No approval — should not show indicator |
| 693 | line := renderOnlyRow(t, m, []*run.State{base}, false) |
| 694 | if strings.Contains(line, "approved") { |
| 695 | t.Error("should not show approved when not approved") |
| 696 | } |
| 697 | |
| 698 | // Single run approved |
| 699 | approvedRun := *base |
| 700 | approvedRun.Approved = &approved |
| 701 | line = renderOnlyRow(t, m, []*run.State{&approvedRun}, false) |
| 702 | if !strings.Contains(line, "approved") { |
| 703 | t.Error("should show approved indicator") |
| 704 | } |
| 705 | |
| 706 | // Multiple runs, only second is approved |
| 707 | notApprovedRun := *base |
| 708 | notApprovedRun.Approved = ¬Approved |
| 709 | line = renderOnlyRow(t, m, []*run.State{¬ApprovedRun, &approvedRun}, false) |
| 710 | if !strings.Contains(line, "approved") { |
| 711 | t.Error("should show approved when any run is approved") |
| 712 | } |
| 713 | |
| 714 | // Approved but MERGED — should not show indicator |
| 715 | m.ghStatus["https://github.com/o/r/pull/10"] = &prStatus{State: "MERGED"} |
| 716 | line = renderOnlyRow(t, m, []*run.State{&approvedRun}, false) |
| 717 | if strings.Contains(line, "approved") { |
| 718 | t.Error("should not show approved for merged PRs") |
| 719 | } |
| 720 | } |
| 721 | |
| 722 | func TestHostFieldRoundTrip(t *testing.T) { |
| 723 | host := "klaus-worker-0" |
| 724 | s := run.State{ |
| 725 | ID: "20260328-1915-e4b3", |
| 726 | Prompt: "test", |
| 727 | Branch: "agent/test", |
| 728 | Worktree: "/tmp/worktree", |
| 729 | CreatedAt: "2026-03-28T19:15:00Z", |
| 730 | Host: &host, |
| 731 | } |
| 732 | |
| 733 | data, err := json.Marshal(s) |
| 734 | if err != nil { |
| 735 | t.Fatalf("Marshal: %v", err) |
| 736 | } |
| 737 | |
| 738 | var loaded run.State |
| 739 | if err := json.Unmarshal(data, &loaded); err != nil { |
| 740 | t.Fatalf("Unmarshal: %v", err) |
| 741 | } |
| 742 | |
| 743 | if loaded.Host == nil { |
| 744 | t.Fatal("Host should not be nil after round-trip") |
| 745 | } |
| 746 | if *loaded.Host != "klaus-worker-0" { |
| 747 | t.Errorf("Host = %q, want %q", *loaded.Host, "klaus-worker-0") |
| 748 | } |
| 749 | } |
| 750 | |
| 751 | func TestHostFieldOmittedWhenNil(t *testing.T) { |
| 752 | s := run.State{ |
| 753 | ID: "20260328-1915-e4b3", |
| 754 | Prompt: "test", |
| 755 | Branch: "agent/test", |
| 756 | Worktree: "/tmp/worktree", |
| 757 | CreatedAt: "2026-03-28T19:15:00Z", |
| 758 | } |
| 759 | |
| 760 | data, err := json.Marshal(s) |
| 761 | if err != nil { |
| 762 | t.Fatalf("Marshal: %v", err) |
| 763 | } |
| 764 | |
| 765 | if strings.Contains(string(data), `"host"`) { |
| 766 | t.Error("host field should be omitted when nil") |
| 767 | } |
| 768 | } |
| 769 | |
| 770 | func TestRenderBareAgentLineWithHost(t *testing.T) { |
| 771 | m := dashboardModel{tmuxDeps: testDashboardTmuxDeps()} |
| 772 | host := "klaus-worker-0" |
| 773 | s := &run.State{ |
| 774 | ID: "20260328-1915-e4b3", |
| 775 | Prompt: "fix tests", |
| 776 | TmuxPane: strPtr("%5"), |
| 777 | Host: &host, |
| 778 | } |
| 779 | |
| 780 | line := renderOnlyRow(t, m, []*run.State{s}, false) |
| 781 | if !strings.Contains(line, "[sandbox]") { |
| 782 | t.Error("bare agent with Host set should show [sandbox], got:", line) |
| 783 | } |
| 784 | } |
| 785 | |
| 786 | func TestRenderBareAgentLineWithoutHost(t *testing.T) { |
| 787 | m := dashboardModel{tmuxDeps: testDashboardTmuxDeps()} |
| 788 | s := &run.State{ |
| 789 | ID: "20260328-1915-e4b3", |
| 790 | Prompt: "fix tests", |
| 791 | TmuxPane: strPtr("%5"), |
| 792 | } |
| 793 | |
| 794 | line := renderOnlyRow(t, m, []*run.State{s}, false) |
| 795 | if strings.Contains(line, "[sandbox]") { |
| 796 | t.Error("bare agent without Host should not show [sandbox], got:", line) |
| 797 | } |
| 798 | } |
| 799 | |
| 800 | func TestRenderPRLineRunningAgentWithHost(t *testing.T) { |
| 801 | // An agent running on a PR (e.g. a dispatched CI fix) is named on the PR |
| 802 | // row, with its sandbox tag. |
| 803 | m := dashboardModel{tmuxDeps: testDashboardTmuxDeps()} |
| 804 | host := "klaus-worker-0" |
| 805 | s := &run.State{ |
| 806 | ID: "20260328-1915-e4b3", |
| 807 | Prompt: "fix tests", |
| 808 | TmuxPane: strPtr("%5"), |
| 809 | Host: &host, |
| 810 | PRURL: strPtr("https://github.com/o/r/pull/9"), |
| 811 | } |
| 812 | |
| 813 | line := renderOnlyRow(t, m, []*run.State{s}, false) |
| 814 | if !strings.Contains(line, "agent:e4b3 running") { |
| 815 | t.Error("PR row should name the running agent, got:", line) |
| 816 | } |
| 817 | if !strings.Contains(line, "[sandbox]") { |
| 818 | t.Error("running agent with Host set should show [sandbox], got:", line) |
| 819 | } |
| 820 | } |
| 821 | |
| 822 | func TestSandboxTag(t *testing.T) { |
| 823 | t.Run("with host", func(t *testing.T) { |
| 824 | host := "klaus-worker-0" |
| 825 | s := &run.State{Host: &host} |
| 826 | tag := sandboxTag(s) |
| 827 | if !strings.Contains(tag, "[sandbox]") { |
| 828 | t.Errorf("sandboxTag with host should contain [sandbox], got %q", tag) |
| 829 | } |
| 830 | }) |
| 831 | |
| 832 | t.Run("without host", func(t *testing.T) { |
| 833 | s := &run.State{} |
| 834 | tag := sandboxTag(s) |
| 835 | if tag != "" { |
| 836 | t.Errorf("sandboxTag without host should be empty, got %q", tag) |
| 837 | } |
| 838 | }) |
| 839 | } |
| 840 | |
| 841 | func TestRenderSandboxStatus(t *testing.T) { |
| 842 | t.Run("empty hosts returns empty", func(t *testing.T) { |
| 843 | got := renderSandboxStatus(map[string]bool{}) |
| 844 | if got != "" { |
| 845 | t.Errorf("expected empty string, got %q", got) |
| 846 | } |
| 847 | }) |
| 848 | |
| 849 | t.Run("reachable host shows checkmark", func(t *testing.T) { |
| 850 | got := renderSandboxStatus(map[string]bool{"myhost": true}) |
| 851 | if !strings.Contains(got, "sandbox myhost: ✓") { |
| 852 | t.Errorf("expected checkmark for reachable host, got %q", got) |
| 853 | } |
| 854 | }) |
| 855 | |
| 856 | t.Run("unreachable host shows X", func(t *testing.T) { |
| 857 | got := renderSandboxStatus(map[string]bool{"myhost": false}) |
| 858 | if !strings.Contains(got, "sandbox myhost: ✗") { |
| 859 | t.Errorf("expected X for unreachable host, got %q", got) |
| 860 | } |
| 861 | }) |
| 862 | } |
| 863 | |
| 864 | func TestDashboardViewWithSandboxAgent(t *testing.T) { |
| 865 | host := "klaus-worker-0" |
| 866 | states := []*run.State{ |
| 867 | { |
| 868 | ID: "20260328-1915-e4b3", |
| 869 | Prompt: "sandbox test", |
| 870 | Type: "launch", |
| 871 | CreatedAt: time.Now().Format(time.RFC3339), |
| 872 | TargetRepo: strPtr("testowner/testrepo"), |
| 873 | TmuxPane: strPtr("%5"), |
| 874 | Host: &host, |
| 875 | }, |
| 876 | } |
| 877 | |
| 878 | m := dashboardModel{ |
| 879 | states: states, |
| 880 | tmuxDeps: testDashboardTmuxDeps(), |
| 881 | ghStatus: map[string]*prStatus{}, |
| 882 | sandboxHosts: map[string]bool{"klaus-worker-0": true}, |
| 883 | width: 80, |
| 884 | height: 24, |
| 885 | } |
| 886 | |
| 887 | view := m.View() |
| 888 | if !strings.Contains(view, "[sandbox]") { |
| 889 | t.Error("view should show [sandbox] for agent with Host set") |
| 890 | } |
| 891 | if !strings.Contains(view, "sandbox klaus-worker-0: ✓") { |
| 892 | t.Error("view should show sandbox reachability in header") |
| 893 | } |
| 894 | } |
| 895 | |
| 896 | func TestWebhookMsgTriggersRefetchForMatchedPR(t *testing.T) { |
| 897 | // When a webhook arrives for a PR that has a matching run state, |
| 898 | // the dashboard should return a tea.Cmd (the re-fetch). This verifies |
| 899 | // webhooks act as invalidation signals, not data sources. |
| 900 | prURL := "https://github.com/owner/repo/pull/42" |
| 901 | states := []*run.State{ |
| 902 | { |
| 903 | ID: "20260407-0900-aaaa", |
| 904 | Prompt: "fix bug", |
| 905 | Type: "launch", |
| 906 | CreatedAt: time.Now().Format(time.RFC3339), |
| 907 | TargetRepo: strPtr("owner/repo"), |
| 908 | PRURL: &prURL, |
| 909 | }, |
| 910 | } |
| 911 | |
| 912 | m := newDashboardModel(run.NewGitDirStore(t.TempDir()), config.Config{}, gh.NewGHCLIClient("")) |
| 913 | m.states = states |
| 914 | // Set webhookCh so waitForWebhookCmd returns a non-nil cmd, |
| 915 | // ensuring tea.Batch produces a BatchMsg (not a single cmd). |
| 916 | ch := make(chan webhook.Event, 1) |
| 917 | m.webhookCh = ch |
| 918 | |
| 919 | msg := webhookMsg{ |
| 920 | event: webhook.Event{ |
| 921 | PRNumber: "42", |
| 922 | Repo: "owner/repo", |
| 923 | EventType: "pull_request_review", |
| 924 | }, |
| 925 | } |
| 926 | |
| 927 | _, cmd := m.Update(msg) |
| 928 | if cmd == nil { |
| 929 | t.Fatal("expected a tea.Cmd from webhook with matching PR") |
| 930 | } |
| 931 | |
| 932 | // The returned cmd is tea.Batch(fetchGHStatusCmd, waitForWebhookCmd). |
| 933 | // Execute the batch to get the sub-commands, then run only the |
| 934 | // non-blocking ones (skip waitForWebhookCmd which blocks on channel). |
| 935 | result := cmd() |
| 936 | bm, ok := result.(tea.BatchMsg) |
| 937 | if !ok { |
| 938 | t.Fatal("expected tea.BatchMsg from webhook handler") |
| 939 | } |
| 940 | |
| 941 | // Run all sub-commands concurrently; one is waitForWebhookCmd which |
| 942 | // blocks forever (the channel is empty), so we wait on a shared result |
| 943 | // channel with a generous timeout rather than per-iteration. A tight |
| 944 | // timeout per sub-command races the real gh CLI on slow CI runners. |
| 945 | if !awaitGHStatusMsg(bm, 15*time.Second) { |
| 946 | t.Error("expected ghStatusMsg from webhook-triggered fetch") |
| 947 | } |
| 948 | } |
| 949 | |
| 950 | func TestWebhookMsgNoMatchReturnsCmd(t *testing.T) { |
| 951 | // When a webhook arrives for a PR with no matching run state, |
| 952 | // the dashboard should still return a cmd (to keep listening). |
| 953 | m := newDashboardModel(run.NewGitDirStore(t.TempDir()), config.Config{}, gh.NewGHCLIClient("")) |
| 954 | m.states = []*run.State{} // no states |
| 955 | |
| 956 | ch := make(chan webhook.Event, 1) |
| 957 | m.webhookCh = ch |
| 958 | |
| 959 | msg := webhookMsg{ |
| 960 | event: webhook.Event{ |
| 961 | PRNumber: "999", |
| 962 | Repo: "owner/repo", |
| 963 | EventType: "check_run", |
| 964 | }, |
| 965 | } |
| 966 | |
| 967 | _, cmd := m.Update(msg) |
| 968 | if cmd == nil { |
| 969 | t.Fatal("expected a tea.Cmd even when no PR matches (to keep listening)") |
| 970 | } |
| 971 | } |
| 972 | |
| 973 | func TestWebhookPushTriggersFullRefetch(t *testing.T) { |
| 974 | // A push to the default branch should trigger a full re-fetch of all |
| 975 | // PR statuses, since any PR's conflict status could have changed. |
| 976 | prURL := "https://github.com/owner/repo/pull/42" |
| 977 | states := []*run.State{ |
| 978 | { |
| 979 | ID: "20260407-0900-aaaa", |
| 980 | Prompt: "fix bug", |
| 981 | Type: "launch", |
| 982 | CreatedAt: time.Now().Format(time.RFC3339), |
| 983 | TargetRepo: strPtr("owner/repo"), |
| 984 | PRURL: &prURL, |
| 985 | }, |
| 986 | } |
| 987 | |
| 988 | m := newDashboardModel(run.NewGitDirStore(t.TempDir()), config.Config{}, gh.NewGHCLIClient("")) |
| 989 | m.states = states |
| 990 | ch := make(chan webhook.Event, 1) |
| 991 | m.webhookCh = ch |
| 992 | |
| 993 | msg := webhookMsg{ |
| 994 | event: webhook.Event{ |
| 995 | Repo: "owner/repo", |
| 996 | EventType: "push", |
| 997 | }, |
| 998 | } |
| 999 | |
| 1000 | _, cmd := m.Update(msg) |
| 1001 | if cmd == nil { |
| 1002 | t.Fatal("expected a tea.Cmd from push webhook") |
| 1003 | } |
| 1004 | |
| 1005 | // The returned cmd is tea.Batch(fetchGHStatusCmd, waitForWebhookCmd). |
| 1006 | result := cmd() |
| 1007 | bm, ok := result.(tea.BatchMsg) |
| 1008 | if !ok { |
| 1009 | t.Fatal("expected tea.BatchMsg from push webhook handler") |
| 1010 | } |
| 1011 | |
| 1012 | if !awaitGHStatusMsg(bm, 15*time.Second) { |
| 1013 | t.Error("expected ghStatusMsg from push-triggered fetch") |
| 1014 | } |
| 1015 | } |
| 1016 | |
| 1017 | // awaitGHStatusMsg runs all sub-commands in bm concurrently and reports |
| 1018 | // whether any produced a ghStatusMsg within the given timeout. Sub-commands |
| 1019 | // that block (e.g. waitForWebhookCmd with an empty channel) are ignored. |
| 1020 | func awaitGHStatusMsg(bm tea.BatchMsg, timeout time.Duration) bool { |
| 1021 | results := make(chan tea.Msg, len(bm)) |
| 1022 | for _, sub := range bm { |
| 1023 | if sub == nil { |
| 1024 | continue |
| 1025 | } |
| 1026 | go func(c tea.Cmd) { results <- c() }(sub) |
| 1027 | } |
| 1028 | deadline := time.After(timeout) |
| 1029 | for { |
| 1030 | select { |
| 1031 | case r := <-results: |
| 1032 | if _, ok := r.(ghStatusMsg); ok { |
| 1033 | return true |
| 1034 | } |
| 1035 | case <-deadline: |
| 1036 | return false |
| 1037 | } |
| 1038 | } |
| 1039 | } |
| 1040 | |
| 1041 | // TestInternalEventMsgTriggersRefetchForMatchedPR is the dashboard-side |
| 1042 | // counterpart to the webhook test above. When `klaus approve` emits a |
| 1043 | // PRApprovalChanged event and the dashboard receives it via the internal |
| 1044 | // event channel, the dashboard must kick a targeted GH refetch so the |
| 1045 | // pipeline FSM gets a fresh evaluation. Without this, an approved PR with |
| 1046 | // already-passing CI sits at StageCIPassed until an unrelated webhook |
| 1047 | // arrives (or polling tick, when poll_fallback is enabled). |
| 1048 | func TestInternalEventMsgTriggersRefetchForMatchedPR(t *testing.T) { |
| 1049 | prURL := "https://github.com/owner/repo/pull/42" |
| 1050 | states := []*run.State{ |
| 1051 | { |
| 1052 | ID: "20260407-0900-aaaa", |
| 1053 | Prompt: "fix bug", |
| 1054 | Type: "launch", |
| 1055 | CreatedAt: time.Now().Format(time.RFC3339), |
| 1056 | TargetRepo: strPtr("owner/repo"), |
| 1057 | PRURL: &prURL, |
| 1058 | }, |
| 1059 | } |
| 1060 | |
| 1061 | m := newDashboardModel(run.NewGitDirStore(t.TempDir()), config.Config{}, gh.NewGHCLIClient("")) |
| 1062 | m.states = states |
| 1063 | ch := make(chan event.Event, 1) |
| 1064 | m.internalEventCh = ch |
| 1065 | |
| 1066 | msg := internalEventMsg{ |
| 1067 | event: event.New("20260407-0900-aaaa", event.PRApprovalChanged, map[string]interface{}{ |
| 1068 | "pr_number": "42", |
| 1069 | "pr_url": prURL, |
| 1070 | "approved": true, |
| 1071 | }), |
| 1072 | } |
| 1073 | |
| 1074 | _, cmd := m.Update(msg) |
| 1075 | if cmd == nil { |
| 1076 | t.Fatal("expected a tea.Cmd from internal event with matching PR") |
| 1077 | } |
| 1078 | result := cmd() |
| 1079 | bm, ok := result.(tea.BatchMsg) |
| 1080 | if !ok { |
| 1081 | t.Fatal("expected tea.BatchMsg from internal event handler") |
| 1082 | } |
| 1083 | if !awaitGHStatusMsg(bm, 15*time.Second) { |
| 1084 | t.Error("expected ghStatusMsg from internal-event-triggered fetch") |
| 1085 | } |
| 1086 | } |
| 1087 | |
| 1088 | // TestInternalEventMsgNoMatchKeepsListening ensures the handler returns a |
| 1089 | // new wait command even when no PR matches, so the dashboard keeps reading |
| 1090 | // from the channel. (Otherwise a stray event would silently kill the |
| 1091 | // subscription.) |
| 1092 | func TestInternalEventMsgNoMatchKeepsListening(t *testing.T) { |
| 1093 | m := newDashboardModel(run.NewGitDirStore(t.TempDir()), config.Config{}, gh.NewGHCLIClient("")) |
| 1094 | m.states = []*run.State{} |
| 1095 | ch := make(chan event.Event, 1) |
| 1096 | m.internalEventCh = ch |
| 1097 | |
| 1098 | msg := internalEventMsg{ |
| 1099 | event: event.New("run-x", event.PRApprovalChanged, map[string]interface{}{ |
| 1100 | "pr_number": "999", |
| 1101 | }), |
| 1102 | } |
| 1103 | |
| 1104 | _, cmd := m.Update(msg) |
| 1105 | if cmd == nil { |
| 1106 | t.Fatal("expected a tea.Cmd even when no PR matches (to keep listening)") |
| 1107 | } |
| 1108 | } |
| 1109 | |
| 1110 | // TestInternalEventMsgIgnoresUnknownEventType verifies the handler only |
| 1111 | // reacts to invalidation-class events. A pr:merged or agent:completed event |
| 1112 | // arriving on the internal channel should not trigger a GH refetch (those |
| 1113 | // reflect state the dashboard already learned from the FSM). |
| 1114 | func TestInternalEventMsgIgnoresUnknownEventType(t *testing.T) { |
| 1115 | prURL := "https://github.com/owner/repo/pull/42" |
| 1116 | states := []*run.State{ |
| 1117 | { |
| 1118 | ID: "20260407-0900-aaaa", |
| 1119 | Type: "launch", |
| 1120 | CreatedAt: time.Now().Format(time.RFC3339), |
| 1121 | TargetRepo: strPtr("owner/repo"), |
| 1122 | PRURL: &prURL, |
| 1123 | }, |
| 1124 | } |
| 1125 | |
| 1126 | m := newDashboardModel(run.NewGitDirStore(t.TempDir()), config.Config{}, gh.NewGHCLIClient("")) |
| 1127 | m.states = states |
| 1128 | ch := make(chan event.Event, 1) |
| 1129 | m.internalEventCh = ch |
| 1130 | |
| 1131 | msg := internalEventMsg{ |
| 1132 | event: event.New("20260407-0900-aaaa", event.PRMerged, map[string]interface{}{ |
| 1133 | "pr_number": "42", |
| 1134 | }), |
| 1135 | } |
| 1136 | |
| 1137 | _, cmd := m.Update(msg) |
| 1138 | if cmd == nil { |
| 1139 | t.Fatal("expected a tea.Cmd (waitForInternalEventCmd) to keep listening") |
| 1140 | } |
| 1141 | // The returned cmd should be the single wait command, not a batch with |
| 1142 | // a fetch. Block on the channel with a short timeout to confirm it is |
| 1143 | // the wait command (returns no ghStatusMsg even if drained). |
| 1144 | done := make(chan tea.Msg, 1) |
| 1145 | go func() { done <- cmd() }() |
| 1146 | select { |
| 1147 | case msg := <-done: |
| 1148 | // Only happens if cmd() returned (e.g. channel closed); ensure it |
| 1149 | // is NOT a ghStatusMsg or BatchMsg containing a fetch. |
| 1150 | if _, ok := msg.(ghStatusMsg); ok { |
| 1151 | t.Errorf("non-invalidation event should not trigger a GH fetch") |
| 1152 | } |
| 1153 | if bm, ok := msg.(tea.BatchMsg); ok { |
| 1154 | if awaitGHStatusMsg(bm, 100*time.Millisecond) { |
| 1155 | t.Errorf("non-invalidation event should not trigger a GH fetch") |
| 1156 | } |
| 1157 | } |
| 1158 | case <-time.After(200 * time.Millisecond): |
| 1159 | // Expected: waitForInternalEventCmd blocks on the empty channel. |
| 1160 | } |
| 1161 | } |
| 1162 | |
| 1163 | // TestInternalEventMsgIdempotentWithExistingFlow checks that an approval |
| 1164 | // event for a PR can be safely delivered after the controller has already |
| 1165 | // transitioned past approval — the handler does not crash, does not double |
| 1166 | // dispatch, and continues to listen. We exercise this by feeding the same |
| 1167 | // event twice and asserting both calls return non-nil commands. |
| 1168 | func TestInternalEventMsgIdempotent(t *testing.T) { |
| 1169 | prURL := "https://github.com/owner/repo/pull/42" |
| 1170 | states := []*run.State{ |
| 1171 | { |
| 1172 | ID: "20260407-0900-aaaa", |
| 1173 | Type: "launch", |
| 1174 | CreatedAt: time.Now().Format(time.RFC3339), |
| 1175 | TargetRepo: strPtr("owner/repo"), |
| 1176 | PRURL: &prURL, |
| 1177 | }, |
| 1178 | } |
| 1179 | |
| 1180 | m := newDashboardModel(run.NewGitDirStore(t.TempDir()), config.Config{}, gh.NewGHCLIClient("")) |
| 1181 | m.states = states |
| 1182 | ch := make(chan event.Event, 1) |
| 1183 | m.internalEventCh = ch |
| 1184 | |
| 1185 | msg := internalEventMsg{ |
| 1186 | event: event.New("20260407-0900-aaaa", event.PRApprovalChanged, map[string]interface{}{ |
| 1187 | "pr_number": "42", |
| 1188 | }), |
| 1189 | } |
| 1190 | |
| 1191 | _, cmd1 := m.Update(msg) |
| 1192 | if cmd1 == nil { |
| 1193 | t.Fatal("first delivery: expected a tea.Cmd") |
| 1194 | } |
| 1195 | _, cmd2 := m.Update(msg) |
| 1196 | if cmd2 == nil { |
| 1197 | t.Fatal("second delivery: expected a tea.Cmd") |
| 1198 | } |
| 1199 | } |
| 1200 | |
| 1201 | func TestQuitCancelsShutdownContext(t *testing.T) { |
| 1202 | tmpDir := t.TempDir() |
| 1203 | store := run.NewGitDirStore(tmpDir) |
| 1204 | cfg := config.Config{} |
| 1205 | ghClient := gh.NewGHCLIClient("") |
| 1206 | model := newDashboardModel(store, cfg, ghClient) |
| 1207 | model.tmuxDeps = testDashboardTmuxDeps() |
| 1208 | |
| 1209 | cancelled := false |
| 1210 | model.shutdownCancel = func() { cancelled = true } |
| 1211 | |
| 1212 | // Simulate pressing 'q'. |
| 1213 | updated, cmd := model.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'q'}}) |
| 1214 | _ = updated |
| 1215 | |
| 1216 | if !cancelled { |
| 1217 | t.Error("expected shutdownCancel to be called on quit") |
| 1218 | } |
| 1219 | if cmd == nil { |
| 1220 | t.Error("expected tea.Quit command") |
| 1221 | } |
| 1222 | } |
| 1223 | |
| 1224 | // Helper functions for tests. |
| 1225 | |
| 1226 | func float64Ptr(f float64) *float64 { |
| 1227 | return &f |
| 1228 | } |
| 1229 | |
| 1230 | func int64Ptr(i int64) *int64 { |
| 1231 | return &i |
| 1232 | } |