| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "log" |
| 9 | "log/slog" |
| 10 | "net/http" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | "syscall" |
| 15 | "time" |
| 16 | |
| 17 | tea "github.com/charmbracelet/bubbletea" |
| 18 | "github.com/charmbracelet/lipgloss" |
| 19 | "github.com/charmbracelet/x/ansi" |
| 20 | "github.com/fsnotify/fsnotify" |
| 21 | "the-valley/flow/internal/config" |
| 22 | "the-valley/flow/internal/event" |
| 23 | "the-valley/flow/internal/git" |
| 24 | gh "the-valley/flow/internal/github" |
| 25 | "the-valley/flow/internal/integration" |
| 26 | "the-valley/flow/internal/jobs" |
| 27 | "the-valley/flow/internal/pipeline" |
| 28 | "the-valley/flow/internal/restack" |
| 29 | "the-valley/flow/internal/run" |
| 30 | "the-valley/flow/internal/tmux" |
| 31 | "the-valley/flow/internal/webhook" |
| 32 | "github.com/spf13/cobra" |
| 33 | ) |
| 34 | |
| 35 | // dashboardError holds a pipeline error for TUI display. |
| 36 | type dashboardError struct { |
| 37 | Time time.Time |
| 38 | Message string |
| 39 | } |
| 40 | |
| 41 | var dashboardCmd = &cobra.Command{ |
| 42 | Use: "dashboard", |
| 43 | Short: "Live TUI dashboard for monitoring agents and PRs", |
| 44 | Long: `Shows a persistent, auto-refreshing terminal UI that monitors all active |
| 45 | agent runs and their PR statuses: CI status, merge conflicts, and review |
| 46 | decisions. |
| 47 | |
| 48 | Local state updates instantly via filesystem watching. |
| 49 | GitHub state (CI, conflicts, reviews) polls every 30 seconds by default. |
| 50 | |
| 51 | When webhook config is present in .klaus/config.json, the dashboard starts |
| 52 | an HTTP server to receive push events from github-relay instead of polling. |
| 53 | Set "webhook": {"port": 9800} in config to enable. When another dashboard |
| 54 | of the same user already holds the port, this one polls instead. |
| 55 | |
| 56 | In webhook-only mode (poll_fallback false), a slow reconcile heartbeat runs |
| 57 | a full status re-fetch every 5 minutes by default (configurable via |
| 58 | "reconcile_interval_seconds") so a dropped webhook can't strand a PR forever. |
| 59 | |
| 60 | Runs are listed by what they work on: the runs on a PR share its row, and |
| 61 | so do the runs without a PR on its change (the same change ID in the same |
| 62 | repo, the repo named by the valley's name or its short name, and by its |
| 63 | GitHub owner where a run knows it, so alice/widget and bob/widget are two |
| 64 | repos), as when a run that stopped before opening the PR was continued by |
| 65 | one that opened it. Where the change stands apart from its PR keeps its own |
| 66 | row: when a valley lists the change, or one of those runs pushed a branch |
| 67 | that waits for integration, they share the change's row, as the runs |
| 68 | without a PR on a change no PR carries do. A run with neither has a row of |
| 69 | its own. A run that needs attention stops counting once a run of its |
| 70 | change records taking its pushed work on (see klaus launch) and is running |
| 71 | or finished: that run carries the attention, and the row reads ATTN if it |
| 72 | in turn ended needing attention or failing. Rows are grouped by whose move |
| 73 | it is, most recent first within each group: |
| 74 | yours needs you: needs attention (ATTN), a valley change to approve |
| 75 | (READY) or to look at (STALE, REJECTED, FAILED, UNCERTAIN, |
| 76 | DRAFT), a pushed branch to submit (SUBMIT), or a PR that is ready |
| 77 | to merge and not yet approved |
| 78 | agents an agent is running on it: a fix agent on a PR, a follow-up |
| 79 | (--resume-from, --pr or a pipeline fix) on a change |
| 80 | pipeline an open PR the pipeline is handling: CI running or failing, |
| 81 | conflicts, behind, approved and waiting to merge; or a valley |
| 82 | change that is approved and waiting on the integrator (APPROVED) |
| 83 | or a draft awaiting its review (REVIEW) |
| 84 | done merged, closed, integrated, gone, withdrawn, no access, or |
| 85 | exited |
| 86 | The line above the list counts each group (e.g. "2 yours") and shows the |
| 87 | scroll position (e.g. "12–30 of 34"). |
| 88 | |
| 89 | A pushed branch (a run that finished without a PR) shows SUBMIT until its |
| 90 | work lands on the default branch. Every minute the dashboard checks the run's |
| 91 | clone against origin: INTEGRATED means the pushed commit, or the branch's |
| 92 | current tip, is on the default branch; INTEGRATED~ means a commit on the |
| 93 | default branch carries the same change (equal patch-id), which is strong |
| 94 | evidence rather than proof; GONE means the branch was deleted without |
| 95 | landing. A PR the agent can no longer read on GitHub shows NO ACCESS and is |
| 96 | re-checked every 30 minutes. |
| 97 | |
| 98 | A run whose repo delivers to a valley shows as its change: the repo (always |
| 99 | shown), the change's handle and its title, then the version and head (e.g. |
| 100 | v2@1a2b3c4). Finalize marked the pushed head ready, or, with |
| 101 | "ready_at_finalize": false in config, left it a draft awaiting review. One |
| 102 | "valley changes --all --json" for all such runs says where each stands. It |
| 103 | runs at once when the valley host reports a decision or new evidence, and |
| 104 | otherwise every minute: REVIEW (a draft finalize left that awaits review; approve refuses it, |
| 105 | and the footer offers the 'klaus ready <handle> --head <head>' that marks the |
| 106 | head on screen ready once its review passes), READY (ready and waiting for you), APPROVED, INTEGRATED |
| 107 | (landed), UNCERTAIN (no landing evidence: look), STALE, REJECTED or FAILED |
| 108 | (the integrator's decision), WITHDRAWN, or DRAFT (returned to draft, as |
| 109 | launch does when a follow-up run continues the change, and no run of it is |
| 110 | running). If valley can't be asked, the git check above decides, and a change |
| 111 | waiting on it reads READY, or REVIEW when finalize left it a draft. A run |
| 112 | whose change finalize couldn't mark ready shows SUBMIT and the reason. |
| 113 | A ready change's row shows its required checks as a PR row shows CI: CI … |
| 114 | (pending), CI ✗ and the failed checks' names, or CI ✓. They don't change |
| 115 | READY: you may approve before they finish. After each check the dashboard |
| 116 | dispatches a run to fix a failed head of a change klaus owns, as |
| 117 | 'klaus failed-checks' does. |
| 118 | |
| 119 | A change's row is built like a PR's. It shows the valley's handle, else the |
| 120 | first 8 characters of the change ID; the valley's title, else the subject |
| 121 | of the head its latest run pushed; and where the valley says the change's |
| 122 | active version stands, with that version's head to approve, wherever it |
| 123 | was marked ready (for a change no valley lists, where its latest push |
| 124 | stands). Earlier versions fold into the row. A newer push the valley |
| 125 | doesn't hold as a version, as when its ready failed, doesn't take the row |
| 126 | over: the footer notes it ("a newer push 1a2b3c4 isn't ready"). While an agent runs on a PR or a change, the row names it (e.g. |
| 127 | "agent:1a2b running"), sorts with the agents and offers no approve command, |
| 128 | and the footer says which agent is working on it. Once it exits, the row |
| 129 | goes back to where the PR or change stands. |
| 130 | |
| 131 | Below the run rows, a jobs section lists the session's consults, reviews and prose passes, |
| 132 | as klaus status does: every running job, with how long it has run, and those |
| 133 | that finished in the last 3 hours, with how long they took and how they |
| 134 | ended (SUCCEEDED, FAILED, TIMED OUT, INTERRUPTED, or DIED when the job's klaus |
| 135 | was killed without recording its end). It follows the job records as they |
| 136 | change. Press tab to select a job: the footer says how it stands, with its |
| 137 | error and where its raw output was saved, and enter opens its record and |
| 138 | answer, as 'klaus jobs show' prints them; esc goes back. On a short pane the |
| 139 | jobs lines go before any run row does. |
| 140 | |
| 141 | Done rows older than an hour are hidden until you press h; the line above the |
| 142 | list says how many are hidden. A row the dashboard watched finish stays for |
| 143 | the full hour. Set "dashboard": {"hide_finished_after_minutes": N} in config |
| 144 | to change the threshold, or a negative N to never hide them. |
| 145 | |
| 146 | Set "dashboard": {"approve_command": "cd ~/hack/{repo} && valley approve {handle} --head {head}"} |
| 147 | to show, in the footer, the command that approves the selected READY row |
| 148 | (or submits a SUBMIT row). {repo} is the repo as the row names it, {branch} |
| 149 | the pushed branch, {change} the full change ID, {handle} the change's handle |
| 150 | and {head} the pushed head, so the approval binds the head you saw. A row |
| 151 | with no value for a placeholder the template uses, such as {handle} on a |
| 152 | branch no valley knows, shows no command, and neither does a DRAFT or |
| 153 | REVIEW row or one with an agent running on it. The command is for you to run on your own |
| 154 | machine; the dashboard never runs it. "submit_command" is the |
| 155 | deprecated name of "approve_command", read only when approve_command is |
| 156 | unset. |
| 157 | |
| 158 | Every 30 seconds the dashboard resolves klaus on PATH, symlinks and all. |
| 159 | When it names a different file than the running binary, and that file runs |
| 160 | --version, as after klaus self-update, the footer says "klaus updated to |
| 161 | <version>; restarting". Once no key has been pressed for 10 seconds, the |
| 162 | dashboard shuts down as on q, releasing its webhook port, and execs the new |
| 163 | klaus with the same arguments and environment. If the exec fails, it keeps |
| 164 | running on the old klaus, shows the error, and leaves that file alone. |
| 165 | |
| 166 | Keyboard shortcuts: |
| 167 | j / k or ↑ / ↓ move the selection |
| 168 | PgUp / PgDn move a page |
| 169 | g / G jump to the top / bottom (also Home / End) |
| 170 | h show all runs / hide old done rows |
| 171 | a approve the selected PR |
| 172 | d discuss the selected PR with the coordinator |
| 173 | o open the selected PR in a browser |
| 174 | tab select a job / back to the runs |
| 175 | enter read the selected job's answer (esc to go back) |
| 176 | r refresh, and redraw the whole screen |
| 177 | q quit`, |
| 178 | RunE: func(cmd *cobra.Command, args []string) error { |
| 179 | bin := newBinCheck() |
| 180 | var notice string |
| 181 | for { |
| 182 | next, err := runDashboard(cmd, bin, notice) |
| 183 | if next == nil { |
| 184 | return err |
| 185 | } |
| 186 | // The dashboard has shut down and released its port: become the |
| 187 | // new klaus, with the same arguments and environment. |
| 188 | err = syscall.Exec(next.path, os.Args, os.Environ()) |
| 189 | // Still here: keep running on this klaus, and leave that file be. |
| 190 | bin.failed[next.path] = true |
| 191 | notice = fmt.Sprintf("klaus updated to %s, but restarting onto it failed: %v", next.version, err) |
| 192 | } |
| 193 | }, |
| 194 | } |
| 195 | |
| 196 | // runDashboard runs the dashboard until it quits. It returns the klaus to |
| 197 | // restart onto when it quit for that, once everything is shut down. notice, |
| 198 | // if set, starts in the footer as an error. |
| 199 | func runDashboard(cmd *cobra.Command, bin *binCheck, notice string) (*binUpdateMsg, error) { |
| 200 | { |
| 201 | store, err := sessionStore() |
| 202 | if err != nil { |
| 203 | return nil, fmt.Errorf("KLAUS_SESSION_ID not set; run inside a klaus session") |
| 204 | } |
| 205 | |
| 206 | // Load config once — used for both the dashboard model and webhook setup. |
| 207 | repoRoot, _ := git.RepoRoot() |
| 208 | cfg, err := config.Load(repoRoot) |
| 209 | if err != nil { |
| 210 | fmt.Fprintf(os.Stderr, "warning: loading config: %v\n", err) |
| 211 | } |
| 212 | |
| 213 | // Shared context for coordinating graceful shutdown of all subsystems. |
| 214 | ctx, cancel := context.WithCancel(cmd.Context()) |
| 215 | |
| 216 | ghClient := gh.NewGHCLIClient("") |
| 217 | model := newDashboardModel(store, cfg, ghClient) |
| 218 | model.shutdownCancel = cancel |
| 219 | model.bin = bin |
| 220 | model.binNotice, model.binNoticeErr = notice, notice != "" |
| 221 | defer logTo(model.logger)() |
| 222 | |
| 223 | // Tail the session event log so klaus-internal commands (e.g. |
| 224 | // `klaus approve`) can wake the dashboard FSM without waiting for |
| 225 | // a GitHub webhook. The tail runs even when no webhook server is |
| 226 | // configured — it is the invalidation channel for our own CLI. |
| 227 | if model.eventsPath != "" { |
| 228 | internalCh := make(chan event.Event, 64) |
| 229 | model.internalEventCh = internalCh |
| 230 | go func() { |
| 231 | defer close(internalCh) |
| 232 | if err := event.Tail(ctx, model.eventsPath, internalCh); err != nil { |
| 233 | model.logger.Warn("event tail stopped", "err", err) |
| 234 | } |
| 235 | }() |
| 236 | } |
| 237 | |
| 238 | webhookSrv, err := setupWebhook(&model, cfg) |
| 239 | if err != nil { |
| 240 | cancel() |
| 241 | return nil, err |
| 242 | } |
| 243 | |
| 244 | model.waker = startValleyWaker(ctx, model.logger) |
| 245 | |
| 246 | p := tea.NewProgram(model, tea.WithAltScreen(), tea.WithContext(ctx)) |
| 247 | finalModel, err := p.Run() |
| 248 | cancel() |
| 249 | |
| 250 | // BubbleTea has exited — centralize cleanup of watcher and log file. |
| 251 | var restart *binUpdateMsg |
| 252 | if m, ok := finalModel.(dashboardModel); ok { |
| 253 | if m.watcher != nil { |
| 254 | m.watcher.Close() |
| 255 | } |
| 256 | if m.logFile != nil { |
| 257 | m.logFile.Close() |
| 258 | } |
| 259 | if m.restarting && err == nil { |
| 260 | restart = m.restart |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | // Gracefully shut down the webhook server so the port is released promptly. |
| 265 | if webhookSrv != nil { |
| 266 | shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 267 | defer shutdownCancel() |
| 268 | if err := webhookSrv.Shutdown(shutdownCtx); err != nil { |
| 269 | fmt.Fprintf(os.Stderr, "webhook server shutdown: %v\n", err) |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | return restart, err |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | // setupWebhook starts the webhook server when cfg asks for one and sets the |
| 278 | // model's data source to match. When another dashboard already holds the |
| 279 | // port, the model polls instead and says so; any other listen error is |
| 280 | // returned. The returned server is nil when none runs. |
| 281 | func setupWebhook(model *dashboardModel, cfg config.Config) (*webhook.Server, error) { |
| 282 | if cfg.Webhook == nil { |
| 283 | model.pollEnabled = true |
| 284 | return nil, nil |
| 285 | } |
| 286 | ch := make(chan webhook.Event, 64) |
| 287 | port := cfg.Webhook.Port |
| 288 | if port == 0 { |
| 289 | port = 9800 |
| 290 | } |
| 291 | srv := webhook.NewServer(port, cfg.Webhook.Path, ch) |
| 292 | if err := srv.Listen(); err != nil { |
| 293 | if !errors.Is(err, syscall.EADDRINUSE) { |
| 294 | return nil, fmt.Errorf("webhook server: %w", err) |
| 295 | } |
| 296 | model.pollEnabled = true |
| 297 | model.webhookHeldNote = fmt.Sprintf("webhook port %d is held by another dashboard", port) |
| 298 | model.logger.Info("polling instead of receiving webhooks", "reason", model.webhookHeldNote) |
| 299 | return nil, nil |
| 300 | } |
| 301 | |
| 302 | model.webhookCh = ch |
| 303 | model.useWebhook = true |
| 304 | model.pollEnabled = cfg.Webhook.PollFallback |
| 305 | model.webhookAddr = srv.Addr() |
| 306 | model.reconcileEvery = reconcileInterval(cfg.Webhook) |
| 307 | |
| 308 | logger := model.logger |
| 309 | go func() { |
| 310 | if err := srv.Serve(); err != nil && err != http.ErrServerClosed { |
| 311 | logger.Error("webhook server", "err", err) |
| 312 | } |
| 313 | }() |
| 314 | return srv, nil |
| 315 | } |
| 316 | |
| 317 | func init() { |
| 318 | rootCmd.AddCommand(dashboardCmd) |
| 319 | } |
| 320 | |
| 321 | // logTo sends what slog's and log's default loggers write to logger until |
| 322 | // the returned func restores them. Nothing may write to the terminal under |
| 323 | // the dashboard: a line there scrolls the pane, and the renderer, which |
| 324 | // redraws only the lines that changed, would leave the scrolled lines on |
| 325 | // screen for good. |
| 326 | func logTo(logger *slog.Logger) (restore func()) { |
| 327 | prev, out, flags := slog.Default(), log.Writer(), log.Flags() |
| 328 | slog.SetDefault(logger) |
| 329 | return func() { |
| 330 | slog.SetDefault(prev) |
| 331 | log.SetOutput(out) |
| 332 | log.SetFlags(flags) |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | // dashboardModel is the bubbletea model for the dashboard. |
| 337 | type dashboardModel struct { |
| 338 | store run.StateStore |
| 339 | ghClient gh.Client |
| 340 | ghPoller *ghPoller |
| 341 | ghLimitedUntil time.Time // GitHub rate-limited PR polling until then |
| 342 | tmuxDeps run.TmuxDeps |
| 343 | tmux tmux.Client // for keyboard-driven actions (discuss) |
| 344 | cursor int // index into the displayed rows of the selected row |
| 345 | selKey string // dashRow.key of the selected row; survives reordering |
| 346 | offset int // index of the first row in the viewport |
| 347 | showAll bool // show old done rows that are hidden by default |
| 348 | hideAfter time.Duration |
| 349 | runningSnap map[string]bool // run ID -> agent running, see agentRunning |
| 350 | seenUnfinished map[string]bool // row keys seen before they finished |
| 351 | finishedAt map[string]time.Time // when a watched row was first seen finished |
| 352 | states []*run.State |
| 353 | ghStatus map[string]*prStatus // keyed by PR URL |
| 354 | sandboxHosts map[string]bool // host -> reachable |
| 355 | pipelineCtrl *pipeline.Controller |
| 356 | pipelineStates map[string]*pipeline.PRPipelineState |
| 357 | noAccessAt map[string]time.Time // PR URL -> when last found unreadable |
| 358 | checker integration.Checker |
| 359 | integration map[string]integration.Result // run ID -> latest check; nil before the first check |
| 360 | changes map[integration.ChangeKey]integration.Result // the valley's view of each change's active version |
| 361 | integrationOn bool // the integration check loop has started |
| 362 | valleyErr string // why the latest valley check failed; "" when it didn't |
| 363 | checking bool // an integration check is running |
| 364 | checkAgain bool // a wake came during the running check: run one more after it |
| 365 | wakeHeld bool // a wake waits wakeSettle for the rest of its burst |
| 366 | checkSeq int // the latest arming of the integration timer |
| 367 | waker *valleyWaker // follows valley hosts' telemetry; nil when not started |
| 368 | logger *slog.Logger // writes dashboard.log |
| 369 | changeLedger *pipeline.ChangeLedger // the valley change transitions seen and reported; nil outside a session |
| 370 | restackOn bool // each integration check runs a restack pass |
| 371 | restacks map[integration.ChangeKey]restack.View // where each restack conflict on a change klaus owns stands |
| 372 | approveTemplate string // dashboard.approve_command, or the deprecated submit_command |
| 373 | recentErrors []dashboardError // last N pipeline errors shown in TUI |
| 374 | jobsDir string // the session's job records; "" outside a session |
| 375 | jobs []*jobs.Job // every job record, newest first |
| 376 | jobFocus bool // a job is selected rather than a run |
| 377 | jobCursor int // index into the shown jobs of the selected job |
| 378 | jobSel string // ID of the selected job; survives reordering |
| 379 | detail *jobDetail // the job shown in place of the list, if any |
| 380 | width int |
| 381 | height int |
| 382 | err error |
| 383 | watcher *fsnotify.Watcher |
| 384 | logFile *os.File |
| 385 | shutdownCancel context.CancelFunc // cancels the shared shutdown context |
| 386 | webhookCh <-chan webhook.Event // non-nil when webhook mode is active |
| 387 | webhookHeldNote string // why polling replaced the webhook: another dashboard holds the port |
| 388 | webhookAddr string // e.g. "127.0.0.1:9800" |
| 389 | useWebhook bool // true when webhook server is running |
| 390 | pollEnabled bool // true when polling is active (default or poll_fallback) |
| 391 | reconcileEvery time.Duration // slow reconcile heartbeat interval (webhook-only mode) |
| 392 | // internalEventCh carries klaus-emitted invalidation events (e.g. |
| 393 | // PRApprovalChanged from `klaus approve`). It is symmetric to webhookCh |
| 394 | // but sourced from the local event log rather than an HTTP listener, |
| 395 | // so internal CLI commands can wake the FSM without waiting for a real |
| 396 | // GitHub webhook. |
| 397 | internalEventCh <-chan event.Event |
| 398 | eventsPath string // path to events.jsonl for the tail goroutine |
| 399 | // lastWebhookAt records the wall-clock time of the most recent webhook |
| 400 | // delivery (any event). The zero value means none received yet. It drives |
| 401 | // the footer freshness indicator; the existing 30s tick re-renders the view |
| 402 | // so the displayed age advances without a dedicated timer. |
| 403 | lastWebhookAt time.Time |
| 404 | // bin watches klaus on PATH; restart is the new klaus it found, which |
| 405 | // the dashboard restarts onto once the keyboard is quiet (lastKeyAt). |
| 406 | // restarting means it quit to do so. binNotice is the footer's line |
| 407 | // about it, an error if binNoticeErr. |
| 408 | bin *binCheck |
| 409 | restart *binUpdateMsg |
| 410 | restarting bool |
| 411 | lastKeyAt time.Time |
| 412 | binNotice string |
| 413 | binNoticeErr bool |
| 414 | // clearing is the clear the x key awaits confirmation of; nil when none. |
| 415 | clearing *dashClear |
| 416 | // jobsClearedAt is when the x key last cleared finished jobs from the |
| 417 | // jobs section. |
| 418 | jobsClearedAt time.Time |
| 419 | // cleared sums the runs cleanup removed, for the header's totals. |
| 420 | cleared run.Cleared |
| 421 | } |
| 422 | |
| 423 | func newDashboardModel(store run.StateStore, cfg config.Config, ghClient gh.Client) dashboardModel { |
| 424 | var eventLog *event.Log |
| 425 | var logWriter io.Writer = io.Discard |
| 426 | var logFile *os.File |
| 427 | var eventsPath, jobsDir, ledgerPath string |
| 428 | var changeLedger *pipeline.ChangeLedger |
| 429 | if hds, ok := store.(*run.HomeDirStore); ok { |
| 430 | eventLog = event.NewLog(hds.BaseDir()) |
| 431 | eventsPath = eventLog.Path() |
| 432 | jobsDir = jobs.NewStore(hds.BaseDir()).Dir |
| 433 | ledgerPath = filepath.Join(hds.BaseDir(), pipeline.LedgerFile) |
| 434 | logPath := filepath.Join(hds.BaseDir(), "dashboard.log") |
| 435 | if f, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644); err == nil { |
| 436 | logWriter = f |
| 437 | logFile = f |
| 438 | } |
| 439 | } |
| 440 | logger := slog.New(slog.NewTextHandler(logWriter, nil)) |
| 441 | ctrl := pipeline.New(store, eventLog, logger) |
| 442 | ctrl.SetAutoMergeOnApproval(cfg.AutoMergesOnApproval()) |
| 443 | if ledgerPath != "" { |
| 444 | // The ledger outlives the dashboard, so a restart doesn't report a |
| 445 | // PR's approval or merge again. |
| 446 | ledger, err := pipeline.LoadLedger(ledgerPath) |
| 447 | if err != nil { |
| 448 | logger.Error("reading the PR transition ledger", "err", err) |
| 449 | } |
| 450 | ctrl.SetLedger(ledger) |
| 451 | // The change ledger does the same for valley changes. |
| 452 | changeLedger, err = pipeline.LoadChangeLedger(filepath.Join(filepath.Dir(ledgerPath), pipeline.ChangeLedgerFile)) |
| 453 | if err != nil { |
| 454 | logger.Error("reading the change transition ledger", "err", err) |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | return dashboardModel{ |
| 459 | store: store, |
| 460 | ghClient: ghClient, |
| 461 | ghPoller: newGHPoller(ghClient, cfg.TrustedReviewers), |
| 462 | tmuxDeps: run.DefaultTmuxDeps(), |
| 463 | tmux: tmux.NewExecClient(), |
| 464 | ghStatus: make(map[string]*prStatus), |
| 465 | sandboxHosts: make(map[string]bool), |
| 466 | pipelineCtrl: ctrl, |
| 467 | pipelineStates: make(map[string]*pipeline.PRPipelineState), |
| 468 | noAccessAt: make(map[string]time.Time), |
| 469 | checker: integration.NewValleyChecker(logger), |
| 470 | changeLedger: changeLedger, |
| 471 | restackOn: ledgerPath != "", // a restack pass keeps its ledger in the session directory |
| 472 | approveTemplate: cfg.Dashboard.ApproveTemplate(), |
| 473 | hideAfter: hideFinishedAfter(cfg.Dashboard), |
| 474 | logFile: logFile, |
| 475 | eventsPath: eventsPath, |
| 476 | jobsDir: jobsDir, |
| 477 | logger: logger, |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | func (m dashboardModel) Init() tea.Cmd { |
| 482 | cmds := []tea.Cmd{ |
| 483 | // Start on a clear screen, as after a restart onto a new klaus. |
| 484 | tea.ClearScreen, |
| 485 | loadStatesCmd(m.store), |
| 486 | loadJobsCmd(m.jobsDir), |
| 487 | startWatcherCmd(m.store, m.jobsDir), |
| 488 | tickCmd(), // always tick once on startup for initial fetch |
| 489 | } |
| 490 | if m.webhookCh != nil { |
| 491 | cmds = append(cmds, waitForWebhookCmd(m.webhookCh)) |
| 492 | } |
| 493 | if shouldScheduleReconcile(m.useWebhook, m.pollEnabled, m.reconcileEvery) { |
| 494 | cmds = append(cmds, reconcileTickAfterCmd(m.reconcileEvery)) |
| 495 | } |
| 496 | if m.internalEventCh != nil { |
| 497 | cmds = append(cmds, waitForInternalEventCmd(m.internalEventCh)) |
| 498 | } |
| 499 | if m.waker != nil { |
| 500 | cmds = append(cmds, m.waker.waitCmd()) |
| 501 | } |
| 502 | return tea.Batch(cmds...) |
| 503 | } |
| 504 | |
| 505 | func (m dashboardModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { |
| 506 | next, cmd := m.update(msg) |
| 507 | dm, ok := next.(dashboardModel) |
| 508 | if !ok { |
| 509 | return next, cmd |
| 510 | } |
| 511 | // Re-resolve the run list whenever it or the pane can have changed, so |
| 512 | // the selection stays on its row and in view. |
| 513 | switch msg.(type) { |
| 514 | case statesLoadedMsg, ghStatusMsg, tickMsg, integrationMsg: |
| 515 | dm.snapshotRunning() |
| 516 | dm.syncView(time.Now()) |
| 517 | case tea.KeyMsg, tea.WindowSizeMsg, jobsLoadedMsg: |
| 518 | dm.syncView(time.Now()) |
| 519 | } |
| 520 | return dm, cmd |
| 521 | } |
| 522 | |
| 523 | func (m dashboardModel) update(msg tea.Msg) (tea.Model, tea.Cmd) { |
| 524 | switch msg := msg.(type) { |
| 525 | case tea.KeyMsg: |
| 526 | m.lastKeyAt = time.Now() |
| 527 | key := msg.String() |
| 528 | if m.detail != nil && key != "ctrl+c" { |
| 529 | return m.detailKey(key), nil |
| 530 | } |
| 531 | if c := m.clearing; c != nil { |
| 532 | m.clearing = nil |
| 533 | if key != "y" { |
| 534 | return m, nil |
| 535 | } |
| 536 | m.jobsClearedAt = m.lastKeyAt |
| 537 | return m, m.clearCmd(c) |
| 538 | } |
| 539 | if m.jobFocus { |
| 540 | if next, ok := m.jobKey(key, m.lastKeyAt); ok { |
| 541 | return next, nil |
| 542 | } |
| 543 | } |
| 544 | switch key { |
| 545 | case "q", "ctrl+c": |
| 546 | // Cancel the shared context to signal all subsystems to stop. |
| 547 | if m.shutdownCancel != nil { |
| 548 | m.shutdownCancel() |
| 549 | } |
| 550 | return m, tea.Quit |
| 551 | case "r": |
| 552 | // Redraw every line: the renderer redraws only the lines that |
| 553 | // changed, so whatever else wrote to the pane stays until then. |
| 554 | return m, tea.Batch( |
| 555 | tea.ClearScreen, |
| 556 | loadStatesCmd(m.store), |
| 557 | loadJobsCmd(m.jobsDir), |
| 558 | m.fetchGHStatusCmd(m.states), |
| 559 | ) |
| 560 | case "tab": |
| 561 | // Select the top job: running ones come first. |
| 562 | m.jobFocus = m.resolve(m.lastKeyAt).jobsShown > 0 |
| 563 | m.jobCursor, m.jobSel = 0, "" |
| 564 | case "up", "k": |
| 565 | m.moveSelection(-1, 0) |
| 566 | case "down", "j": |
| 567 | m.moveSelection(1, 0) |
| 568 | case "pgup": |
| 569 | m.moveSelection(0, -1) |
| 570 | case "pgdown": |
| 571 | m.moveSelection(0, 1) |
| 572 | case "g", "home": |
| 573 | m.selectEdge(false) |
| 574 | case "G", "end": |
| 575 | m.selectEdge(true) |
| 576 | case "h": |
| 577 | m.showAll = !m.showAll |
| 578 | case "x": |
| 579 | // Clear what's finished, as klaus cleanup --done does, once |
| 580 | // the operator confirms. |
| 581 | m.clearing = m.planClear(m.lastKeyAt) |
| 582 | case "a": |
| 583 | // Approve the selected PR immediately (no confirmation). |
| 584 | r, ok := m.selectedPR("approve") |
| 585 | if !ok { |
| 586 | break |
| 587 | } |
| 588 | if err := markApproved(r.state(), m.store); err != nil { |
| 589 | m.noteError(fmt.Sprintf("approve PR #%s: %v", r.prNum, err)) |
| 590 | } |
| 591 | // Reload so the row reflects approval immediately; the fsnotify |
| 592 | // watcher also catches the save, but this avoids the round-trip lag. |
| 593 | return m, loadStatesCmd(m.store) |
| 594 | case "d": |
| 595 | // Discuss the selected PR with the coordinator: pre-fill a prompt |
| 596 | // in the coordinator pane and switch focus there. |
| 597 | r, ok := m.selectedPR("discuss") |
| 598 | if !ok { |
| 599 | break |
| 600 | } |
| 601 | pane := m.coordinatorPane() |
| 602 | if pane == "" { |
| 603 | m.noteError("coordinator pane unknown (older session; relaunch to enable discuss)") |
| 604 | break |
| 605 | } |
| 606 | if err := m.discussPR(r.prNum, pane); err != nil { |
| 607 | m.noteError(fmt.Sprintf("discuss PR #%s: %v", r.prNum, err)) |
| 608 | } |
| 609 | case "o": |
| 610 | // Open the selected PR in the system browser. |
| 611 | r, ok := m.selectedPR("open") |
| 612 | if !ok { |
| 613 | break |
| 614 | } |
| 615 | s := r.state() |
| 616 | if s.PRURL == nil || *s.PRURL == "" { |
| 617 | break |
| 618 | } |
| 619 | url := *s.PRURL |
| 620 | prNum := r.prNum |
| 621 | // Fire-and-forget so Update stays clean and the UI never blocks on |
| 622 | // the browser launch. Surface a transient hint on failure. |
| 623 | return m, func() tea.Msg { |
| 624 | if err := openInBrowser(url); err != nil { |
| 625 | return errHintMsg{msg: fmt.Sprintf("open PR #%s: %v", prNum, err)} |
| 626 | } |
| 627 | return nil |
| 628 | } |
| 629 | } |
| 630 | |
| 631 | case tea.WindowSizeMsg: |
| 632 | m.width = msg.Width |
| 633 | m.height = msg.Height |
| 634 | |
| 635 | case clearedMsg: |
| 636 | if len(msg.failed) > 0 { |
| 637 | m.noteError(fmt.Sprintf("clear finished: couldn't remove %v", msg.failed)) |
| 638 | } |
| 639 | return m, loadStatesCmd(m.store) |
| 640 | |
| 641 | case statesLoadedMsg: |
| 642 | m.states = msg.states |
| 643 | m.cleared = msg.cleared |
| 644 | // Detect and finalize stale (orphaned) runs so they stop appearing as active. |
| 645 | for _, s := range m.states { |
| 646 | if s.IsStaleWith(m.tmuxDeps) { |
| 647 | slog.Info("finalizing stale run", "id", s.ID) |
| 648 | markRunFailed(m.store, s) |
| 649 | } |
| 650 | } |
| 651 | // Follow the valley hosts of the changes the check asks about, so |
| 652 | // the host's decisions wake it. |
| 653 | m.waker.Track(valleyCheckouts(m.states)) |
| 654 | cmd := m.fetchGHStatusCmd(m.states) |
| 655 | if !m.integrationOn { |
| 656 | // The first load starts the integration check loop; it then |
| 657 | // re-arms itself each time a check completes. |
| 658 | m.integrationOn = true |
| 659 | var check tea.Cmd |
| 660 | m, check = m.startIntegrationCheck() |
| 661 | cmd = tea.Batch(cmd, check) |
| 662 | } |
| 663 | return m, cmd |
| 664 | |
| 665 | case integrationTickMsg: |
| 666 | if msg.seq != m.checkSeq || m.checking { |
| 667 | return m, nil // a woken check took this tick's place |
| 668 | } |
| 669 | return m.startIntegrationCheck() |
| 670 | |
| 671 | case valleyWakeMsg: |
| 672 | cmd := m.waker.waitCmd() |
| 673 | if !m.wakeHeld { |
| 674 | m.wakeHeld = true |
| 675 | cmd = tea.Batch(cmd, tea.Tick(wakeSettle, func(time.Time) tea.Msg { return valleyWakeCheckMsg{} })) |
| 676 | } |
| 677 | return m, cmd |
| 678 | |
| 679 | case valleyWakeCheckMsg: |
| 680 | m.wakeHeld = false |
| 681 | if m.checking { |
| 682 | m.checkAgain = true |
| 683 | return m, nil |
| 684 | } |
| 685 | if !m.integrationOn { |
| 686 | return m, nil // the first load's check is yet to start |
| 687 | } |
| 688 | return m.startIntegrationCheck() |
| 689 | |
| 690 | case integrationMsg: |
| 691 | m.integration = keepValleyViews(m.integration, msg.results) |
| 692 | m.changes = keepChangeViews(m.changes, msg.changes) |
| 693 | m.valleyErr = msg.valleyErr |
| 694 | if msg.restacks != nil { |
| 695 | m.restacks = msg.restacks |
| 696 | } |
| 697 | m.checking = false |
| 698 | if m.checkAgain { |
| 699 | m.checkAgain = false |
| 700 | return m.startIntegrationCheck() |
| 701 | } |
| 702 | m.checkSeq++ |
| 703 | return m, integrationTickAfterCmd(m.checkSeq) |
| 704 | |
| 705 | case ghStatusMsg: |
| 706 | now := time.Now() |
| 707 | m.ghLimitedUntil = msg.rateLimitedUntil |
| 708 | for url, v := range msg.statuses { |
| 709 | m.ghStatus[url] = v |
| 710 | if v.State == gh.StateNoAccess { |
| 711 | m.noAccessAt[url] = now |
| 712 | } else { |
| 713 | delete(m.noAccessAt, url) |
| 714 | } |
| 715 | } |
| 716 | // Feed statuses to the pipeline controller, which keys PRs by number: |
| 717 | // the first run state for a number decides which PR it tracks. PRs the |
| 718 | // agent can't read are left out; the pipeline can't act on them. |
| 719 | pStatuses := make(map[string]*pipeline.PRStatus, len(msg.statuses)) |
| 720 | claimed := make(map[string]bool) |
| 721 | for _, s := range m.states { |
| 722 | prNum, url := extractPRNumber(s), extractPRRef(s) |
| 723 | if prNum == "" || claimed[prNum] { |
| 724 | continue |
| 725 | } |
| 726 | claimed[prNum] = true |
| 727 | v, ok := msg.statuses[url] |
| 728 | if !ok || v.State == gh.StateNoAccess { |
| 729 | continue |
| 730 | } |
| 731 | ps := &pipeline.PRStatus{ |
| 732 | PRNumber: v.PRNumber, |
| 733 | PRURL: url, |
| 734 | State: v.State, |
| 735 | CI: v.CI, |
| 736 | Conflicts: v.Conflicts, |
| 737 | BehindBy: v.BehindBy, |
| 738 | ReviewDecision: v.ReviewDecision, |
| 739 | HasNewTrustedComments: v.HasNewTrustedComments, |
| 740 | Labels: v.Labels, |
| 741 | HeadSHA: v.HeadSHA, |
| 742 | TrustedFeedbackAt: v.TrustedFeedbackAt, |
| 743 | } |
| 744 | if s.TargetRepo != nil { |
| 745 | ps.TargetRepo = *s.TargetRepo |
| 746 | } |
| 747 | pStatuses[prNum] = ps |
| 748 | } |
| 749 | actions := m.pipelineCtrl.HandleGHStatus(context.Background(), pStatuses, m.states) |
| 750 | m.pipelineStates = m.pipelineCtrl.PipelineStates() |
| 751 | if len(actions) > 0 { |
| 752 | return m, func() tea.Msg { |
| 753 | return pipelineActionMsg{actions: actions} |
| 754 | } |
| 755 | } |
| 756 | |
| 757 | case pipelineActionMsg: |
| 758 | // Capture any error actions for TUI display. |
| 759 | for _, a := range msg.actions { |
| 760 | if a.Error != "" { |
| 761 | errMsg := a.Detail + " — " + a.Error |
| 762 | m.recentErrors = append(m.recentErrors, dashboardError{ |
| 763 | Time: time.Now(), |
| 764 | Message: errMsg, |
| 765 | }) |
| 766 | if len(m.recentErrors) > 3 { |
| 767 | m.recentErrors = m.recentErrors[len(m.recentErrors)-3:] |
| 768 | } |
| 769 | } |
| 770 | } |
| 771 | // Pipeline dispatched agents or merged PRs — refresh state. |
| 772 | return m, loadStatesCmd(m.store) |
| 773 | |
| 774 | case fsEventMsg: |
| 775 | return m, tea.Batch(loadStatesCmd(m.store), watchFSCmd(m.watcher, m.jobsDir)) |
| 776 | |
| 777 | case jobsFSMsg: |
| 778 | return m, tea.Batch(loadJobsCmd(m.jobsDir), watchFSCmd(m.watcher, m.jobsDir)) |
| 779 | |
| 780 | case jobsLoadedMsg: |
| 781 | m.jobs = msg.jobs |
| 782 | m.refreshJobDetail(time.Now()) |
| 783 | |
| 784 | case sandboxStatusMsg: |
| 785 | for k, v := range msg.hosts { |
| 786 | m.sandboxHosts[k] = v |
| 787 | } |
| 788 | |
| 789 | case webhookMsg: |
| 790 | // Webhooks are invalidation signals, not data sources. When a |
| 791 | // webhook arrives, trigger an immediate re-fetch of PR status |
| 792 | // via the same code path that polling uses. This eliminates |
| 793 | // the class of bugs where the webhook path diverges from polling. |
| 794 | ev := msg.event |
| 795 | // Record the delivery time for the footer freshness indicator. Every |
| 796 | // delivery counts, regardless of PRNumber/type. |
| 797 | m.lastWebhookAt = time.Now() |
| 798 | if ev.PRNumber != "" { |
| 799 | // Find run states that match this PR for a targeted fetch. |
| 800 | var matchedStates []*run.State |
| 801 | for _, s := range m.states { |
| 802 | if extractPRNumber(s) == ev.PRNumber { |
| 803 | matchedStates = append(matchedStates, s) |
| 804 | } |
| 805 | } |
| 806 | if len(matchedStates) > 0 { |
| 807 | return m, tea.Batch( |
| 808 | m.fetchGHStatusCmd(matchedStates), |
| 809 | waitForWebhookCmd(m.webhookCh), |
| 810 | ) |
| 811 | } |
| 812 | } else if ev.EventType == "push" && ev.Repo != "" { |
| 813 | // Push to default branch — re-fetch all open PRs since |
| 814 | // conflicts may have changed. |
| 815 | return m, tea.Batch( |
| 816 | m.fetchGHStatusCmd(m.states), |
| 817 | waitForWebhookCmd(m.webhookCh), |
| 818 | ) |
| 819 | } |
| 820 | return m, waitForWebhookCmd(m.webhookCh) |
| 821 | |
| 822 | case webhookClosedMsg: |
| 823 | // Live webhook consumption has stopped. Do not re-arm (re-reading a |
| 824 | // closed channel busy-loops). Surface it non-fatally; the reconcile |
| 825 | // heartbeat, if active, still bounds staleness. |
| 826 | m.recentErrors = append(m.recentErrors, dashboardError{ |
| 827 | Time: time.Now(), |
| 828 | Message: "webhook event channel closed; live webhook updates stopped (reconcile heartbeat still active)", |
| 829 | }) |
| 830 | if len(m.recentErrors) > 3 { |
| 831 | m.recentErrors = m.recentErrors[len(m.recentErrors)-3:] |
| 832 | } |
| 833 | return m, nil |
| 834 | |
| 835 | case internalEventMsg: |
| 836 | // Klaus-internal invalidation events are handled symmetrically to |
| 837 | // webhooks: a CLI command (e.g. `klaus approve`) signalled that the |
| 838 | // pipeline preconditions for a PR may have changed, so we trigger |
| 839 | // a targeted re-fetch of GitHub status. That re-fetch funnels into |
| 840 | // the same HandleGHStatus path that polling and webhooks use, so |
| 841 | // the FSM gets a fresh evaluation without any divergent code path. |
| 842 | ev := msg.event |
| 843 | prNum := internalEventPRNumber(ev) |
| 844 | if shouldInvalidate(ev.Type) && prNum != "" { |
| 845 | var matchedStates []*run.State |
| 846 | for _, s := range m.states { |
| 847 | if extractPRNumber(s) == prNum { |
| 848 | matchedStates = append(matchedStates, s) |
| 849 | } |
| 850 | } |
| 851 | if len(matchedStates) > 0 { |
| 852 | return m, tea.Batch( |
| 853 | m.fetchGHStatusCmd(matchedStates), |
| 854 | waitForInternalEventCmd(m.internalEventCh), |
| 855 | ) |
| 856 | } |
| 857 | } |
| 858 | return m, waitForInternalEventCmd(m.internalEventCh) |
| 859 | |
| 860 | case trustedCommentsMsg: |
| 861 | existing, ok := m.ghStatus[msg.prURL] |
| 862 | if ok { |
| 863 | existing.HasNewTrustedComments = msg.hasNewTrustedComments |
| 864 | } |
| 865 | |
| 866 | case reconcileTickMsg: |
| 867 | // Slow reconcile heartbeat (webhook-only mode). Webhooks are the only |
| 868 | // reconcile trigger when poll_fallback is false, so a single dropped |
| 869 | // or missed event would strand a PR forever. This periodic full |
| 870 | // re-fetch bounds worst-case staleness (see issue #271). It re-arms |
| 871 | // itself; it is never scheduled when polling is active (which already |
| 872 | // re-fetches every 30s), so there is no double-fetch. |
| 873 | return m, tea.Batch( |
| 874 | m.fetchGHStatusCmd(m.states), |
| 875 | reconcileTickAfterCmd(m.reconcileEvery), |
| 876 | ) |
| 877 | |
| 878 | case tickMsg: |
| 879 | // Expire errors older than 3 minutes. |
| 880 | cutoff := time.Now().Add(-3 * time.Minute) |
| 881 | filtered := m.recentErrors[:0] |
| 882 | for _, e := range m.recentErrors { |
| 883 | if e.Time.After(cutoff) { |
| 884 | filtered = append(filtered, e) |
| 885 | } |
| 886 | } |
| 887 | m.recentErrors = filtered |
| 888 | |
| 889 | cmds := []tea.Cmd{ |
| 890 | checkSandboxCmd(m.states), |
| 891 | // Reloading the jobs judges again which running ones died. |
| 892 | loadJobsCmd(m.jobsDir), |
| 893 | tickAfterCmd(), |
| 894 | } |
| 895 | if m.bin != nil && m.restart == nil { |
| 896 | cmds = append(cmds, checkBinCmd(m.bin)) |
| 897 | } |
| 898 | if m.pollEnabled { |
| 899 | cmds = append(cmds, m.fetchGHStatusCmd(m.states)) |
| 900 | } |
| 901 | return m, tea.Batch(cmds...) |
| 902 | |
| 903 | case *fsnotify.Watcher: |
| 904 | m.watcher = msg |
| 905 | return m, watchFSCmd(msg, m.jobsDir) |
| 906 | |
| 907 | case binUpdateMsg: |
| 908 | if m.restart != nil { |
| 909 | break |
| 910 | } |
| 911 | m.restart = &msg |
| 912 | m.binNotice, m.binNoticeErr = "klaus updated to "+msg.version+"; restarting", false |
| 913 | // Show the notice for a moment before restarting. |
| 914 | return m, restartWaitCmd() |
| 915 | |
| 916 | case restartWaitMsg: |
| 917 | return m.restartWhenIdle(time.Now()) |
| 918 | |
| 919 | case restartTargetMsg: |
| 920 | return m.restartOnto(msg.target, time.Now()) |
| 921 | |
| 922 | case errHintMsg: |
| 923 | m.noteError(msg.msg) |
| 924 | |
| 925 | case errMsg: |
| 926 | m.err = msg.err |
| 927 | } |
| 928 | |
| 929 | return m, nil |
| 930 | } |
| 931 | |
| 932 | func (m dashboardModel) View() string { |
| 933 | if m.err != nil { |
| 934 | return fmt.Sprintf("Error: %v\n\nPress q to quit.", m.err) |
| 935 | } |
| 936 | if m.states == nil { |
| 937 | return "Loading..." |
| 938 | } |
| 939 | |
| 940 | now := time.Now() |
| 941 | width := m.width |
| 942 | if width <= 0 { |
| 943 | width = defaultDashboardWidth |
| 944 | } |
| 945 | if m.detail != nil { |
| 946 | return m.renderJobDetail(width) |
| 947 | } |
| 948 | v := m.resolve(now) |
| 949 | |
| 950 | chrome := func(c chromeItem) string { |
| 951 | switch c.kind { |
| 952 | case chromeHeader: |
| 953 | title := " klaus dashboard" |
| 954 | span := computeSessionDuration(m.states) |
| 955 | if first := m.cleared.FirstCreated; !first.IsZero() && now.Sub(first) > span { |
| 956 | span = now.Sub(first) |
| 957 | } |
| 958 | headerRight := fmt.Sprintf("Session: %s | Cost: $%.2f", |
| 959 | formatDuration(span), computeTotalCost(m.states)+m.cleared.CostUSD) |
| 960 | if now.Before(m.ghLimitedUntil) { |
| 961 | headerRight = "GitHub rate-limited until " + m.ghLimitedUntil.Format("15:04") + " | " + headerRight |
| 962 | } |
| 963 | pad := max(width-2-lipgloss.Width(title)-lipgloss.Width(headerRight), 1) |
| 964 | return headerStyle.Render(title + strings.Repeat(" ", pad) + headerRight) |
| 965 | case chromeSource: |
| 966 | return m.renderSourceLine() |
| 967 | case chromeSandbox: |
| 968 | return strings.TrimSuffix(renderSandboxStatus(m.sandboxHosts), "\n") |
| 969 | case chromeSummary: |
| 970 | return m.renderSummary(v, width) |
| 971 | case chromeError: |
| 972 | e := m.recentErrors[c.idx] |
| 973 | line := fmt.Sprintf(" %s ✗ %s", e.Time.Format("15:04"), e.Message) |
| 974 | return dimRedStyle.Render(truncateLine(line, max(width-1, 1))) |
| 975 | case chromeNotice: |
| 976 | style := yellowStyle |
| 977 | if m.binNoticeErr { |
| 978 | style = dimRedStyle |
| 979 | } |
| 980 | return style.Render(truncateLine(" "+m.binNotice, max(width-1, 1))) |
| 981 | case chromeValley: |
| 982 | return yellowStyle.Render(truncateLine(" "+integration.ValleyNote(m.valleyErr), max(width-1, 1))) |
| 983 | case chromeJobs: |
| 984 | return renderJobsHeader(v) |
| 985 | case chromeJob: |
| 986 | return renderJobLine(v.jobs[c.idx], v.jobFocus && c.idx == v.jobCursor, now) |
| 987 | case chromeFooter: |
| 988 | if v.jobFocus { |
| 989 | return renderJobsFooter(v, width) |
| 990 | } |
| 991 | return m.renderFooter(v, width) |
| 992 | } |
| 993 | return "" |
| 994 | } |
| 995 | |
| 996 | var lines []string |
| 997 | for _, c := range v.chrome { |
| 998 | if c.top { |
| 999 | lines = append(lines, chrome(c)) |
| 1000 | } |
| 1001 | } |
| 1002 | if len(v.rows) == 0 && (m.height <= 0 || m.height > len(v.chrome)) { |
| 1003 | msg := " No runs found." |
| 1004 | if v.hidden > 0 { |
| 1005 | msg = fmt.Sprintf(" No runs to show: %d done hidden (h to show all).", v.hidden) |
| 1006 | } |
| 1007 | lines = append(lines, dimStyle.Render(msg)) |
| 1008 | } |
| 1009 | lay := newRowLayout(v.all, width) |
| 1010 | for i := v.offset; i < v.offset+v.bodyH && i < len(v.rows); i++ { |
| 1011 | lines = append(lines, m.renderRow(v.rows[i], i == v.cursor && !v.jobFocus, lay, now)) |
| 1012 | } |
| 1013 | for _, c := range v.chrome { |
| 1014 | if !c.top { |
| 1015 | lines = append(lines, chrome(c)) |
| 1016 | } |
| 1017 | } |
| 1018 | |
| 1019 | // One line each, never wrapped: a line break or a wrapped line would |
| 1020 | // push rows off the bottom of the pane. |
| 1021 | for i, l := range lines { |
| 1022 | l, _, _ = strings.Cut(l, "\n") |
| 1023 | lines[i] = ansi.Truncate(l, width, "…") |
| 1024 | } |
| 1025 | return strings.Join(lines, "\n") |
| 1026 | } |