gunk-dev/the-valley

dashboard.go

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