Files
pipelines/internal/tui/run_detail.go
T
alan f3e0593f4d Let runs carry an operator title shown in the CLI and TUI
Add a bounded, never-empty title to every run. `pipelines run --title "..."`
sets it explicitly and skips model generation; otherwise the server generates
it from the prompt through the shared summariser and falls back to the prompt's
first line, recording title_source (model/fallback/explicit) and title_model.

- protocol/store: RunSummary.Title plus Label(), a set_run_title message, title
  columns with an idempotent migration, CreateRunTitled, and SetRunTitle renames.
- summarise: Title/GenerateTitle/DeriveTitle/ExplicitTitle bounded to TitleCap.
- runner: generate the title outside the admission lock and only for a request
  that starts a run; a replay reuses the stored title and an explicit title
  skips the model entirely.
- CLI: `--title` on run and a `title <run-id> "<title>"` rename command; human
  `runs` and `inspect` show the title beside the pipeline name and version.
- TUI: the run list row, run detail header, Home run cards and last-run line,
  and the pipeline Results line show the title via Label().

Tests cover storage/migration/fallback, explicit-title and rename, the
end-to-end CLI flow, and title rendering; CLI and operations docs updated.
2026-10-16 13:36:48 +01:00

654 lines
20 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package tui
import (
"encoding/json"
"fmt"
"maps"
"sort"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
"github.com/sahilm/fuzzy"
)
func (m Model) selectedFailedRun() int64 {
if !m.runOpen || m.runStartRequest != "" {
return 0
}
if m.runDetail != nil {
if m.runDetail.Status == "failed" && m.runDetail.FinishedAt != "" && !m.runDetail.Executing {
for _, step := range m.runDetail.Steps {
if step.AgentActive {
return 0
}
}
return m.runDetail.ID
}
return 0
}
if m.requestedRunID > 0 {
return 0
}
runs := m.visibleRuns()
if len(runs) > 0 {
r := runs[min(m.runIndex, len(runs)-1)]
if r.Status == "failed" && r.FinishedAt != "" && !r.Executing {
return r.ID
}
}
return 0
}
func (m Model) retrySelectedRun() (tea.Model, tea.Cmd) {
id := m.selectedFailedRun()
if id <= 0 {
m.runError = "Select a failed run to retry."
return m, nil
}
return m.runRequest(protocol.Message{Type: protocol.RetryRun, RunID: id, RequestKey: fmt.Sprintf("retry-%d", time.Now().UnixNano())})
}
func (m Model) selectedRunPipeline() (int64, int) {
if !m.runOpen {
return 0, 0
}
if m.runDetail != nil {
return m.runDetail.PipelineID, m.runDetail.Version
}
if m.requestedRunID > 0 || m.runStartRequest != "" {
return 0, 0
}
runs := m.visibleRuns()
if len(runs) == 0 {
return 0, 0
}
r := runs[min(m.runIndex, len(runs)-1)]
return r.PipelineID, r.Version
}
func (m Model) openRunPipeline() (tea.Model, tea.Cmd) {
id, version := m.selectedRunPipeline()
if id <= 0 || version <= 0 {
m.runError = "Select a loaded run to open its pipeline."
return m, nil
}
m.closeRuns()
// Explicit navigation must not trigger the CLI's initial auto-run flow.
if m.cliRun {
m.cliStarted = true
}
return m.requestPipeline(id, version)
}
func (m *Model) closeRuns() {
m.runOpen = false
m.keys.runs = false
m.requestedRunID = 0
m.runStartRequest = ""
m.runDetail = nil
m.runError = ""
m.runTop = 0
m.runDetailFocus = false
m.runPipelineID = 0
m.runFailedOnly = false
m.runSearch = newInput()
m.runSearchOpen = false
m.runGraphFocus = false
m.runGraphTop = 0
m.runGraphPan = 0
}
func (m Model) visibleRuns() []protocol.RunSummary {
query := strings.TrimSpace(m.runSearch.Value())
if m.runPipelineID == 0 && !m.runFailedOnly && query == "" {
return m.runs
}
var runs []protocol.RunSummary
for _, run := range m.runs {
if (m.runPipelineID == 0 || run.PipelineID == m.runPipelineID) && (!m.runFailedOnly || run.Status == "failed") {
runs = append(runs, run)
}
}
if query != "" {
if strings.HasPrefix(query, "#") {
matched := make([]protocol.RunSummary, 0)
for _, run := range runs {
if strings.HasPrefix(fmt.Sprintf("#%d", run.ID), query) {
matched = append(matched, run)
}
}
return matched
}
labels := make([]string, len(runs))
for i, run := range runs {
labels[i] = fmt.Sprintf("#%d %s v%d %s %s %s %s", run.ID, run.Label(), run.Version, run.Status, run.Outcome, run.CurrentStage, run.Diagnostic)
}
matched := make([]protocol.RunSummary, 0)
for _, match := range fuzzy.Find(query, labels) {
matched = append(matched, runs[match.Index])
}
return matched
}
return runs
}
func (m *Model) selectRunStep(index int) {
if m.runStepIndex != index {
m.runStepIndex = index
m.runTop = 0
}
}
func (m Model) runSectionKey(index int) string {
sequence := 0
if m.runDetail != nil && m.runStepIndex > 0 && m.runStepIndex <= len(m.runDetail.Steps) {
sequence = m.runDetail.Steps[m.runStepIndex-1].Sequence
}
return fmt.Sprintf("%d:%d", sequence, index)
}
func (m Model) runSectionClosed(index int) bool {
if closed, ok := m.runCollapsed[m.runSectionKey(index)]; ok {
return closed
}
return index != 2 && index != 5
}
func (m *Model) toggleRunSection(index int) {
closed := m.runSectionClosed(index)
m.runCollapsed = maps.Clone(m.runCollapsed)
if m.runCollapsed == nil {
m.runCollapsed = map[string]bool{}
}
m.runCollapsed[m.runSectionKey(index)] = !closed
}
func (m Model) runDetailWidth() int {
return max(1, m.width-4)
}
func (m Model) runPageSize() int {
extra := 11
if m.width < 80 {
extra = 7
}
if m.runDetail != nil && m.height-4 >= 14 {
graphHeight, _ := m.runPaneHeights(m.height - 4)
extra += graphHeight
}
return max(1, m.height-extra)
}
func (m Model) openOpenCodeEvidence() (tea.Model, tea.Cmd) {
if m.runDetail == nil {
return m, nil
}
index := -1
for i, step := range m.runDetail.Steps {
if step.SessionID != "" {
index = i
}
if step.AgentActive {
index = i
break
}
}
if index < 0 {
m.runError = "No retained agent session for this run yet."
return m, nil
}
m.selectRunStep(index + 1)
m.runGraphFocus = false
m.runDetailFocus = true
m.runTop = 0
if m.runCollapsed == nil {
m.runCollapsed = map[string]bool{}
}
for section := 0; section < 5; section++ {
m.runCollapsed[m.runSectionKey(section)] = section != 3
}
return m, nil
}
func runStatus(status string) string {
color := themeMuted
switch status {
case "succeeded", "completed":
color = themeSuccess
case "failed":
color = themeError
case "running", "queued":
color = themeAccent
}
return lipgloss.NewStyle().Foreground(color).Render(status)
}
func runDuration(start, end string) string {
first, err := time.Parse(time.RFC3339, start)
if err != nil {
return "—"
}
last, err := time.Parse(time.RFC3339, end)
if err != nil {
if end != "" {
return "—"
}
last = time.Now()
}
return max(time.Duration(0), last.Sub(first)).Round(time.Second).String()
}
func valueLines(values map[string]any) []string {
if len(values) == 0 {
return []string{"No data yet."}
}
keys := make([]string, 0, len(values))
for key := range values {
keys = append(keys, key)
}
sort.Strings(keys)
// Put human conclusions before duplicated handoff context and long evidence.
priority := []string{"summary", "reason", "error", "diagnosis", "fix_plan", "diff_summary", "verification_results", "review_findings", "approval", "changed_files", "remaining_risks", "evidence"}
ranks := map[string]int{}
for i, key := range priority {
ranks[key] = i
}
sort.SliceStable(keys, func(i, j int) bool {
a, okA := ranks[keys[i]]
b, okB := ranks[keys[j]]
if okA != okB {
return okA
}
return okA && a < b
})
var lines []string
for _, key := range keys {
lines = append(lines, lipgloss.NewStyle().Foreground(themeMuted).Bold(true).Render(key))
if text, ok := values[key].(string); ok {
lines = append(lines, strings.Split(ansi.Strip(text), "\n")...)
} else {
encoded, _ := json.MarshalIndent(values[key], "", " ")
lines = append(lines, strings.Split(string(encoded), "\n")...)
}
lines = append(lines, "")
}
return lines
}
func evidenceLines(step protocol.RunStep) []string {
lines := []string{"Session: " + step.SessionID, "Evidence is a bounded, redacted preview; full evidence remains in the retained configured-harness session."}
if step.SessionID == "" {
lines = []string{"Recorded result evidence"}
}
if step.Transcript == "" {
return append(lines, "No captured tool evidence yet.")
}
var audit struct {
Limits *struct {
Timeout string `json:"timeout"`
Retries int `json:"retries"`
Budget stage.BudgetSnapshot `json:"budget"`
} `json:"stage_limits"`
Data []json.RawMessage `json:"data"`
FormatRepairs []struct {
Method string `json:"method"`
Accepted bool `json:"accepted"`
Diagnostic string `json:"diagnostic"`
} `json:"format_repairs"`
}
if json.Unmarshal([]byte(step.Transcript), &audit) != nil {
lines = append(lines, "Audit preview is truncated; showing complete captured messages only.")
audit.Data = nil
decoder := json.NewDecoder(strings.NewReader(step.Transcript))
if start, err := decoder.Token(); err == nil && start == json.Delim('{') {
for decoder.More() {
key, err := decoder.Token()
if err != nil {
break
}
if key != "data" {
if key == "format_repairs" {
if decoder.Decode(&audit.FormatRepairs) != nil {
break
}
continue
}
var skip json.RawMessage
if decoder.Decode(&skip) != nil {
break
}
continue
}
start, err := decoder.Token()
if err != nil || start != json.Delim('[') {
break
}
for decoder.More() {
var message json.RawMessage
if decoder.Decode(&message) != nil {
break
}
audit.Data = append(audit.Data, message)
}
break
}
}
}
for _, repair := range audit.FormatRepairs {
lines = append(lines, fmt.Sprintf("JSON format repair: %s · accepted: %t", repair.Method, repair.Accepted), repair.Diagnostic)
}
if limits := audit.Limits; limits != nil {
b := limits.Budget
lines = append(lines, fmt.Sprintf("Timeout per attempt: %s · Retries: %d · Attempts: %d", limits.Timeout, limits.Retries, b.Attempts))
if b.LimitUSD > 0 {
used := "unknown"
if b.USDKnown {
used = fmt.Sprintf("$%.6f", b.UsedUSD)
}
lines = append(lines, fmt.Sprintf("USD budget: %s / $%.6f", used, b.LimitUSD))
}
if b.LimitTokens > 0 {
used := "unknown"
if b.TokensKnown {
used = fmt.Sprint(b.UsedTokens)
}
lines = append(lines, fmt.Sprintf("Token budget: %s / %d", used, b.LimitTokens))
}
}
count := 0
for i := len(audit.Data) - 1; i >= 0; i-- {
var message struct {
Content []struct {
Type string `json:"type"`
Name string `json:"name"`
State struct {
Status string `json:"status"`
Input map[string]any `json:"input"`
Content []struct {
Text string `json:"text"`
} `json:"content"`
} `json:"state"`
} `json:"content"`
}
if json.Unmarshal(audit.Data[i], &message) != nil {
continue
}
for _, part := range message.Content {
if part.Type != "tool" {
continue
}
count++
lines = append(lines, "", fmt.Sprintf("%d. %s · %s", count, part.Name, part.State.Status))
lines = append(lines, valueLines(part.State.Input)...)
for _, result := range part.State.Content {
lines = append(lines, strings.Split(ansi.Strip(result.Text), "\n")...)
}
}
}
if count == 0 {
lines = append(lines, "No tool calls in this preview.")
}
return lines
}
func (m Model) runSectionLines(width int) []string {
if m.runDetail == nil {
return nil
}
r := m.runDetail
titles := []string{"Progress", "Task & input", "Result", "Evidence", "Execution details", "File changes"}
shortcuts := []string{"s", "i", "o", "t", "m", "d"}
summary := append(runResultLines(r), "", strings.Join(completedWorkLines(r), "\n"))
if m.runError != "" {
summary = append(summary, "Request error: "+m.runError)
}
editScope := "all files in run directory"
if len(r.WritePaths) > 0 {
editScope = strings.Join(r.WritePaths, ", ")
}
var output, input []string
if !m.runSectionClosed(2) {
output = runOutputDocument(r, max(1, width-2))
}
if !m.runSectionClosed(1) {
input = resultDocument(r.Input, max(1, width-2))
}
content := [][]string{summary, input, output, {"Choose a stage with n/p to inspect its retained evidence."}, {"Started: " + dateLabel(r.CreatedAt), "Finished: " + dateLabel(r.FinishedAt), "Duration: " + runDuration(r.CreatedAt, r.FinishedAt), "Workspace: " + r.Workspace, "Source hash: " + r.ContentHash, "Stage tools: defined by the pinned pipeline version", "Edit scope: " + editScope}}
if r.RetryOf > 0 {
content[4] = append(content[4], fmt.Sprintf("Retry of run #%d", r.RetryOf))
}
content = append(content, []string{"Select a recorded stage visit with n/p to inspect its retained file diff."})
if m.runStepIndex > 0 && m.runStepIndex <= len(r.Steps) {
step := r.Steps[m.runStepIndex-1]
titles[0] = "Stage progress"
summary = []string{m.progress(m.stepProgressStatus(step)) + " · " + runDuration(step.StartedAt, step.FinishedAt), "Route: " + outcomeLabel(step.Outcome, step.Outcome) + " → " + step.Target}
var stageOutput, stageInput, evidence []string
if !m.runSectionClosed(2) {
stageOutput = resultDocument(step.Output, max(1, width-2))
}
if !m.runSectionClosed(1) {
stageInput = resultDocument(step.Input, max(1, width-2))
}
if !m.runSectionClosed(3) {
evidence = evidenceLines(step)
}
stageState := m.progress(m.stepProgressStatus(step))
if step.Outcome != "" && step.Target != "" {
stageState += " · " + outcomeLabel(step.Outcome, step.Outcome) + " → " + step.Target
}
stageOutput = append([]string{stageState, ""}, stageOutput...)
if step.Status == "running" {
stageOutput = append([]string{m.loading("Working on " + step.Stage + " · result pending"), ""}, stageOutput...)
}
if step.Diagnostic != "" {
stageOutput = append([]string{lipgloss.NewStyle().Foreground(themeError).Render("Stopped: " + step.Diagnostic), ""}, stageOutput...)
}
content = [][]string{summary, stageInput, stageOutput, evidence, {"Started: " + dateLabel(step.StartedAt), "Finished: " + dateLabel(step.FinishedAt), "Duration: " + runDuration(step.StartedAt, step.FinishedAt), "Session: " + step.SessionID, fmt.Sprintf("Agent active: %t", step.AgentActive), fmt.Sprintf("Step: %d", step.Sequence)}}
if step.Control != nil {
content[4] = append(content[4], fmt.Sprintf("Runner visit: %d / %d", step.Control.Visit, step.Control.MaxVisits))
if step.Control.LimitReached {
content[4] = append(content[4], "Runtime limit stopped route: "+step.Control.ModelTarget)
}
for alias, read := range step.Control.Memory {
content[4] = append(content[4], fmt.Sprintf("Shared memory %s ← %s (visit sequence %d)", alias, read.Source, read.Sequence))
}
}
if !m.runSectionClosed(2) {
content[2] = append(content[2], "", fileChangesSummary(step), artifactsSummary(step))
}
var diff []string
if !m.runSectionClosed(5) {
diff = append(stageDiffLines(step), artifactLines(step)...)
}
content = append(content, diff)
for _, receipt := range step.Notifications {
line := "Notification: " + receipt.Destination + " · " + receipt.Status
if receipt.Filename != "" {
line += " · " + receipt.Filename
}
content[4] = append(content[4], line)
if receipt.MessageID != "" {
content[4] = append(content[4], "Message ID: "+receipt.MessageID)
}
if receipt.AttachmentURL != "" {
content[4] = append(content[4], "Attachment: "+receipt.AttachmentURL)
}
if receipt.Diagnostic != "" {
content[4] = append(content[4], "Notification diagnostic: "+receipt.Diagnostic)
}
}
}
var lines []string
for _, i := range []int{2, 5, 0, 1, 3, 4} {
title := titles[i]
marker := "▾"
if m.runSectionClosed(i) {
marker = "▸"
}
lines = append(lines, bar(fmt.Sprintf("[%s] %s %s", shortcuts[i], marker, title), "", width, false))
if !m.runSectionClosed(i) {
for _, line := range content[i] {
for _, wrapped := range strings.Split(ansi.Wrap(line, max(1, width-2), ""), "\n") {
lines = append(lines, " "+wrapped)
}
}
}
lines = append(lines, "")
}
if !m.runGraphFocus {
row, _ := runFocusedSection(lines, m.runTop)
lines[row] = runHighlight(lines[row], width)
}
return lines
}
// The section containing the top visible detail row is the scroll focus.
func runFocusedSection(lines []string, top int) (int, string) {
row, title := 0, "Result"
for i, line := range lines {
plain := ansi.Strip(line)
if i > top {
break
}
if len(plain) > 4 && plain[0] == '[' && plain[2] == ']' {
row = i
fields := strings.Fields(plain)
if len(fields) > 2 {
title = strings.Join(fields[2:], " ")
}
}
}
return row, title
}
func runHighlight(text string, width int) string {
text = ansi.Truncate(text, max(1, width), "…")
text += strings.Repeat(" ", max(0, width-ansi.StringWidth(text)))
return lipgloss.NewStyle().Foreground(themeAccent).Background(themeSelection).Bold(true).
Render(surfaceContent(text, themeSelection))
}
func runPaneTitle(title, right string, width int, focused bool) string {
if focused {
return runHighlight(bar("▸ "+title, right, width, true), width)
}
return bar(title, right, width, false)
}
func (m Model) runSelectionLabel() string {
if m.runDetail != nil && m.runStepIndex > 0 && m.runStepIndex <= len(m.runDetail.Steps) {
step := m.runDetail.Steps[m.runStepIndex-1]
return fmt.Sprintf("%d. %s", step.Sequence, step.Stage)
}
return "Run overview"
}
func (m Model) runActions() string {
text := "P pipeline"
if m.runDetail != nil {
text = "n/p next/prev stage · " + text
}
if m.selectedRunID() > 0 {
text += " · D debug"
}
if m.runDetail != nil {
text += " · a evidence"
}
if m.selectedFailedRun() > 0 {
text += " · r retry failed"
}
return text
}
func (m Model) runsDetailsView(height int) string {
if m.runDetail == nil {
title := "Runs · Enter inspect · Esc close"
if m.runPipelineID > 0 && m.detail != nil {
title = "Runs · " + m.detail.Name + " · Esc back"
}
if m.runFailedOnly {
title = "Failed runs · Esc back"
}
if m.requestedRunID > 0 || m.runStartRequest != "" {
if m.runError != "" {
return fitBlock([]string{"Run unavailable", m.runError, "Use :refresh to try again. Esc returns to runs."}, m.width, height)
}
return fitBlock([]string{m.loading("Loading run…"), m.runError, "Esc returns to runs"}, m.width, height)
}
rows := []string{}
searching := m.runSearchOpen || strings.TrimSpace(m.runSearch.Value()) != ""
if searching {
m.runSearch.Width = max(1, m.width-12)
rows = append(rows, "Search: "+m.runSearch.View())
}
runs := m.visibleRuns()
start, end := selectionWindow(len(runs), m.runIndex, max(1, (height-4-len(rows))/2))
for i := start; i < end; i++ {
r := runs[i]
text := fmt.Sprintf("#%d %s · v%d · %s · %s", r.ID, r.Label(), r.Version, m.progress(r.Status), dateLabel(r.FinishedAt))
rows = append(rows, menuOption(text, i == m.runIndex))
rows = append(rows, " "+ansi.Truncate(resultLabel(r), max(1, m.width-6), "…"))
}
if len(runs) == 0 {
rows = append(rows, "No runs yet.")
if m.runFailedOnly {
rows[len(rows)-1] = "No failed runs."
}
if strings.TrimSpace(m.runSearch.Value()) != "" {
rows[len(rows)-1] = "No matching runs."
}
}
if m.runError != "" {
rows = append(rows, strings.Split(ansi.Wrap(lipgloss.NewStyle().Foreground(themeError).Render(m.runError), max(1, m.width-4), ""), "\n")...)
}
footer := "/ fuzzy search · j/k select · Enter inspect · " + m.runActions()
if m.runSearchOpen {
footer = "Type to filter · Enter results · Esc clear"
}
return panel(m.width, height, []string{bar(title, fmt.Sprint(len(runs)), max(1, m.width-4), true)}, rows, footer, true)
}
r := m.runDetail
header := bar(fmt.Sprintf("#%d %s · v%d", r.ID, r.Label(), r.Version), m.progress(r.Status)+" · "+runDuration(r.CreatedAt, r.FinishedAt), m.width, false)
if height <= 6 {
return fitBlock([]string{header, runHighlight(m.runSelectionLabel(), m.width), m.runActions() + " · Tab pane · Esc back"}, m.width, height)
}
if m.width < 80 {
lines := m.runSectionLines(m.runDetailWidth())
page := max(0, height-3)
top := max(0, min(m.runTop, max(0, len(lines)-page)))
rows := []string{header, m.runVisitTabs(m.width)}
rows = append(rows, lines[top:min(len(lines), top+page)]...)
for len(rows) < height-1 {
rows = append(rows, "")
}
continuation := "Details"
if top+page < len(lines) {
continuation = "↓ More result"
}
rows = append(rows, bar(continuation, fmt.Sprintf("%d–%d / %d", top+1, min(top+page, len(lines)), len(lines)), m.width, false))
return lipgloss.NewStyle().Background(themeSurface).Foreground(themeText).Render(surfaceContent(fitBlock(rows, m.width, height), themeSurface))
}
innerHeight := height - 2
lines := m.runSectionLines(m.runDetailWidth())
page := max(0, innerHeight-5)
top := max(0, min(m.runTop, max(0, len(lines)-page)))
footer := bar("o result · d diff · s progress · i input · t evidence · m details", fmt.Sprintf("%d–%d / %d", min(top+1, len(lines)), min(top+page, len(lines)), len(lines)), max(1, m.width-4), false)
label := m.runSelectionLabel()
if m.runStepIndex > 0 && m.runStepIndex <= len(r.Steps) {
step := r.Steps[m.runStepIndex-1]
label = fmt.Sprintf("Details · %s · step %d", step.Stage, step.Sequence)
label += " · " + runDuration(step.StartedAt, step.FinishedAt)
}
focused := !m.runGraphFocus
if focused {
_, section := runFocusedSection(lines, top)
label += " · " + section
}
body := panel(m.width, innerHeight, []string{runPaneTitle(label, "", m.runDetailWidth(), focused), m.runVisitTabs(m.runDetailWidth())}, lines[top:min(len(lines), top+page)], footer, focused)
return fitBlock(strings.Split(header+"\n\n"+body, "\n"), m.width, height)
}