gunk-dev/the-valley

dashboard.go

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