gunk-dev/the-valley

dashboard.go

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