Improve workflow UI, retain stage diffs, and add portable pipeline transfers

Make OpenCode authoring responsive and expand the managed skill references. Add conflict-aware import/export, real-provider reference workflows, and tracked V2 generation for reliable budget accounting.
This commit is contained in:
2026-10-10 20:55:42 +01:00
parent a66d540125
commit c42a19f7d3
81 changed files with 5593 additions and 539 deletions
+6 -1
View File
@@ -16,6 +16,10 @@ func (m Model) updateActionConfirm(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
m.actionConfirm = nil
m.actionApproved = true
return m.sendRunRequest(request)
case "j", "down", "pgdown":
m.actionConfirmTop++
case "k", "up", "pgup":
m.actionConfirmTop = max(0, m.actionConfirmTop-1)
}
return m, nil
}
@@ -23,6 +27,7 @@ func (m Model) updateActionConfirm(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
func (m Model) confirmMutation(title string, cmd func() tea.Cmd) (tea.Model, tea.Cmd) {
m.mutationTitle = title
m.mutationCommand = cmd
m.mutationTop = 0
return m, nil
}
@@ -37,5 +42,5 @@ func (m Model) actionConfirmView(height int) string {
if r.Type == protocol.CancelRun {
lines = []string{fmt.Sprintf("Cancel run #%d?", r.RunID), "Stops execution and interrupts its active agent.", "Sessions/history are retained; previous side effects are not undone."}
}
return popup(m.width, height, 96, append(lines, "", "y confirm · n / Esc cancel"))
return wrappedDialog(m.width, height, 96, lines[0], lines[1:], "y confirm · n / Esc cancel", m.actionConfirmTop)
}
+106
View File
@@ -0,0 +1,106 @@
package tui
import (
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
)
// Modal controls replace, rather than inherit, the obscured page's shortcuts.
func (m Model) activeFooter() string {
text := ""
switch {
case m.editorChecking:
text = "Refreshing published state · draft retained"
case m.actionConfirm != nil || m.mutationCommand != nil:
text = "y confirm · n/Esc cancel · j/k read"
case m.draftDeletingPath != "":
text = "y delete · n/Esc keep · j/k read"
case m.statusOpen:
text = "j/k scroll · r refresh · Esc back"
case m.editorOpen:
text = "Type to filter · ↑/↓ choose · Enter open · Esc cancel"
case m.confirmOpen && m.templateConfirm:
text = "Enter create pipeline · edit name · Esc keep draft"
if m.pendingDraft != nil && m.pendingDraft.path == "" {
text = "Enter create pipeline · edit name · Esc back"
}
case m.confirmOpen && m.pendingDraft != nil && strings.TrimSpace(m.pendingDraft.name) == "":
text = "Enter save name · Esc keep draft"
case m.confirmOpen:
text = "s " + m.publicationAction() + " · e edit · Esc keep draft"
case m.versionsOpen:
text = "↑/↓ choose · Enter view version · Esc back"
case m.paletteOpen && m.searchOpen:
text = "Type to search · ↑/↓ choose · Enter open · Esc cancel"
case m.paletteOpen:
text = "Type a command · ↑/↓ choose · Enter execute · Esc cancel"
case m.logOpen:
text = "j/k line · ←/→ pan · Esc back"
case m.runPicker:
text = "Type to filter · ↑/↓ choose · Enter select · Esc cancel"
case m.runForm != 0:
text = "Ctrl+S run · Enter newline · Esc cancel"
case m.templateOpen && len(m.templates) == 0:
text = ": commands · Esc back"
case m.templateOpen:
text = "s create pipeline · Tab graph · n/p template · j/k read · Esc back"
if m.templateGraphFocus {
text = "s create pipeline · Tab description · n/p template · hjkl pan · Esc back"
}
case m.runSearchOpen:
text = "Type to filter · Enter results · Esc clear"
}
if text == "" {
return ""
}
if m.width < 65 {
switch {
case m.editorChecking:
text = "Refreshing · draft retained"
case m.actionConfirm != nil || m.mutationCommand != nil:
text = "Esc cancel · y confirm · j/k read"
case m.draftDeletingPath != "":
text = "Esc keep · y delete · j/k read"
case m.statusOpen:
text = "Esc back · r refresh · j/k read"
case m.editorOpen || m.runPicker:
text = "Esc back · Enter open · ↑↓ select"
case m.confirmOpen && m.templateConfirm:
text = "Esc keep · Enter create pipeline"
if m.pendingDraft != nil && m.pendingDraft.path == "" {
text = "Esc back · Enter create pipeline"
}
case m.confirmOpen && m.pendingDraft != nil && strings.TrimSpace(m.pendingDraft.name) == "":
text = "Esc keep · Enter save name"
case m.confirmOpen:
text = "Esc keep · s " + m.publicationAction()
case m.versionsOpen:
text = "Esc back · Enter view · ↑↓ select"
case m.paletteOpen && m.searchOpen:
text = "Esc back · Enter open · ↑↓ select"
case m.paletteOpen:
text = "Esc back · Enter run · ↑↓ select"
case m.logOpen:
text = "Esc back · j/k read · ←→ pan"
case m.runForm != 0:
text = "Esc cancel · Ctrl+S run"
case m.templateOpen:
text = "Esc · s create · Tab graph · n/p"
if m.templateGraphFocus {
text = "Esc · Tab description · hjkl pan · n/p"
}
case m.runSearchOpen:
text = "Esc clear · Enter results"
}
}
return lipgloss.NewStyle().Foreground(themeMuted).Render(ansi.Truncate(text, max(1, m.width), "…"))
}
func (m Model) publicationAction() string {
if m.pendingDraft != nil && !m.pendingDraft.createOnly && m.pendingDraft.baseVersion > 0 {
return "update pipeline"
}
return "create pipeline"
}
+3 -3
View File
@@ -80,7 +80,7 @@ func TestCreateAndSubmit(t *testing.T) {
m = updated.(Model)
}
text := strings.Join(m.lines, "\n")
for _, expected := range []string{"Submitted demo: version 1", "Already published", "unexpected text outside a block"} {
for _, expected := range []string{"Created pipeline demo: version 1", "Already published", "unexpected text outside a block"} {
if !strings.Contains(text, expected) {
t.Fatalf("missing %q in %s", expected, text)
}
@@ -123,12 +123,12 @@ func TestPopupLayout(t *testing.T) {
}
}
if size.Width == 100 {
if !strings.Contains(view, "Submit edited pipeline") || !strings.Contains(view, "demo") {
if !strings.Contains(view, "Create pipeline") || !strings.Contains(view, "demo") {
t.Fatal("missing form content")
}
var top int
for i, line := range lines {
if strings.Contains(line, "Submit edited pipeline") {
if strings.Contains(line, "Create pipeline") {
top = i
if !strings.HasPrefix(line, " ") {
t.Fatalf("dialog not horizontally centered: %q", line)
+142 -26
View File
@@ -13,9 +13,46 @@ import (
"git.a-wan.net/alan/pipelines/internal/protocol"
)
var commands = []string{":status", ":logs", ":new", ":drafts", ":templates", ":refresh", ":ping", ":edit", ":submit", ":versions", ":run", ":runs", ":retry", ":debug", ":pipeline", ":home", ":quit"}
var commands = []string{":status", ":logs", ":new", ":drafts", ":templates", ":export", ":import", ":refresh", ":ping", ":edit", ":submit", ":versions", ":run", ":runs", ":retry", ":debug", ":pipeline", ":home", ":quit"}
var commandDescriptions = map[string]string{
":export": "Select pipelines and save their definitions in a portable ZIP in the current directory.",
":import": "Select definitions from a ZIP, resolve conflicts, then confirm publication. Schedules may activate.",
":status": "Server health and phone connection details", ":logs": "Read retained client diagnostics", ":new": "Create a retained pipeline draft", ":drafts": "Continue editing or publish a draft", ":templates": "Choose a reusable workflow starter", ":refresh": "Reload the current screen from the server", ":ping": "Check the server connection", ":edit": "Edit a retained draft of this definition", ":submit": "Publish the edited draft after confirmation", ":versions": "View an immutable published version", ":run": "Describe a task for this pipeline", ":runs": "Inspect recorded runs and their results", ":retry": "Confirm a fresh run; previous side effects may repeat", ":debug": "Open OpenCode with the pinned definition and failure evidence", ":pipeline": "View the definition used by this run", ":home": "Return to recent results and pipelines", ":quit": "Exit the client; server-owned runs continue"}
func (m Model) footerContent() string {
if footer := m.activeFooter(); footer != "" {
return footer
}
if m.width < 80 && m.runOpen {
text := "↑↓ select · Enter open · / find · Esc"
if len(m.visibleRuns()) == 0 {
text = "Esc back · / search · : commands"
}
if m.runDetail != nil {
text = "Tab graph · n/p visit · j/k read · Esc"
if m.runGraphFocus {
text = "Tab details · n/p visit · hjkl pan · Esc"
}
if m.width < 40 {
text = "Esc back · Tab pane · j/k read"
}
if m.width < 30 {
text = "Esc · Tab pane"
}
}
return lipgloss.NewStyle().Foreground(themeMuted).Render(ansi.Truncate(text, max(1, m.width), "…"))
}
if m.width < 80 && m.keys.detail {
text := "Tab stage · n/p stage · hjkl pan · Esc"
if m.stageFocus {
text = "Tab graph · n/p stage · j/k read · Esc"
}
if m.width < 40 {
text = "Esc home · Tab pane · n/p stage"
}
return lipgloss.NewStyle().Foreground(themeMuted).Render(ansi.Truncate(text, max(1, m.width), "…"))
}
label := fmt.Sprintf(" LOGS %d · :logs ", len(m.lines))
style := lipgloss.NewStyle().Foreground(themeMuted)
if m.unread > 0 {
@@ -35,6 +72,8 @@ func (m Model) footerContent() string {
left := ""
if available > 0 {
keys := m.keys
keys.runInspect = m.runDetail != nil
keys.runGraph = m.runGraphFocus
keys.retryAvailable = m.selectedFailedRun() > 0
left = ansi.Truncate(m.help.View(keys), available, "…")
}
@@ -43,43 +82,52 @@ func (m Model) footerContent() string {
func (m Model) homeLines() []string {
panelWidth := m.width
if m.width >= 96 {
panelWidth = (m.width - 2) / 2
if m.width >= 120 {
panelWidth = (m.width - 2) * 3 / 5
}
runs := []string{bar("Latest runs", fmt.Sprint(len(m.runs)), max(1, panelWidth-4), true),
lipgloss.NewStyle().Foreground(themeMuted).Render("Outcome · Result · Completed work")}
runs := []string{bar("Latest runs", "Outcome & result", max(1, panelWidth-4), true), ""}
if len(m.runs) == 0 {
runs = append(runs, "No runs yet.")
}
for _, r := range m.runs[:min(8, len(m.runs))] {
runs = append(runs, lipgloss.NewStyle().Bold(true).Render(fmt.Sprintf("#%d %s", r.ID, r.Name))+fmt.Sprintf(" · v%d · %s · %s", r.Version, m.progress(r.Status), runDuration(r.CreatedAt, r.FinishedAt)), " "+resultLabel(r))
if r.CompletedSteps > 0 {
runs = append(runs, fmt.Sprintf(" %d completed visits", r.CompletedSteps))
if !m.loaded {
runs = append(runs, m.loading("Loading recent work…"))
} else {
runs = append(runs, "No runs yet.", "Results will appear here after you run a pipeline.")
}
}
limit := 4
if m.width < 120 {
limit = 2
}
for _, r := range m.runs[:min(limit, len(m.runs))] {
runs = append(runs, bar(fmt.Sprintf("#%d %s", r.ID, r.Name), m.progress(r.Status), max(1, panelWidth-4), false))
runs = append(runs, previewRows(resultLabel(r), max(1, panelWidth-4), 3)...)
runs = append(runs, lipgloss.NewStyle().Foreground(themeMuted).Render(fmt.Sprintf("v%d · %d completed visits · %s", r.Version, r.CompletedSteps, runDuration(r.CreatedAt, r.FinishedAt))))
if r.CurrentStage != "" && (r.Status == "running" || r.Status == "queued") {
runs = append(runs, " Stage: "+r.CurrentStage)
runs = append(runs, "Working on "+r.CurrentStage)
}
runs = append(runs, "")
}
if len(m.runs) > 8 {
runs = append(runs, fmt.Sprintf("%d more runs in history", len(m.runs)-8))
if len(m.runs) > limit {
runs = append(runs, lipgloss.NewStyle().Foreground(themeMuted).Render(fmt.Sprintf("%d more runs in history", len(m.runs)-limit)))
}
lines := []string{bar("Existing pipelines", fmt.Sprintf("%d", len(m.pipelines)), max(1, panelWidth-4), true), ""}
pipelineWidth := m.width
if m.width >= 120 {
pipelineWidth = m.width - panelWidth - 2
}
lines := []string{bar("Existing pipelines", fmt.Sprintf("%d", len(m.pipelines)), max(1, pipelineWidth-4), true), ""}
if !m.loaded {
lines = append(lines, m.loading("Waiting for pipeline data…"))
} else if len(m.pipelines) == 0 {
lines = append(lines, "No pipelines yet. Create one using commands.")
} else {
for _, p := range m.pipelines {
for _, p := range m.pipelines[:min(4, len(m.pipelines))] {
lines = append(lines,
lipgloss.NewStyle().Bold(true).Render(p.Name)+lipgloss.NewStyle().Foreground(themeMuted).Render(fmt.Sprintf(" v%d · %d stages", p.Version, p.Stages)),
lipgloss.NewStyle().Foreground(themeMuted).Render(" Updated: "+dateLabel(p.UpdatedAt)))
lipgloss.NewStyle().Bold(true).Render(p.Name), lipgloss.NewStyle().Foreground(themeMuted).Render(fmt.Sprintf("v%d · %d stages", p.Version, p.Stages)))
if r := m.latestPipelineRun(p.ID, 0); r != nil {
lines = append(lines, fmt.Sprintf(" Last run #%d · v%d · %s", r.ID, r.Version, m.progress(r.Status)), " "+resultLabel(*r))
lines = append(lines, fmt.Sprintf("Last run #%d · v%d · %s", r.ID, r.Version, m.progress(r.Status)))
lines = append(lines, previewRows(resultLabel(*r), max(1, pipelineWidth-4), 2)...)
} else {
lines = append(lines, " Not run yet · no recorded results")
lines = append(lines, "Not run yet · no recorded results")
}
lines = append(lines, lipgloss.NewStyle().Foreground(themeMuted).Render(" Created: "+dateLabel(p.CreatedAt)))
if m.usage != nil {
for _, u := range m.usage.Pipelines {
if u.PipelineID == p.ID {
@@ -90,6 +138,9 @@ func (m Model) homeLines() []string {
}
lines = append(lines, "")
}
if len(m.pipelines) > 4 {
lines = append(lines, fmt.Sprintf("%d more pipelines", len(m.pipelines)-4))
}
}
if m.width < 8 {
return append(append(runs, ""), lines...)
@@ -104,10 +155,22 @@ func (m Model) homeLines() []string {
return content
}
panels := widget(runs, panelWidth) + "\n\n" + widget(lines, panelWidth)
if m.width >= 96 {
if m.width >= 120 {
panels = lipgloss.JoinHorizontal(lipgloss.Top, widget(runs, panelWidth), " ", widget(lines, m.width-panelWidth-2))
}
return strings.Split(widget(m.usageLines(), m.width)+"\n"+panels, "\n")
if m.usage != nil {
panels += "\n\n" + widget(m.usageLines(), m.width)
}
return strings.Split(panels, "\n")
}
func previewRows(text string, width, limit int) []string {
rows := strings.Split(ansi.Wrap(ansi.Strip(text), max(1, width), ""), "\n")
if len(rows) > limit {
rows = rows[:limit]
rows[limit-1] = ansi.Truncate(rows[limit-1], max(1, width-1), "") + "…"
}
return rows
}
func (m Model) homePage() bool {
@@ -190,6 +253,10 @@ func (m Model) updatePalette(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
m.paletteOpen = false
m.keys.palette = false
switch command {
case ":export":
return m.transferPipelines(false)
case ":import":
return m.transferPipelines(true)
case ":status":
return m.openStatus()
case ":debug":
@@ -210,6 +277,7 @@ func (m Model) updatePalette(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
m.logOpen = true
m.keys.logs = true
m.logTop = max(0, len(m.lines)-m.logPageSize())
m.logPan = 0
m.markVisibleLogs()
return m, nil
case ":new":
@@ -225,7 +293,7 @@ func (m Model) updatePalette(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
m.confirmOpen = true
m.keys.confirm = true
} else {
m.appendLine("no edited draft to submit")
m.appendLine("no edited draft to create/update")
}
return m, nil
case ":versions":
@@ -234,6 +302,9 @@ func (m Model) updatePalette(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
m.closeRuns()
return m.goHome(), nil
case ":refresh":
if m.templateOpen {
return m.openTemplates()
}
if m.runOpen {
request := protocol.Message{Type: protocol.ListRuns}
if m.requestedRunID > 0 {
@@ -285,7 +356,16 @@ func (m Model) updateLogs(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
m.logTop -= max(1, m.logPageSize()/2)
case "l":
m.logTop += max(1, m.logPageSize()/2)
case "left":
m.logPan = max(0, m.logPan-8)
case "right":
m.logPan += 8
}
widest := 0
for _, line := range m.lines {
widest = max(widest, ansi.StringWidth(line))
}
m.logPan = min(m.logPan, max(0, widest-min(100, max(1, m.width-6))))
m.logTop = max(0, min(m.logTop, max(0, len(m.lines)-m.logPageSize())))
m.markVisibleLogs()
return m, nil
@@ -312,13 +392,41 @@ func popup(width, height, preferredWidth int, lines []string) string {
return lipgloss.Place(width, height, lipgloss.Center, lipgloss.Center, dialog)
}
// Safety text wraps and scrolls independently of its pinned title and controls.
func wrappedDialog(width, height, preferredWidth int, title string, paragraphs []string, controls string, top int) string {
if width <= 0 || height <= 0 {
return ""
}
dialogWidth := min(width, preferredWidth+4)
inner := max(1, dialogWidth-4)
var rows []string
for i, text := range paragraphs {
if i > 0 {
rows = append(rows, "")
}
rows = append(rows, strings.Split(ansi.Wrap(ansi.Strip(text), inner, ""), "\n")...)
}
dialogHeight := min(height, len(rows)+4)
page := max(0, dialogHeight-4)
top = max(0, min(top, max(0, len(rows)-page)))
if page < len(rows) {
controls += " · j/k read"
}
content := panel(dialogWidth, dialogHeight, []string{bar(title, "", inner, true)}, rows[top:min(len(rows), top+page)], controls, true)
return lipgloss.Place(width, height, lipgloss.Center, lipgloss.Center, content)
}
func (m Model) logsView(height int) string {
end := min(len(m.lines), m.logTop+m.logPageSize())
lines := []string{fmt.Sprintf("Logs · %d–%d / %d", min(m.logTop+1, len(m.lines)), end, len(m.lines)), ""}
if len(m.lines) == 0 {
lines[0] = "Logs"
lines = append(lines, "No logs yet.")
} else {
lines = append(lines, m.lines[m.logTop:end]...)
width := min(100, max(1, m.width-6))
for _, line := range m.lines[m.logTop:end] {
lines = append(lines, ansi.Cut(line, m.logPan, m.logPan+width))
}
}
return popup(m.width, height, 100, lines)
}
@@ -334,7 +442,12 @@ func (m Model) paletteView(height int) string {
if len(items) == 0 {
lines = append(lines, "No matching commands")
}
start, end := selectionWindow(len(items), m.commandIndex, max(1, height-5))
if len(items) > 0 {
selected := items[min(m.commandIndex, len(items)-1)]
lines = append(lines, previewRows(commandDescriptions[selected], min(50, max(1, m.width-10)), 2)...)
lines = append(lines, "")
}
start, end := selectionWindow(len(items), m.commandIndex, max(1, height-8))
for i := start; i < end; i++ {
item := items[i]
prefix := " "
@@ -343,5 +456,8 @@ func (m Model) paletteView(height int) string {
}
lines = append(lines, menuOption(prefix+item, i == m.commandIndex))
}
if len(items) > 0 {
lines = append(lines, lipgloss.NewStyle().Foreground(themeMuted).Render(fmt.Sprintf("%d–%d / %d commands", start+1, end, len(items))))
}
return popup(m.width, height, 54, lines)
}
+1 -1
View File
@@ -197,7 +197,7 @@ func TestDashboardAndModalDimensions(t *testing.T) {
}
}
if size.Width == 100 && mode == "home" {
for _, text := range []string{"Existing pipelines", "demo", "v2", "3 stages", "Created:", "Updated:"} {
for _, text := range []string{"Existing pipelines", "demo", "v2", "3 stages", "Not run yet"} {
if !strings.Contains(view, text) {
t.Fatalf("missing %q", text)
}
+19 -2
View File
@@ -3,6 +3,7 @@ package tui
import (
"context"
"fmt"
"path/filepath"
"strings"
"time"
@@ -85,6 +86,10 @@ func (m Model) updateDrafts(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
m.submitNotice = ""
}
return m.openDrafts()
case "j", "down", "pgdown":
m.draftDeletingTop++
case "k", "up", "pgup":
m.draftDeletingTop = max(0, m.draftDeletingTop-1)
}
return m, nil
}
@@ -92,6 +97,7 @@ func (m Model) updateDrafts(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
case "x":
if len(m.draftItems) > 0 && m.submitID == "" {
m.draftDeletingPath = m.draftItems[m.draftIndex].Path
m.draftDeletingTop = 0
}
return m, nil
case "esc":
@@ -150,7 +156,14 @@ func (m Model) updateDrafts(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
func (m Model) draftsView(height int) string {
if m.draftDeletingPath != "" {
return popup(m.width, height, 90, []string{"Delete retained draft?", m.draftDeletingPath, "Only this draft and its metadata are deleted. Published pipelines/history stay intact.", "y delete · n/Esc keep"})
name := filepath.Base(m.draftDeletingPath)
for _, item := range m.draftItems {
if item.Path == m.draftDeletingPath && item.Name != "" {
name = item.Name + " · " + name
break
}
}
return wrappedDialog(m.width, height, 90, "Delete retained draft?", []string{name, "Only this draft and its metadata are deleted. Published pipelines/history stay intact.", "File: " + m.draftDeletingPath}, "y delete · n/Esc keep", m.draftDeletingTop)
}
if len(m.draftItems) == 0 {
return fitBlock([]string{"Drafts", "No retained drafts.", m.draftError, "r refresh · Esc back"}, m.width, height)
@@ -165,7 +178,11 @@ func (m Model) draftsView(height int) string {
rows := max(0, height-len(lines)-1)
top := min(m.draftTop, max(0, len(source)-rows))
lines = append(lines, source[top:min(len(source), top+rows)]...)
lines = append(lines, "n/p select · e edit · v validate · s submit · x delete · r refresh · Esc back")
label := "create pipeline"
if !d.CreateOnly && d.BaseVersion > 0 && (d.Server == "" || d.Server == m.url) {
label = "update pipeline"
}
lines = append(lines, "n/p select · e edit · v validate · s "+label+" · x delete · r refresh · Esc back")
for i := range lines {
lines[i] = ansi.Strip(lines[i])
}
+6 -2
View File
@@ -74,13 +74,17 @@ func (m Model) editorPickerView(height int) string {
input := m.editorInput
input.Width = max(1, min(60, m.width-12))
muted := lipgloss.NewStyle().Foreground(themeMuted)
lines := []string{"Edit pipeline with…", input.View(), muted.Render("Tab/Shift+Tab choose · type to search · Enter open · Esc cancel"), ""}
lines := []string{"Edit pipeline with…", "Filter editors: " + input.View(), ""}
if m.editorDraft != nil && m.editorDraft.createOnly {
lines[0] = "New pipeline with…"
}
choices := m.editorChoices()
for i, choice := range choices {
lines = append(lines, menuOption(choice, i == m.editorIndex))
prefix := " "
if i == m.editorIndex {
prefix = "▸ "
}
lines = append(lines, menuOption(prefix+choice, i == m.editorIndex))
if choice == "nvim" {
lines = append(lines, muted.Render(" Write the pipeline Markdown in a retained draft file."))
} else {
+106
View File
@@ -0,0 +1,106 @@
package tui
import (
"fmt"
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
)
func fileChangesSummary(step protocol.RunStep) string {
if step.FileChanges == nil {
if step.Status == "running" {
return "File changes · capture pending"
}
return "File changes · not recorded for this visit"
}
c := step.FileChanges
if c.Status == "unavailable" {
return "File changes · capture unavailable"
}
label := fmt.Sprintf("File changes · %d observed files", len(c.Files))
if len(c.Files) == 0 {
label = "File changes · no changes observed"
}
if c.Status == "partial" {
label += " · partial capture"
}
return label + " · d view diff"
}
func diffHighlight(line string) string {
line = ansi.Strip(line)
line = strings.ReplaceAll(strings.ReplaceAll(line, "\t", " "), "\r", "␍")
line = strings.Map(func(r rune) rune {
if r < 32 || r == 127 {
return '�'
}
return r
}, line)
style := lipgloss.NewStyle()
switch {
case strings.HasPrefix(line, "--- "), strings.HasPrefix(line, "+++ "):
style = style.Foreground(themeMuted).Bold(true)
case strings.HasPrefix(line, "@@"):
style = style.Foreground(themeAccent).Bold(true)
case strings.HasPrefix(line, "+"):
style = style.Foreground(lipgloss.Color("2"))
case strings.HasPrefix(line, "-"):
style = style.Foreground(lipgloss.Color("1"))
case strings.HasPrefix(line, "\\ "):
style = style.Foreground(themeMuted)
}
return style.Render(line)
}
// HighlightDiff also sanitizes untrusted source before terminal rendering.
func HighlightDiff(patch string) string {
lines := strings.Split(strings.TrimSuffix(patch, "\n"), "\n")
for i, line := range lines {
lines[i] = diffHighlight(line)
}
return strings.Join(lines, "\n")
}
func stageDiffLines(step protocol.RunStep) []string {
c := step.FileChanges
if c == nil {
return []string{fileChangesSummary(step)}
}
lines := []string{fileChangesSummary(step), "Observed workspace changes during this visit; not proof of exclusive authorship."}
if c.Scope != "" {
lines = append(lines, c.Scope)
}
if c.Diagnostic != "" {
lines = append(lines, lipgloss.NewStyle().Foreground(themeError).Render(ansi.Strip(c.Diagnostic)))
}
if c.Skipped > 0 {
lines = append(lines, fmt.Sprintf("%d files excluded from capture.", c.Skipped))
}
if c.Omitted > 0 {
lines = append(lines, fmt.Sprintf("%d additional changed files omitted by capture limits.", c.Omitted))
}
for _, file := range c.Files {
lines = append(lines, "", lipgloss.NewStyle().Bold(true).Render(fmt.Sprintf("%s · %q", file.Kind, file.Path)))
if file.BeforeMode != file.AfterMode {
lines = append(lines, fmt.Sprintf("Mode: %s → %s", file.BeforeMode, file.AfterMode))
}
if file.Binary {
lines = append(lines, "Binary file changed · contents not displayed.")
}
if file.Patch != "" {
for _, line := range strings.Split(strings.TrimSuffix(file.Patch, "\n"), "\n") {
lines = append(lines, diffHighlight(line))
}
}
if file.Truncated {
lines = append(lines, lipgloss.NewStyle().Foreground(themeMuted).Render("Patch omitted or truncated by capture limits."))
}
if !file.Binary && file.Patch == "" && !file.Truncated {
lines = append(lines, "No text hunk · empty file or file-mode change.")
}
}
return lines
}
+90
View File
@@ -0,0 +1,90 @@
package tui
import (
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
"github.com/muesli/termenv"
)
func TestDiffHighlightAndTerminalSafety(t *testing.T) {
old := lipgloss.ColorProfile()
lipgloss.SetColorProfile(termenv.ANSI256)
defer lipgloss.SetColorProfile(old)
for _, line := range []string{"+added", "-removed", "@@ -1 +1 @@", "--- a/file", "+++ b/file"} {
rendered := diffHighlight(line)
if rendered == ansi.Strip(rendered) {
t.Fatal("diff not highlighted", line)
}
if ansi.Strip(rendered) != line {
t.Fatal("diff text changed", rendered)
}
}
unsafe := diffHighlight("+\x1b[2J\x07evil")
if strings.Contains(unsafe, "\x1b[2J") || strings.Contains(unsafe, "\x07") {
t.Fatal("terminal control retained", unsafe)
}
}
func TestStageDiffResultsAndHistoricalState(t *testing.T) {
step := protocol.RunStep{Status: "completed", FileChanges: &protocol.StageFileChanges{Status: "partial", Skipped: 1, Files: []protocol.FileChange{{Path: "main.go", Kind: "modified", Patch: "--- a/main.go\n+++ b/main.go\n@@ -1 +1 @@\n-old\n+new\n"}, {Path: "image.png", Kind: "added", Binary: true}, {Path: "big", Kind: "modified", Truncated: true}}}}
text := ansi.Strip(strings.Join(stageDiffLines(step), "\n"))
for _, want := range []string{"main.go", "-old", "+new", "Binary file", "truncated", "partial capture", "not proof of exclusive authorship"} {
if !strings.Contains(text, want) {
t.Fatal(want, text)
}
}
if !strings.Contains(fileChangesSummary(protocol.RunStep{Status: "completed"}), "not recorded") {
t.Fatal("historical stage implies no edits")
}
if !strings.Contains(fileChangesSummary(protocol.RunStep{Status: "running"}), "pending") {
t.Fatal("running stage implies no edits")
}
m := Model{width: 80, runDetail: &protocol.RunDetail{Steps: []protocol.RunStep{step}}, runStepIndex: 1}
text = ansi.Strip(strings.Join(m.runSectionLines(74), "\n"))
if !strings.Contains(text, "[d] ▾ File changes") || !strings.Contains(text, "+new") {
t.Fatal("diff missing from stage details", text)
}
m.toggleRunSection(5)
text = ansi.Strip(strings.Join(m.runSectionLines(74), "\n"))
if strings.Contains(text, "+new") {
t.Fatal("collapsed diff still visible")
}
}
func TestDiffShortcutPerVisitAndNarrowLayout(t *testing.T) {
m := runInspectionModel()
m = runKey(m, "n")
c := &protocol.StageFileChanges{Status: "complete", Files: []protocol.FileChange{{Path: "long/path/main.go", Kind: "modified", Patch: "--- a/main.go\n+++ b/main.go\n@@ -1 +1 @@\n-old line\n+new line\n"}}}
m.runDetail.Steps[0].FileChanges = c
m = runKey(m, "g")
m = runKey(m, "d")
if m.runGraphFocus || !m.runDetailFocus || m.runSectionClosed(5) {
t.Fatal("diff shortcut did not focus open section")
}
_, title := runFocusedSection(m.runSectionLines(m.runDetailWidth()), m.runTop)
if title != "File changes" {
t.Fatal(title)
}
m = runKey(m, "d")
if !m.runSectionClosed(5) {
t.Fatal("diff shortcut failed to collapse")
}
m = runKey(m, "n")
if m.runSectionClosed(5) {
t.Fatal("collapse leaked to next visit")
}
m = runKey(m, "p")
m = runKey(m, "d")
for _, width := range []int{120, 63, 35, 10} {
m.width = width
for _, line := range strings.Split(m.runsView(24), "\n") {
if ansi.StringWidth(line) > width {
t.Fatal("diff exceeds viewport", width, line)
}
}
}
}
+150 -118
View File
@@ -51,6 +51,8 @@ type keyMap struct {
versions bool
confirm bool
runs bool
runInspect bool
runGraph bool
retryAvailable bool
templates bool
drafts bool
@@ -58,10 +60,10 @@ type keyMap struct {
func (k keyMap) ShortHelp() []key.Binding {
if k.confirm {
return []key.Binding{key.NewBinding(key.WithKeys("s"), key.WithHelp("s", "submit")), key.NewBinding(key.WithKeys("e"), key.WithHelp("e", "edit")), k.cancel}
return []key.Binding{key.NewBinding(key.WithKeys("s"), key.WithHelp("s", "create/update pipeline")), key.NewBinding(key.WithKeys("e"), key.WithHelp("e", "edit")), k.cancel}
}
if k.drafts {
return []key.Binding{key.NewBinding(key.WithKeys("n", "p"), key.WithHelp("n/p", "draft")), key.NewBinding(key.WithKeys("e"), key.WithHelp("e", "edit")), key.NewBinding(key.WithKeys("v"), key.WithHelp("v", "validate")), key.NewBinding(key.WithKeys("s"), key.WithHelp("s", "submit")), k.cancel}
return []key.Binding{key.NewBinding(key.WithKeys("n", "p"), key.WithHelp("n/p", "draft")), key.NewBinding(key.WithKeys("e"), key.WithHelp("e", "edit")), key.NewBinding(key.WithKeys("v"), key.WithHelp("v", "validate")), key.NewBinding(key.WithKeys("s"), key.WithHelp("s", "create/update pipeline")), k.cancel}
}
if k.versions {
return []key.Binding{key.NewBinding(key.WithKeys("j", "k"), key.WithHelp("j/k", "select")), k.enter, k.cancel}
@@ -73,14 +75,17 @@ func (k keyMap) ShortHelp() []key.Binding {
return []key.Binding{k.enter, k.cancel}
}
if k.templates {
return []key.Binding{key.NewBinding(key.WithKeys("s", "enter"), key.WithHelp("s/Enter", "submit")), key.NewBinding(key.WithKeys("e"), key.WithHelp("e", "customize")), key.NewBinding(key.WithKeys("n", "p"), key.WithHelp("n/p", "template")), key.NewBinding(key.WithKeys("v"), key.WithHelp("v", "render/source")), k.cancel}
return []key.Binding{key.NewBinding(key.WithKeys("s", "enter"), key.WithHelp("s/Enter", "create pipeline")), key.NewBinding(key.WithKeys("tab"), key.WithHelp("Tab", "pane")), key.NewBinding(key.WithKeys("e"), key.WithHelp("e", "customize")), key.NewBinding(key.WithKeys("n", "p"), key.WithHelp("n/p", "template")), k.cancel}
}
if k.runs {
bindings := []key.Binding{k.commands, key.NewBinding(key.WithKeys("n", "p"), key.WithHelp("n/p", "next/prev stage")), key.NewBinding(key.WithKeys("g"), key.WithHelp("g", "graph")), key.NewBinding(key.WithKeys("D"), key.WithHelp("D", "debug")), key.NewBinding(key.WithKeys("P"), key.WithHelp("P", "pipeline"))}
if k.retryAvailable {
bindings = append(bindings, key.NewBinding(key.WithKeys("r"), key.WithHelp("r", "retry failed")))
if !k.runInspect {
return []key.Binding{k.commands, k.search, key.NewBinding(key.WithKeys("j", "k"), key.WithHelp("j/k", "select")), k.enter, key.NewBinding(key.WithKeys("esc"), key.WithHelp("Esc", "back"))}
}
return append(bindings, key.NewBinding(key.WithKeys("tab"), key.WithHelp("Tab", "pane")), key.NewBinding(key.WithKeys("j", "k"), key.WithHelp("j/k", "select/scroll")), key.NewBinding(key.WithKeys("esc"), key.WithHelp("Esc", "back")))
target, keys, action := "graph", "j/k", "scroll"
if k.runGraph {
target, keys, action = "details", "h/j/k/l", "pan"
}
return []key.Binding{k.commands, key.NewBinding(key.WithKeys("tab"), key.WithHelp("Tab", target)), key.NewBinding(key.WithKeys("n", "p"), key.WithHelp("n/p", "stage")), key.NewBinding(key.WithKeys(keys), key.WithHelp(keys, action)), key.NewBinding(key.WithKeys("esc"), key.WithHelp("Esc", "back"))}
}
if k.detail {
return []key.Binding{k.commands, k.search, key.NewBinding(key.WithKeys("n", "p"), key.WithHelp("n/p", "next/prev stage")), key.NewBinding(key.WithKeys("tab"), key.WithHelp("Tab", "pane")), key.NewBinding(key.WithKeys("r"), key.WithHelp("r", "runs")), key.NewBinding(key.WithKeys("j", "k"), key.WithHelp("j/k", "scroll")), key.NewBinding(key.WithKeys("esc"), key.WithHelp("esc", "home"))}
@@ -90,101 +95,108 @@ func (k keyMap) ShortHelp() []key.Binding {
func (k keyMap) FullHelp() [][]key.Binding { return [][]key.Binding{k.ShortHelp()} }
type Model struct {
editorCheckGeneration uint64
editorChecking bool
statusOpen bool
statusTop int
statusRequest, statusError string
systemStatus *protocol.SystemStatus
usage *protocol.UsageStats
draftOpen bool
draftItems []draft.Draft
draftIndex, draftTop int
draftError, draftSource string
ctx context.Context
url string
conn *websocket.Conn
status string
nextID uint64
lines []string
width int
height int
help help.Model
keys keyMap
pipelines []protocol.PipelineSummary
loaded bool
notificationEndpoints []protocol.NotificationEndpoint
logSeen []bool
unread int
logOpen bool
logTop int
paletteOpen bool
commandInput textinput.Model
commandIndex int
homeTop int
searchOpen bool
detail *protocol.PipelineDetail
detailRequest string
detailLoading bool
detailError string
pipelineTop int
graphPan int
versionsOpen bool
versionIndex int
confirmOpen bool
actionConfirm *protocol.Message
actionApproved bool
defaultModel string
mutationTitle string
mutationCommand func() tea.Cmd
pendingDraft *editedMsg
draftNameInput textinput.Model
submitID string
submitNotice string
stageIndex int
stageTop int
stageFocus bool
reconnecting bool
requestedPipelineID int64
requestedVersion int
runs []protocol.RunSummary
runDetail *protocol.RunDetail
runOpen bool
runForm int
runInput textinput.Model
runPrompt textarea.Model
runWorkspace string
cliRun, cliStarted, runPicker bool
cliOptions RunOptions
runPickerIndex int
runPickerInput textinput.Model
runTask string
runPaths []string
runIndex, runTop int
requestedRunID int64
runStartRequest string
runStepIndex int
runDetailFocus bool
runCollapsed map[string]bool
runError string
runPipelineID int64
runFailedOnly bool
runSearch textinput.Model
runSearchOpen bool
runGraphFocus bool
runGraphTop int
runGraphPan int
editorOpen bool
editorInput textinput.Model
editorIndex int
editorDraft *editedMsg
draftDeletingPath string
runSpinner spinner.Model
templates []protocol.Template
templateOpen, templateRaw bool
templateIndex, templateTop int
templateLines []string
templateRequest, templateError string
editorCheckGeneration uint64
editorChecking bool
statusOpen bool
statusTop int
statusRequest, statusError string
systemStatus *protocol.SystemStatus
usage *protocol.UsageStats
draftOpen bool
draftItems []draft.Draft
draftIndex, draftTop int
draftError, draftSource string
ctx context.Context
url string
conn *websocket.Conn
status string
nextID uint64
lines []string
width int
height int
help help.Model
keys keyMap
pipelines []protocol.PipelineSummary
loaded bool
notificationEndpoints []protocol.NotificationEndpoint
logSeen []bool
unread int
logOpen bool
logTop int
logPan int
paletteOpen bool
commandInput textinput.Model
commandIndex int
homeTop int
searchOpen bool
detail *protocol.PipelineDetail
detailRequest string
detailLoading bool
detailError string
pipelineTop int
graphPan int
versionsOpen bool
versionIndex int
confirmOpen bool
actionConfirm *protocol.Message
actionConfirmTop int
actionApproved bool
defaultModel string
mutationTitle string
mutationCommand func() tea.Cmd
mutationTop int
pendingDraft *editedMsg
draftNameInput textinput.Model
submitID string
submitNotice string
stageIndex int
stageTop int
stageFocus bool
stageConfigExpanded bool
reconnecting bool
requestedPipelineID int64
requestedVersion int
runs []protocol.RunSummary
runDetail *protocol.RunDetail
runOpen bool
runForm int
runInput textinput.Model
runPrompt textarea.Model
runWorkspace string
cliRun, cliStarted, runPicker bool
cliOptions RunOptions
runPickerIndex int
runPickerInput textinput.Model
runTask string
runPaths []string
runIndex, runTop int
requestedRunID int64
runStartRequest string
runStepIndex int
runDetailFocus bool
runCollapsed map[string]bool
runError string
runPipelineID int64
runFailedOnly bool
runSearch textinput.Model
runSearchOpen bool
runGraphFocus bool
runGraphTop int
runGraphPan int
editorOpen bool
editorInput textinput.Model
editorIndex int
editorDraft *editedMsg
draftDeletingPath string
draftDeletingTop int
runSpinner spinner.Model
templates []protocol.Template
templateOpen, templateRaw bool
templateGraphFocus, templateConfirm bool
templateGraphTop, templateGraphPan int
templateIndex, templateTop int
templateLines []string
templateRequest, templateError string
}
func New(ctx context.Context, url string) Model {
@@ -268,12 +280,15 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.help.Width = m.width
if m.runForm == 1 {
m.runPrompt.SetWidth(max(1, min(96, m.width-12)))
m.runPrompt.SetHeight(max(1, min(10, m.height-14)))
m.runPrompt.SetHeight(max(1, min(14, m.height-10)))
}
if m.templateOpen {
oldTop := m.templateTop
graphTop, graphPan := m.templateGraphTop, m.templateGraphPan
m.renderTemplate()
m.templateTop = oldTop
m.templateGraphTop, m.templateGraphPan = graphTop, graphPan
m = m.clampTemplateGraph()
}
if m.keys.detail {
m.clampPipelineScroll()
@@ -377,11 +392,16 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
}
} else if msg.Type == protocol.Submitted {
m.templateConfirm = false
m.draftOpen = false
m.keys.drafts = false
m.templateOpen = false
m.keys.templates = false
m.appendLine(fmt.Sprintf("Submitted %s: version %d", msg.Name, msg.Version))
verb := "Updated"
if msg.Version == 1 {
verb = "Created"
}
m.appendLine(fmt.Sprintf("%s pipeline %s: version %d", verb, msg.Name, msg.Version))
m.pipelines = msg.Pipelines
m.loaded = true
if msg.ID == m.submitID {
@@ -389,7 +409,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.pendingDraft = nil
m.confirmOpen = false
m.keys.confirm = false
m.submitNotice = fmt.Sprintf("Submitted version %d", msg.Version)
m.submitNotice = fmt.Sprintf("%s pipeline · version %d", verb, msg.Version)
}
if msg.Detail != nil {
m.detail = msg.Detail
@@ -444,6 +464,12 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, nil
case sentMsg:
// Responses are displayed by the independent read loop.
case transferFinishedMsg:
m.transferResult(msg)
if msg.imported && m.conn != nil {
return m, m.send(protocol.Message{Type: protocol.List})
}
return m, nil
case editedMsg:
m.appendLine("Draft: " + msg.path)
if msg.err != nil {
@@ -462,7 +488,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.confirmOpen = false
m.keys.confirm = false
m.submitNotice = "No changes."
m.appendLine("No changes; nothing to submit.")
m.appendLine("No changes; nothing to update.")
return m, nil
}
// Editor completion is never approval to publish, for either new or existing drafts.
@@ -516,6 +542,12 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.mutationCommand = nil
m.mutationTitle = ""
}
if msg.String() == "j" || msg.String() == "down" || msg.String() == "pgdown" {
m.mutationTop++
}
if msg.String() == "k" || msg.String() == "up" || msg.String() == "pgup" {
m.mutationTop = max(0, m.mutationTop-1)
}
return m, nil
}
if m.editorChecking {
@@ -657,17 +689,6 @@ func (m Model) View() string {
if m.conn == nil {
connection = m.loading(connection)
}
if len(m.notificationEndpoints) > 0 {
endpoint := m.notificationEndpoints[0]
address := endpoint.ServerURL
if address == "" {
address = "not configured"
}
connection += " · ntfy " + address + " · topic " + endpoint.Topic
if m.width < 100 {
connection = "Connected · ntfy " + address + "/" + endpoint.Topic
}
}
status := ansi.Truncate(connection, max(0, m.width-min(24, m.width/4)), "…")
title := ""
if titleWidth := m.width - lipgloss.Width(status) - 1; titleWidth > 0 {
@@ -693,6 +714,9 @@ func (m Model) View() string {
if m.draftOpen {
name = "Drafts"
}
if m.statusOpen {
name = "Status"
}
title = ansi.Truncate(name, titleWidth, "…")
}
gap := max(0, m.width-lipgloss.Width(title)-lipgloss.Width(status))
@@ -705,6 +729,7 @@ func (m Model) View() string {
}
bodyHeight := max(0, m.height-lipgloss.Height(header)-lipgloss.Height(footer))
lines := m.homeLines()
homeLength := len(lines)
top := m.homeTop
top = min(top, max(0, len(lines)-bodyHeight))
lines = lines[top:min(len(lines), top+bodyHeight)]
@@ -712,6 +737,9 @@ func (m Model) View() string {
for i, line := range lines {
body[i] = ansi.Truncate(line, m.width, "…")
}
if m.homePage() && len(body) > 0 && top+bodyHeight < homeLength {
body[len(body)-1] = bar("↓ More below", fmt.Sprintf("%d–%d / %d", top+1, top+bodyHeight, homeLength), m.width, false)
}
parts := []string{header}
if bodyHeight > 0 {
content := strings.Join(body, "\n")
@@ -752,7 +780,11 @@ func (m Model) View() string {
content = m.actionConfirmView(bodyHeight)
}
if m.mutationCommand != nil {
content = popup(m.width, bodyHeight, 76, []string{m.mutationTitle, "This opens a new session/editor and may modify a retained draft.", "Published definitions and previous run history are unchanged.", "y confirm · n / Esc cancel"})
paragraphs := []string{"This opens a new session/editor and may modify a retained draft.", "Published definitions and previous run history are unchanged."}
if strings.Contains(m.mutationTitle, "debugging") {
paragraphs = []string{"Opens OpenCode with the pinned definition and retained failure evidence.", "Debugging may propose or edit a retained draft. It does not retry the run or change published history."}
}
content = wrappedDialog(m.width, bodyHeight, 76, m.mutationTitle, paragraphs, "y confirm · n / Esc cancel", m.mutationTop)
}
if m.editorChecking {
content = popup(m.width, bodyHeight, 76, []string{"Checking published edits", m.loading("Refreshing pipeline information…"), "Local draft remains retained."})
+111
View File
@@ -0,0 +1,111 @@
package tui
import (
"context"
"fmt"
"git.a-wan.net/alan/pipelines/internal/protocol"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/x/ansi"
"strings"
)
// PickPipelines retains selections while filtering, keyed by server-local ID.
func PickPipelines(ctx context.Context, items []protocol.PipelineSummary, title string) ([]protocol.PipelineSummary, error) {
if len(items) == 0 {
return nil, fmt.Errorf("no pipelines available")
}
p := multiPicker{picker: picker{items: items, input: newInput()}, title: title, checked: map[int64]bool{}}
p.input.Placeholder = "Search pipelines…"
p.input.Focus()
result, err := tea.NewProgram(p, tea.WithContext(ctx), tea.WithAltScreen()).Run()
if err != nil {
return nil, err
}
done := result.(multiPicker)
if !done.accepted {
return nil, fmt.Errorf("selection canceled")
}
var selected []protocol.PipelineSummary
for _, item := range items {
if done.checked[item.ID] {
selected = append(selected, item)
}
}
return selected, nil
}
type multiPicker struct {
picker
title string
checked map[int64]bool
accepted bool
}
func (p multiPicker) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if key, ok := msg.(tea.KeyMsg); ok {
switch key.String() {
case "esc", "ctrl+c":
return p, tea.Quit
case " ":
items := p.matches()
if len(items) > 0 {
id := items[min(p.index, len(items)-1)].ID
if p.checked[id] {
delete(p.checked, id)
} else {
p.checked[id] = true
}
}
return p, nil
case "ctrl+a":
items := p.matches()
all := len(items) > 0
for _, item := range items {
all = all && p.checked[item.ID]
}
for _, item := range items {
if all {
delete(p.checked, item.ID)
} else {
p.checked[item.ID] = true
}
}
return p, nil
case "enter":
if len(p.checked) > 0 {
p.accepted = true
return p, tea.Quit
}
return p, nil
}
}
next, cmd := p.picker.Update(msg)
p.picker = next.(picker)
return p, cmd
}
func (p multiPicker) View() string {
width := max(1, p.width-2)
input := p.input
input.Width = max(1, min(72, width-4))
lines := []string{p.title, input.View(), fmt.Sprintf("%d selected · Space toggle · Ctrl+A toggle filtered · Enter continue · Esc cancel", len(p.checked)), ""}
items := p.matches()
start, end := selectionWindow(len(items), p.index, max(1, p.height-7))
for i := start; i < end; i++ {
prefix := " "
if i == p.index {
prefix = "▸ "
}
check := "[ ]"
if p.checked[items[i].ID] {
check = "[x]"
}
lines = append(lines, fmt.Sprintf("%s%s %s · v%d", prefix, check, ansi.Strip(items[i].Name), items[i].Version))
}
if len(items) == 0 {
lines = append(lines, "No matching pipelines")
}
for i := range lines {
lines[i] = ansi.Truncate(lines[i], width, "…")
}
return strings.Join(lines, "\n")
}
+41
View File
@@ -0,0 +1,41 @@
package tui
import (
"git.a-wan.net/alan/pipelines/internal/protocol"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/x/ansi"
"strings"
"testing"
)
func TestMultiPickerSelectionsSurviveFiltering(t *testing.T) {
p := multiPicker{picker: picker{items: []protocol.PipelineSummary{{ID: 1, Name: "alpha"}, {ID: 2, Name: "beta"}}, input: newInput(), width: 80, height: 20}, checked: map[int64]bool{}, title: "Select pipelines to export"}
key := func(k tea.KeyMsg) { t.Helper(); m, _ := p.Update(k); p = m.(multiPicker) }
key(tea.KeyMsg{Type: tea.KeyEnter})
if p.accepted {
t.Fatal("empty selection accepted")
}
key(tea.KeyMsg{Type: tea.KeySpace})
if !p.checked[1] {
t.Fatal("space did not check")
}
p.input.SetValue("beta")
key(tea.KeyMsg{Type: tea.KeyCtrlA})
if !p.checked[1] || !p.checked[2] {
t.Fatal("filtered select lost hidden item")
}
key(tea.KeyMsg{Type: tea.KeyCtrlA})
if !p.checked[1] || p.checked[2] {
t.Fatal("filtered deselect lost hidden item")
}
key(tea.KeyMsg{Type: tea.KeyEnter})
if !p.accepted {
t.Fatal("selection not accepted")
}
p.width = 25
for _, line := range strings.Split(p.View(), "\n") {
if ansi.StringWidth(line) > 23 {
t.Fatal("picker overflows", line)
}
}
}
+5 -5
View File
@@ -8,7 +8,7 @@ import (
"testing"
)
func TestHomeNotificationSetup(t *testing.T) {
func TestInfrastructureRetainedWithoutClutteringPageHeaders(t *testing.T) {
m := New(context.Background(), "ws://localhost/connect")
m.width = 120
m.height = 40
@@ -17,16 +17,16 @@ func TestHomeNotificationSetup(t *testing.T) {
view := ansi.Strip(m.View())
header := strings.Split(view, "\n")[0]
for _, text := range []string{"ntfy", "http://10.0.0.249:8090", "topic pipelines"} {
if !strings.Contains(header, text) {
t.Fatal("missing phone setup", text, view)
if strings.Contains(header, text) {
t.Fatal("infrastructure cluttered the result page header", text, view)
}
}
if strings.Contains(strings.Join(m.homeLines(), "\n"), "Phone notifications") {
t.Fatal("notification setup still occupies home panel")
}
m.runOpen = true
if !strings.Contains(strings.Split(ansi.Strip(m.View()), "\n")[0], "topic pipelines") {
t.Fatal("ntfy setup missing from run page header")
if strings.Contains(strings.Split(ansi.Strip(m.View()), "\n")[0], "topic pipelines") || len(m.notificationEndpoints) != 1 || m.notificationEndpoints[0].Topic != "pipelines" {
t.Fatal("notification information lost or leaked into run header")
}
for _, width := range []int{1, 12, 40, 80, 120} {
m.width = width
+63 -70
View File
@@ -18,20 +18,17 @@ type paneGeometry struct {
}
func (m Model) pipelineGeometry(height int) paneGeometry {
remaining := max(0, height-3-len(m.pipelineResultLines()))
if remaining >= 15 {
graph := remaining * 3 / 4
if m.stageFocus {
graph = remaining / 4
}
graph = max(6, min(remaining-8, graph))
bottom := remaining - graph
return paneGeometry{graphWidth: m.width, graphHeight: remaining - bottom, stageWidth: m.width, stageHeight: bottom}
}
remaining := max(0, height-len(m.pipelineToolbar()))
if m.stageFocus {
return paneGeometry{stageWidth: m.width, stageHeight: remaining}
if remaining < 14 {
return paneGeometry{stageWidth: m.width, stageHeight: remaining}
}
return paneGeometry{graphWidth: m.width, graphHeight: 2, stageWidth: m.width, stageHeight: remaining - 2}
}
return paneGeometry{graphWidth: m.width, graphHeight: remaining}
if remaining < 14 {
return paneGeometry{graphWidth: m.width, graphHeight: remaining}
}
return paneGeometry{graphWidth: m.width, graphHeight: remaining - 2, stageWidth: m.width, stageHeight: 2}
}
func fitBlock(lines []string, width, height int) string {
@@ -92,6 +89,9 @@ func dateLabel(value string) string {
func (m Model) pipelineToolbar() []string {
d := m.detail
if d == nil {
return []string{"", "", ""}
}
state := lipgloss.NewStyle().Foreground(themeSuccess).Bold(true).Render("LATEST")
if d.Version != d.LatestVersion {
state = lipgloss.NewStyle().Foreground(themeAccent).Render(fmt.Sprintf("HISTORY · latest v%d", d.LatestVersion))
@@ -123,6 +123,18 @@ func (m Model) pipelineToolbar() []string {
meta += " · historical, inactive"
}
}
if m.width < 80 {
short := action(fmt.Sprintf("v Version %d", d.Version), true) + " " + action("e Edit", false)
result := "Not run yet · no recorded results"
if run := m.latestPipelineRun(d.ID, d.Version); run != nil {
result = resultLabel(*run)
}
lines := []string{bar(short, state, m.width, false), ansi.Truncate(result, max(1, m.width), "…")}
if d.Graph.Settings != nil && len(d.Graph.Settings.Schedules) > 0 {
lines = append(lines, ansi.Truncate(meta, max(1, m.width), "…"))
}
return lines
}
lines := []string{buttons}
lines = append(lines, m.pipelineResultLines()...)
return append(lines, meta, "")
@@ -178,6 +190,9 @@ func (m Model) graphLines() []string {
}
func (m Model) graphPanel(width, height int) string {
if height <= 2 && height > 0 {
return fitBlock([]string{bar("Graph", "Tab to expand", width, false)}, width, height)
}
label := "Graph"
if !m.stageFocus {
label = "▸ " + label
@@ -343,75 +358,33 @@ func (m Model) stageColumns(width int) (string, []string) {
func (m Model) stageColumnsWithHeaders(width int) (string, []string, []string) {
fields := m.stageFields()
if width < 110 {
var compact []stageField
var capabilities []string
for _, field := range fields {
if field.title == "TOOLS" || field.title == "NOTIFY" {
capabilities = append(capabilities, field.title+"\n"+field.text)
} else {
compact = append(compact, field)
}
}
for i := range compact {
if compact[i].title == "CONFIGURATION" && len(capabilities) > 0 {
compact[i].text = strings.Join(capabilities, "\n\n") + "\n\n" + compact[i].text
}
}
fields = compact
}
if len(fields) == 0 {
return "Stages", []string{"No stages."}, []string{"Stages"}
}
count := 4
if width >= 110 && len(fields) > 4 {
count = 5
}
if width < 90 {
count = 4
}
if width < 68 {
count = 3
}
if width < 48 {
count = 2
}
if width < 28 {
count = 1
}
columnWidth := max(1, (width-(count-1)*3)/count)
separator := " "
order := map[string]int{"OUTPUT": 0, "TOOLS": 1, "OUTCOMES": 2, "NOTIFY": 3, "PROMPT": 4, "PERMISSIONS": 5, "CONFIGURATION": 6}
sort.SliceStable(fields, func(i, j int) bool { return order[fields[i].title] < order[fields[j].title] })
var header string
var result []string
var rowHeaders []string
for start := 0; start < len(fields); start += count {
end := min(len(fields), start+count)
columns, labels := []string{}, []string{}
height := 1
for _, field := range fields[start:end] {
rows := strings.Split(ansi.Wrap(field.text, columnWidth, ""), "\n")
height = max(height, len(rows))
columns = append(columns, strings.Join(rows, "\n"))
labels = append(labels, fitBlock([]string{lipgloss.NewStyle().Foreground(themeAccent).Bold(true).Render(field.title)}, columnWidth, 1))
selected := m.selectedStage()
collapsedConfig := !m.stageConfigExpanded && selected != nil && (selected.Type == "" || selected.Type == stageconfig.ModelType)
for i, field := range fields {
title := field.title
if title == "CONFIGURATION" && collapsedConfig {
title = "▸ CONFIGURATION · c expand"
}
label := strings.Join(labels, separator)
if start == 0 {
label := lipgloss.NewStyle().Foreground(themeAccent).Bold(true).Render(title)
if i == 0 {
header = label
} else {
result = append(result, "", label)
rowHeaders = append(rowHeaders, label, label)
}
for i := range columns {
columns[i] = fitBlock(strings.Split(columns[i], "\n"), columnWidth, height)
if field.title == "CONFIGURATION" && collapsedConfig {
continue
}
joined := columns[0]
divider := strings.TrimSuffix(strings.Repeat(separator+"\n", height), "\n")
for _, column := range columns[1:] {
joined = lipgloss.JoinHorizontal(lipgloss.Top, joined, divider, column)
}
joinedRows := strings.Split(joined, "\n")
result = append(result, joinedRows...)
for range joinedRows {
for _, line := range strings.Split(ansi.Wrap(field.text, max(1, width), ""), "\n") {
result = append(result, line)
rowHeaders = append(rowHeaders, label)
}
}
@@ -427,6 +400,22 @@ func (m Model) stagePanel(width, height int) string {
if width <= 0 || height <= 0 {
return ""
}
if width < 80 {
inner := max(1, width-4)
heading, lines, labels := m.stageColumnsWithHeaders(inner)
page := max(0, height-4)
top := max(0, min(m.stageTop, max(0, len(lines)-page)))
if top < len(labels) {
heading = labels[top]
}
rows := []string{runPaneTitle("Stages", "", width, m.stageFocus), m.stageTabs(width), heading}
rows = append(rows, lines[top:min(len(lines), top+page)]...)
for len(rows) < height-1 {
rows = append(rows, "")
}
rows = append(rows, bar("c configuration", fmt.Sprintf("%d–%d / %d", top+1, min(top+page, len(lines)), len(lines)), width, false))
return fitBlock(rows, width, height)
}
inner := max(1, width-4)
rows := max(0, height-6)
columns, lines, rowHeaders := m.stageColumnsWithHeaders(inner)
@@ -439,7 +428,7 @@ func (m Model) stagePanel(width, height int) string {
label = "▸ " + label
}
headers := []string{runPaneTitle(strings.TrimPrefix(label, "▸ "), fmt.Sprintf("%d / %d · rows %d–%d/%d", m.stageIndex+1, len(m.detail.Graph.Stages), min(top+1, len(lines)), min(len(lines), top+rows), len(lines)), inner, m.stageFocus), m.stageTabs(inner), columns}
return panel(width, height, headers, lines[top:min(len(lines), top+rows)], "n/p stage · Tab pane · j/k scroll · PgUp/Dn page", m.stageFocus)
return panel(width, height, headers, lines[top:min(len(lines), top+rows)], "c configuration · stage definition, not a run result", m.stageFocus)
}
func (m *Model) resetPipelineView() {
@@ -492,7 +481,11 @@ func (m *Model) clampPipelineScroll() {
m.stageIndex = max(0, min(m.stageIndex, max(0, len(m.detail.Graph.Stages)-1)))
g := m.pipelineGeometry(max(0, m.height-4))
m.pipelineTop = max(0, min(m.pipelineTop, max(0, len(m.graphLines())-max(1, g.graphHeight-5))))
m.stageTop = max(0, min(m.stageTop, max(0, len(m.stageLines(max(1, g.stageWidth-4)))-max(1, g.stageHeight-6))))
stagePage := g.stageHeight - 6
if g.stageWidth < 80 {
stagePage = g.stageHeight - 4
}
m.stageTop = max(0, min(m.stageTop, max(0, len(m.stageLines(max(1, g.stageWidth-4)))-max(1, stagePage))))
width := 0
for _, line := range m.graphLines() {
width = max(width, lipgloss.Width(line))
+11 -5
View File
@@ -37,7 +37,7 @@ func TestTabbedPanesAndIndependentScrolling(t *testing.T) {
m := panelModel(t)
view := ansi.Strip(m.View())
t.Log("\n" + view)
for _, text := range []string{"Version 2 ▾", "Edit source", "LATEST", "Graph", "Stages", "Output for", "implementer", "OUTPUT", "PROMPT", "CONFIGURATION", "OUTCOMES"} {
for _, text := range []string{"Version 2 ▾", "Edit source", "LATEST", "Graph", "Stages", "implementer"} {
if !strings.Contains(view, text) {
t.Fatalf("missing %q", text)
}
@@ -66,8 +66,9 @@ func TestTabbedPanesAndIndependentScrolling(t *testing.T) {
t.Fatal("stage scrolling affected the graph")
}
m = press(m, "tab")
graphTop = m.pipelineTop
m = press(m, "j")
if m.stageFocus || m.stageTop != 1 || m.pipelineTop != graphTop+1 {
if m.stageFocus || m.stageTop != 1 || m.pipelineTop < graphTop || m.pipelineTop > graphTop+1 {
t.Fatal("graph scrolling affected stage details")
}
m = press(m, "1")
@@ -152,7 +153,7 @@ func TestStageCapabilitiesAndScrolledHeadings(t *testing.T) {
m := panelModel(t)
m.detail.Graph.Stages[0].Notify = &protocol.NotificationPolicy{On: []string{"failure"}, Destination: "system"}
_, narrow, _ := m.stageColumnsWithHeaders(76)
first := strings.Join(narrow[:min(8, len(narrow))], "\n")
first := strings.Join(narrow[:min(16, len(narrow))], "\n")
if !strings.Contains(first, "TOOLS") || !strings.Contains(first, "NOTIFY") {
t.Fatal("capabilities hidden below long prompt", first)
}
@@ -160,10 +161,15 @@ func TestStageCapabilitiesAndScrolledHeadings(t *testing.T) {
if len(rows) != len(labels) {
t.Fatal("missing row heading context")
}
if labels[0] != header || !strings.Contains(labels[len(labels)-1], "NOTIFY") {
if labels[0] != header || !strings.Contains(labels[len(labels)-1], "CONFIGURATION") {
t.Fatal("field-group context did not follow scroll")
}
m.stageTop = len(rows) - 3
for i, label := range labels {
if strings.Contains(label, "NOTIFY") {
m.stageTop = i
break
}
}
view := ansi.Strip(m.stagePanel(120, 9))
if !strings.Contains(view, "NOTIFY") || strings.Contains(view, "CONFIGURATION") {
t.Fatal("pinned columns do not match scrolled group", view)
+67 -6
View File
@@ -68,7 +68,7 @@ func (m Model) updateSearch(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
func (m Model) searchView(height int) string {
field := m.commandInput
field.Width = max(1, min(54, m.width-10))
lines := []string{"Omnisearch · pipelines", field.View(), ""}
lines := []string{"Search pipelines", field.View(), ""}
items := m.searchMatches()
if len(items) == 0 {
lines = append(lines, "No matching pipelines")
@@ -205,6 +205,21 @@ func (m Model) updatePipeline(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
return m.openVersions()
case "r":
return m.openRuns()
case "c", "enter":
if m.stageFocus {
m.stageConfigExpanded = !m.stageConfigExpanded
if m.stageConfigExpanded {
_, _, labels := m.stageColumnsWithHeaders(max(1, m.width-4))
for i, label := range labels {
if strings.Contains(label, "CONFIGURATION") {
m.stageTop = i
break
}
}
}
} else {
m.revealStage()
}
case "e":
return m.editPipeline()
case "s":
@@ -240,6 +255,9 @@ func (m Model) updatePipeline(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
}
case "tab", "shift+tab":
m.stageFocus = !m.stageFocus
if !m.stageFocus {
m.revealStage()
}
case "1", "2", "3", "4", "5", "6", "7", "8", "9":
if m.detail != nil && len(m.detail.Graph.Stages) > 0 {
index := int(msg.String()[0] - '1')
@@ -278,6 +296,7 @@ func (m Model) updateConfirm(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
m.confirmOpen = false
m.keys.confirm = false
m.draftNameInput = newInput()
m.templateConfirm = false
return m, nil
}
if m.submitID != "" {
@@ -288,6 +307,31 @@ func (m Model) updateConfirm(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
m.keys.confirm = false
return m, nil
}
if m.templateConfirm {
if msg.Type != tea.KeyEnter && msg.String() != "ctrl+s" {
var cmd tea.Cmd
m.draftNameInput, cmd = m.draftNameInput.Update(msg)
return m, cmd
}
name := strings.TrimSpace(m.draftNameInput.Value())
if name == "" || len(name) > 200 || strings.ContainsAny(name, "\r\n\x00") {
m.submitNotice = "Name must be 1–200 bytes without line breaks or NUL."
return m, nil
}
if m.pendingDraft.path == "" {
d, err := draft.Create(name, m.pendingDraft.source, m.url, true, 0)
if err != nil {
m.submitNotice = "Could not retain draft: " + err.Error()
return m, nil
}
m.pendingDraft.path = d.Path
} else if err := draft.SetName(m.pendingDraft.path, name); err != nil {
m.submitNotice = "Could not save draft name: " + err.Error()
return m, nil
}
m.pendingDraft.name = name
msg = tea.KeyMsg{Type: tea.KeyEnter}
}
if strings.TrimSpace(m.pendingDraft.name) == "" {
if m.draftNameInput.Prompt != "Name: " {
m.draftNameInput = newInput()
@@ -342,14 +386,30 @@ func (m Model) updateConfirm(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
}
m.nextID++
m.submitID = strconv.FormatUint(m.nextID, 10)
m.submitNotice = "Submitting…"
m.appendLine("Submitting " + m.pendingDraft.name + "…")
m.submitNotice = "Updating pipeline…"
if m.pendingDraft.createOnly || m.pendingDraft.baseVersion == 0 {
m.submitNotice = "Creating pipeline…"
}
m.appendLine(m.submitNotice + " " + m.pendingDraft.name)
return m, m.send(protocol.Message{Type: protocol.Submit, ID: m.submitID, Name: m.pendingDraft.name, Source: m.pendingDraft.source, CreateOnly: m.pendingDraft.createOnly, ExpectedVersion: m.pendingDraft.baseVersion})
}
return m, nil
}
func (m Model) confirmView(height int) string {
if m.templateConfirm {
field := m.draftNameInput
field.Width = max(1, min(60, m.width-12))
cancelHint := "Esc back"
if m.pendingDraft.path != "" {
cancelHint = "Esc keep draft"
}
lines := []string{"Create pipeline", field.View(), "Uses this template without opening an editor.", "Creates a new pipeline; existing pipelines are never replaced.", "Destination: " + m.url, m.submitNotice, "Enter create pipeline · " + cancelHint}
if strings.Contains(m.pendingDraft.source, "```schedule") {
lines = append(lines, "WARNING: creation activates the included schedule.")
}
return popup(m.width, height, 90, lines)
}
if strings.TrimSpace(m.pendingDraft.name) == "" {
field := m.draftNameInput
if field.Prompt != "Name: " {
@@ -365,10 +425,11 @@ func (m Model) confirmView(height int) string {
}
return popup(m.width, height, 76, []string{"Name this pipeline", "", field.View(), m.submitNotice, hint})
}
lines := []string{"Submit edited pipeline", m.pendingDraft.name, "", "Creates a new immutable version.", "s submit · e edit again · Esc keep draft"}
if m.pendingDraft.createOnly {
lines := []string{"Update pipeline", m.pendingDraft.name, "", "Creates a new immutable version; previous versions are retained.", "s update pipeline · e edit again · Esc keep draft"}
if m.pendingDraft.createOnly || m.pendingDraft.baseVersion == 0 {
lines[0] = "Create pipeline"
lines[3] = "Creates a NEW pipeline only when you submit."
lines[3] = "Creates a new pipeline after confirmation."
lines[4] = "s create pipeline · e edit again · Esc keep draft"
}
lines = append(lines, "Destination: "+m.url)
if strings.Contains(m.pendingDraft.source, "```schedule") {
+19 -8
View File
@@ -2,9 +2,10 @@ package tui
import (
"fmt"
"strings"
"maps"
"git.a-wan.net/alan/pipelines/internal/protocol"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
)
@@ -115,17 +116,27 @@ func completedWorkLines(r *protocol.RunDetail) []string {
return append([]string{"Completed stage outputs (reported, not independently verified):"}, lines...)
}
func resultOutputLines(r *protocol.RunDetail) []string {
if len(r.Output) > 0 {
return valueLines(r.Output)
func runOutputDocument(r *protocol.RunDetail, width int) []string {
var notice []string
if r.Diagnostic != "" {
notice = append(notice, lipgloss.NewStyle().Foreground(themeError).Render("Stopped: "+ansi.Strip(r.Diagnostic)), "")
}
if r.Status == "succeeded" {
if len(r.Output) == 0 {
return []string{"Finished · no result recorded"}
}
return resultDocument(r.Output, width)
}
for i := len(r.Steps) - 1; i >= 0; i-- {
if r.Steps[i].Status == "completed" && len(r.Steps[i].Output) > 0 {
return append([]string{"Partial output · " + r.Steps[i].Stage + " (not a final result)", ""}, valueLines(r.Steps[i].Output)...)
notice = append(notice, lipgloss.NewStyle().Foreground(themeMuted).Render("Partial result · "+r.Steps[i].Stage+" · final result not available"), "")
return append(notice, resultDocument(r.Steps[i].Output, width)...)
}
}
if strings.TrimSpace(r.Diagnostic) != "" {
return []string{r.Diagnostic}
if len(r.Output) > 0 {
values := maps.Clone(r.Output)
delete(values, "input")
return append(notice, resultDocument(values, width)...)
}
return []string{"No output recorded yet."}
return append(notice, "No output recorded yet.")
}
+3 -2
View File
@@ -50,7 +50,7 @@ func TestRunLeadsWithResultAndPreservesPartialAccomplishments(t *testing.T) {
}}
m.runDetail = r
view := ansi.Strip(m.runsView(44))
for _, want := range []string{"Stopped: Verification timed out", "Latest completed output (implement): Updated the layout", "Partial output", "screen.go"} {
for _, want := range []string{"Stopped: Verification timed out", "Updated the layout", "Partial result", "screen.go"} {
if !strings.Contains(view, want) {
t.Fatal("partial result hidden", want, view)
}
@@ -58,6 +58,7 @@ func TestRunLeadsWithResultAndPreservesPartialAccomplishments(t *testing.T) {
if strings.Index(view, "Updated the layout") > strings.Index(view, "Run graph") {
t.Fatal("graph precedes result")
}
m.toggleRunSection(0)
lines := ansi.Strip(strings.Join(m.runSectionLines(100), "\n"))
if !strings.Contains(lines, "1. implement · success — Updated the layout") || strings.Index(lines, "[o]") > strings.Index(lines, "[i]") {
t.Fatal("recorded accomplishments hidden behind inputs", lines)
@@ -65,7 +66,7 @@ func TestRunLeadsWithResultAndPreservesPartialAccomplishments(t *testing.T) {
r.Status = "succeeded"
r.Diagnostic = ""
r.Output = map[string]any{"summary": "Layout verified", "report": "Checks passed", "artifacts": []string{"screen.go"}}
if lines = ansi.Strip(strings.Join(m.runSectionLines(100), "\n")); !strings.Contains(lines, "Result: Layout verified") {
if lines = ansi.Strip(strings.Join(m.runSectionLines(100), "\n")); !strings.Contains(lines, "Layout verified") {
t.Fatal("final result not prominent", lines)
}
r.Output = nil
+73 -70
View File
@@ -156,7 +156,7 @@ func (m Model) runSectionClosed(index int) bool {
if closed, ok := m.runCollapsed[m.runSectionKey(index)]; ok {
return closed
}
return index == 1 || index >= 3
return index != 2 && index != 5
}
func (m *Model) toggleRunSection(index int) {
@@ -168,25 +168,13 @@ func (m *Model) toggleRunSection(index int) {
m.runCollapsed[m.runSectionKey(index)] = !closed
}
func (m Model) runSidebarWidth() int {
if m.width < 64 {
return 0
}
if !m.runDetailFocus && !m.runGraphFocus {
return min(m.width-28, max(22, m.width*3/5))
}
return min(30, max(22, m.width/4))
}
func (m Model) runDetailWidth() int {
if sidebar := m.runSidebarWidth(); sidebar > 0 {
return max(1, m.width-sidebar-5)
}
return max(1, m.width-4)
}
func (m Model) runPageSize() int {
extra := 10
if m.runSidebarWidth() == 0 {
extra = 11
extra := 11
if m.width < 80 {
extra = 7
}
if m.runDetail != nil && m.height-4 >= 14 {
graphHeight, _ := m.runPaneHeights(m.height - 4)
@@ -412,9 +400,9 @@ func (m Model) runSectionLines(width int) []string {
return nil
}
r := m.runDetail
titles := []string{"Summary", "Input", "Output", "Tool evidence", "Metadata"}
shortcuts := []string{"s", "i", "o", "t", "m"}
summary := append([]string{"Status: " + m.progress(r.Status)}, runResultLines(r)...)
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)
}
@@ -422,22 +410,52 @@ func (m Model) runSectionLines(width int) []string {
if len(r.WritePaths) > 0 {
editScope = strings.Join(r.WritePaths, ", ")
}
output := resultOutputLines(r)
output = append(output, "", strings.Join(completedWorkLines(r), "\n"))
content := [][]string{summary, valueLines(r.Input), output, {"Select a stage to inspect its tool calls."}, {"Started: " + dateLabel(r.CreatedAt), "Finished: " + dateLabel(r.FinishedAt), "Duration: " + runDuration(r.CreatedAt, r.FinishedAt), "Workspace: " + r.Workspace, "Source hash: " + r.ContentHash, fmt.Sprintf("Shell/edit enabled: %t", r.AllowTools), "Stage tools: defined by the pinned pipeline version", "Edit scope: " + editScope}}
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]
summary = []string{"Status: " + m.progress(m.stepProgressStatus(step)), "Route: " + outcomeLabel(step.Outcome, step.Outcome) + " → " + step.Target}
if preview := protocol.OutputPreview(step.Output); preview != "" {
summary = append(summary, "Reported output: "+ansi.Strip(preview))
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 != "" {
summary = append(summary, lipgloss.NewStyle().Foreground(themeError).Render(step.Diagnostic))
stageOutput = append([]string{lipgloss.NewStyle().Foreground(themeError).Render("Stopped: " + step.Diagnostic), ""}, stageOutput...)
}
content = [][]string{summary, valueLines(step.Input), valueLines(step.Output), evidenceLines(step), {"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("Attempt sequence: %d", step.Sequence)}}
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("Recorded visit: %d", step.Sequence)}}
if !m.runSectionClosed(2) {
content[2] = append(content[2], "", fileChangesSummary(step))
}
var diff []string
if !m.runSectionClosed(5) {
diff = stageDiffLines(step)
}
content = append(content, diff)
for _, receipt := range step.Notifications {
line := "Notification: " + receipt.Destination + " · " + receipt.Status
if receipt.Filename != "" {
@@ -456,7 +474,7 @@ func (m Model) runSectionLines(width int) []string {
}
}
var lines []string
for _, i := range []int{0, 2, 1, 3, 4} {
for _, i := range []int{2, 5, 0, 1, 3, 4} {
title := titles[i]
marker := "▾"
if m.runSectionClosed(i) {
@@ -472,7 +490,7 @@ func (m Model) runSectionLines(width int) []string {
}
lines = append(lines, "")
}
if m.runDetailFocus && !m.runGraphFocus {
if !m.runGraphFocus {
row, _ := runFocusedSection(lines, m.runTop)
lines[row] = runHighlight(lines[row], width)
}
@@ -481,7 +499,7 @@ func (m Model) runSectionLines(width int) []string {
// The section containing the top visible detail row is the scroll focus.
func runFocusedSection(lines []string, top int) (int, string) {
row, title := 0, "Summary"
row, title := 0, "Result"
for i, line := range lines {
plain := ansi.Strip(line)
if i > top {
@@ -547,6 +565,9 @@ func (m Model) runsDetailsView(height int) string {
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{}
@@ -586,56 +607,38 @@ func (m Model) runsDetailsView(height int) string {
if height <= 6 {
return fitBlock([]string{header, runHighlight(m.runSelectionLabel(), m.width), m.runActions() + " · Tab pane · Esc back"}, m.width, height)
}
innerHeight := height - 2
sidebar := m.runSidebarWidth()
rightWidth := m.width
var left string
if sidebar > 0 {
rightWidth = m.width - sidebar - 1
labels := []string{"Run overview"}
for _, step := range r.Steps {
status := m.progress(m.stepProgressStatus(step))
name := fmt.Sprintf("%d. %s", step.Sequence, step.Stage)
budget := max(1, sidebar-6-ansi.StringWidth(status)-3)
labels = append(labels, ansi.Truncate(name, budget, "…")+" · "+status)
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, "")
}
start, end := selectionWindow(len(labels), m.runStepIndex, max(1, innerHeight-4))
var body []string
for i := start; i < end; i++ {
prefix := " "
if i == m.runStepIndex {
prefix = "▸ "
}
text := ansi.Truncate(prefix+labels[i], sidebar-4, "…")
if i == m.runStepIndex {
text = runHighlight(text, sidebar-4)
}
body = append(body, text)
continuation := "Details"
if top+page < len(lines) {
continuation = "↓ More result"
}
label := "Stages"
focused := !m.runDetailFocus && !m.runGraphFocus
left = panel(sidebar, innerHeight, []string{runPaneTitle(label, fmt.Sprint(len(r.Steps)), sidebar-4, focused)}, body, "n/p stage · 0 overview", focused)
} else {
innerHeight--
header += "\n" + runHighlight(m.runSelectionLabel()+" · n/p stage · Tab pane", m.width)
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))
}
lines := m.runSectionLines(max(1, rightWidth-4))
page := max(0, innerHeight-4)
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 := fmt.Sprintf("%d–%d / %d · s/i/o/t/m sections · %s · PgUp/Dn · Esc back", min(top+1, len(lines)), min(top+page, len(lines)), len(lines), m.runActions())
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) {
label = fmt.Sprintf("Details · %s · step %d", r.Steps[m.runStepIndex-1].Stage, r.Steps[m.runStepIndex-1].Sequence)
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.runDetailFocus && !m.runGraphFocus
focused := !m.runGraphFocus
if focused {
_, section := runFocusedSection(lines, top)
label += " · " + section
}
right := panel(rightWidth, innerHeight, []string{runPaneTitle(label, "", max(1, rightWidth-4), focused)}, lines[top:min(len(lines), top+page)], footer, focused)
body := right
if sidebar > 0 {
body = lipgloss.JoinHorizontal(lipgloss.Top, left, " ", right)
}
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)
}
+190
View File
@@ -0,0 +1,190 @@
package tui
import (
"encoding/json"
"fmt"
"reflect"
"sort"
"strings"
"github.com/charmbracelet/glamour"
glamansi "github.com/charmbracelet/glamour/ansi"
"github.com/charmbracelet/glamour/styles"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
)
func documentKeys(values map[string]any) []string {
keys := make([]string, 0, len(values))
for key := range values {
keys = append(keys, key)
}
priority := map[string]int{"summary": 0, "result": 1, "report": 2, "diagnosis": 3, "accomplished": 4, "changes": 5, "artifacts": 6, "findings": 7, "evidence": 8, "acceptance_checks": 9, "reason": 10, "error": 11}
sort.Slice(keys, func(i, j int) bool {
a, ok := priority[keys[i]]
if !ok {
a = 20
}
b, ok := priority[keys[j]]
if !ok {
b = 20
}
if a != b {
return a < b
}
return keys[i] < keys[j]
})
return keys
}
func fieldLabel(key string) string {
label := strings.ReplaceAll(strings.ReplaceAll(key, "_", " "), "-", " ")
if label == "" {
return "Value"
}
runes := []rune(label)
runes[0] = []rune(strings.ToUpper(string(runes[0])))[0]
return string(runes)
}
// Use the terminal's inherited palette rather than a fixed dark Markdown theme.
// Rendering changes presentation only: the original output remains in the audit.
func resultMarkdown(text string, width int) []string {
text = ansi.Strip(text)
if len(text) > 64<<10 || !strings.ContainsAny(text, "#*_`[|>") {
return strings.Split(text, "\n")
}
style := styles.ASCIIStyleConfig
zero := uint(0)
bold, italic := true, true
style.Document.Margin = &zero
style.Document.BlockPrefix = ""
style.Document.BlockSuffix = ""
style.Heading.StylePrimitive = glamansi.StylePrimitive{Bold: &bold, BlockSuffix: "\n"}
for _, heading := range []*glamansi.StyleBlock{&style.H1, &style.H2, &style.H3, &style.H4, &style.H5, &style.H6} {
heading.Prefix = ""
heading.Suffix = ""
}
style.Strong = glamansi.StylePrimitive{Bold: &bold}
style.Emph = glamansi.StylePrimitive{Italic: &italic}
style.CodeBlock.Margin = &zero
renderer, err := glamour.NewTermRenderer(glamour.WithStyles(style), glamour.WithWordWrap(max(1, width)), glamour.WithPreservedNewLines())
if err != nil {
return strings.Split(text, "\n")
}
rendered, err := renderer.Render(text)
if err != nil {
return strings.Split(text, "\n")
}
return strings.Split(strings.Trim(rendered, "\n"), "\n")
}
func resultDocument(values map[string]any, width int) []string {
if len(values) == 0 {
return []string{"No output recorded yet."}
}
var lines []string
var render func(any, int)
render = func(value any, depth int) {
indent := strings.Repeat(" ", min(depth, 8))
if depth > 8 {
data, _ := json.Marshal(value)
lines = append(lines, indent+string(data))
return
}
switch value := value.(type) {
case string:
for _, line := range resultMarkdown(value, max(1, width-len(indent))) {
lines = append(lines, indent+line)
}
case map[string]any:
if len(value) == 0 {
lines = append(lines, indent+"(empty)")
return
}
for _, key := range documentKeys(value) {
label := lipgloss.NewStyle().Foreground(themeMuted).Bold(true).Render(fieldLabel(key))
lines = append(lines, indent+label)
render(value[key], depth+1)
lines = append(lines, "")
}
case nil:
lines = append(lines, indent+"(none)")
default:
rv := reflect.ValueOf(value)
if rv.Kind() == reflect.Slice || rv.Kind() == reflect.Array {
if rv.Len() == 0 {
lines = append(lines, indent+"(empty list)")
return
}
for i := 0; i < rv.Len(); i++ {
start := len(lines)
render(rv.Index(i).Interface(), depth+1)
if len(lines) > start {
lines[start] = indent + "• " + strings.TrimLeft(lines[start], " ")
}
}
} else {
lines = append(lines, indent+fmt.Sprint(value))
}
}
}
for i, key := range documentKeys(values) {
if i > 0 {
lines = append(lines, "")
}
if !(i == 0 && (key == "summary" || key == "result" || key == "report")) {
lines = append(lines, lipgloss.NewStyle().Foreground(themeMuted).Bold(true).Render(fieldLabel(key)))
}
render(values[key], 0)
}
return lines
}
func (m Model) runVisitTabs(width int) string {
if m.runDetail == nil {
return ""
}
labels := []string{"Overview"}
for _, step := range m.runDetail.Steps {
marker := strings.Fields(ansi.Strip(m.progress(m.stepProgressStatus(step))))
status := ""
if len(marker) > 0 {
status = " " + marker[0]
}
labels = append(labels, fmt.Sprintf("%d %s%s", step.Sequence, step.Stage, status))
}
index := max(0, min(m.runStepIndex, len(labels)-1))
selected := action(ansi.Truncate(labels[index], max(1, width-6), "…"), true)
left, right := index, index
text := selected
for {
changed := false
if left > 0 {
prior := action(labels[left-1], false) + " "
if ansi.StringWidth(prior+text)+4 <= width {
text = prior + text
left--
changed = true
}
}
if right+1 < len(labels) {
next := " " + action(labels[right+1], false)
if ansi.StringWidth(text+next)+4 <= width {
text += next
right++
changed = true
}
}
if !changed {
break
}
}
if left > 0 {
text = "‹ " + text
}
if right+1 < len(labels) {
text += " ›"
}
return ansi.Truncate(text, max(1, width), "…")
}
+7 -8
View File
@@ -10,7 +10,7 @@ import (
)
func TestRunNextPreviousNavigatesExecutionVisitsFromEveryPane(t *testing.T) {
for _, pane := range []string{"stages", "details", "graph"} {
for _, pane := range []string{"details", "graph"} {
t.Run(pane, func(t *testing.T) {
m := runInspectionModel()
m.width = 100
@@ -54,28 +54,27 @@ func TestRunFocusHighlightsSelectionPaneAndVisibleSection(t *testing.T) {
m.width = 120
m = runKey(m, "n")
view := m.runsDetailsView(30)
if !strings.Contains(ansi.Strip(view), "▸ Stages") || !strings.Contains(view, "48;") {
t.Fatal("stage pane/selection lacks background highlight")
if !strings.Contains(ansi.Strip(view), "▸ Details") || strings.Contains(ansi.Strip(view), "▸ Stages") || !strings.Contains(view, "48;") {
t.Fatal("details/visit selection lacks background highlight")
}
m = runKey(m, "tab")
lines := m.runSectionLines(80)
row, title := runFocusedSection(lines, 0)
if title != "Summary" || !strings.Contains(lines[row], "48;") {
if title != "Result" || !strings.Contains(lines[row], "48;") {
t.Fatal("focused section not highlighted", lines[row])
}
for i, line := range lines {
if strings.HasPrefix(ansi.Strip(line), "[o]") {
if strings.HasPrefix(ansi.Strip(line), "[s]") {
m.runTop = i
break
}
}
lines = m.runSectionLines(80)
row, title = runFocusedSection(lines, m.runTop)
if title != "Output" || !strings.Contains(lines[row], "48;") {
if title != "Stage progress" || !strings.Contains(lines[row], "48;") {
t.Fatal("scroll focus did not follow section", title)
}
view = ansi.Strip(m.runsDetailsView(30))
if !strings.Contains(view, "▸ Details") || !strings.Contains(view, "· Output") || strings.Contains(view, "▸ Stages") {
if !strings.Contains(view, "▸ Details") || !strings.Contains(view, "· Result") || strings.Contains(view, "▸ Stages") {
t.Fatal("focused pane ambiguous", view)
}
m = runKey(m, "g")
+33 -14
View File
@@ -87,7 +87,7 @@ func (m Model) runGraphState() (protocol.Graph, string, *graphAppearance) {
}
func (m Model) runsView(height int) string {
if m.runDetail == nil || height < 14 {
if m.runDetail == nil {
return m.runsDetailsView(height)
}
graphHeight, detailHeight := m.runPaneHeights(height)
@@ -95,20 +95,42 @@ func (m Model) runsView(height int) string {
if !m.runGraphFocus {
top, pan = m.runGraphFollow()
}
graph := m.runGraphPanel(graphHeight, top, pan)
graph := ""
if graphHeight > 0 {
if graphHeight <= 2 {
graph = fitBlock([]string{bar("Run graph", "Tab to expand", m.width, false)}, m.width, graphHeight)
} else {
graph = m.runGraphPanel(graphHeight, top, pan)
}
}
details := m.runsDetailsView(detailHeight)
return fitBlock(strings.Split(details+"\n"+graph, "\n"), m.width, height)
parts := []string{}
if detailHeight > 0 {
parts = append(parts, details)
}
if graphHeight > 0 {
parts = append(parts, graph)
}
return fitBlock(strings.Split(strings.Join(parts, "\n"), "\n"), m.width, height)
}
func (m Model) runPaneHeights(height int) (int, int) {
if height < 14 {
if m.runGraphFocus {
details := min(2, max(0, height-6))
return height - details, details
}
if height < 8 {
return 0, height
}
graphHeight := height / 4
if m.runGraphFocus {
graphHeight = height * 3 / 4
lines := m.runGraphLines(max(1, m.width-4))
widest := 0
for _, line := range lines {
widest = max(widest, ansi.StringWidth(line))
}
graphHeight := len(lines) + 5
if graphHeight > height-12 || widest > max(1, m.width-4) {
graphHeight = 2
}
graphHeight = max(6, min(height-8, graphHeight))
return graphHeight, height - graphHeight
}
@@ -121,13 +143,10 @@ func (m Model) runGraphTitle() string {
if r.FinishedAt != "" {
durationLabel = "duration"
}
title := "Run graph · " + durationLabel + " " + runDuration(r.CreatedAt, r.FinishedAt) + " · started " + dateLabel(r.CreatedAt)
title := fmt.Sprintf("Run graph · %d recorded visits · %s %s", len(r.Steps), durationLabel, runDuration(r.CreatedAt, r.FinishedAt))
if m.runGraphFocus {
title = "▸ " + title
}
if r.FinishedAt != "" {
title += " · finished " + dateLabel(r.FinishedAt)
}
return title
}
@@ -162,9 +181,9 @@ func (m Model) runGraphPanel(height, top, pan int) string {
body = append(body, strings.Repeat(" ", leftPad)+ansi.Cut(line, pan, pan+width-leftPad))
}
label := m.runGraphTitle()
footer := "Tab pane · n/p stage · dim = not executed"
footer := "Dimmed stages and routes were not executed."
if widest > width || len(lines) > rows {
footer = "h/j/k/l pan · c center · Tab pane · n/p stage"
footer = "h/j/k/l pan · c center · dim = not executed"
}
header := runPaneTitle(strings.TrimPrefix(label, "▸ "), "", width, m.runGraphFocus)
return panel(m.width, height, []string{header, ""}, body, footer, m.runGraphFocus)
+2 -6
View File
@@ -80,10 +80,6 @@ func TestRunTabCycleAndGraphPanning(t *testing.T) {
m.runDetail.Graph.Stages = append(m.runDetail.Graph.Stages, protocol.Stage{Key: fmt.Sprintf("node_%02d", i), Edges: map[string]string{"success": protocol.SuccessEnd}})
}
m = runKey(m, "tab")
if !m.runDetailFocus || m.runGraphFocus {
t.Fatal("Tab did not focus details")
}
m = runKey(m, "tab")
if !m.runGraphFocus || m.runDetailFocus {
t.Fatal("Tab did not focus graph")
}
@@ -101,8 +97,8 @@ func TestRunTabCycleAndGraphPanning(t *testing.T) {
t.Fatal("h/k did not pan back")
}
m = runKey(m, "tab")
if m.runGraphFocus || m.runDetailFocus {
t.Fatal("Tab did not return to stages")
if m.runGraphFocus || !m.runDetailFocus {
t.Fatal("Tab did not return directly to details")
}
m = runKey(m, "shift+tab")
if !m.runGraphFocus {
+1 -1
View File
@@ -182,7 +182,7 @@ func TestRunningDurationAndOpenCodeEvidenceShortcut(t *testing.T) {
graphModel := New(context.Background(), "")
graphModel.runDetail = &protocol.RunDetail{RunSummary: protocol.RunSummary{CreatedAt: "2026-10-09T00:00:00Z", FinishedAt: "2026-10-09T00:01:02Z"}}
title := graphModel.runGraphTitle()
for _, field := range []string{"duration 1m2s", "started ", "finished "} {
for _, field := range []string{"duration 1m2s", "recorded visits"} {
if !strings.Contains(title, field) {
t.Fatal("graph title omitted run timing", title)
}
+5 -10
View File
@@ -29,13 +29,8 @@ func TestRunPanesExpandWithTabFocus(t *testing.T) {
graphPage := m.runPageSize()
m = runKey(m, "tab")
graph, details = m.runPaneHeights(44)
stageWidth := m.runSidebarWidth()
if m.runGraphFocus || m.runDetailFocus || details <= graph || stageWidth <= m.width/2 || m.runPageSize() <= graphPage {
t.Fatal("stage focus did not expand", graph, details, stageWidth)
}
m = runKey(m, "tab")
if !m.runDetailFocus || m.runSidebarWidth() >= stageWidth || m.width-m.runSidebarWidth() <= m.width/2 {
t.Fatal("details focus did not expand detail pane")
if m.runGraphFocus || !m.runDetailFocus || details <= graph || m.runDetailWidth() != m.width-4 || m.runPageSize() <= graphPage {
t.Fatal("details did not expand directly to full width", graph, details)
}
updated, _ = m.Update(receivedMsg(protocol.Message{Type: protocol.Run, RunDetail: run}))
m = updated.(Model)
@@ -48,10 +43,10 @@ func TestRunPanesExpandWithTabFocus(t *testing.T) {
t.Fatal("graph did not expand again")
}
for _, height := range []int{14, 18, 24, 44, 80} {
for _, pane := range []int{0, 1, 2} {
m.runDetailFocus, m.runGraphFocus = pane == 1, pane == 2
for _, graphFocus := range []bool{false, true} {
m.runDetailFocus, m.runGraphFocus = !graphFocus, graphFocus
graph, details = m.runPaneHeights(height)
if graph+details != height || graph < 6 || details < 8 {
if graph+details != height || graph < 2 || details < 2 {
t.Fatal("pane sizes exceed available height", height, graph, details)
}
view := m.runsView(height)
+1 -1
View File
@@ -25,7 +25,7 @@ func TestRunStageProgressAnimatesAndStops(t *testing.T) {
if cmd == nil || before == after {
t.Fatal("running stage spinner did not animate")
}
if !strings.Contains(after, "✓ done") || !strings.Contains(after, "running") {
if !strings.Contains(after, "✓") || !strings.Contains(after, "running") {
t.Fatal("stage progress missing", after)
}
for _, test := range []struct{ status, outcome, target, want string }{
+67 -40
View File
@@ -9,6 +9,7 @@ import (
"git.a-wan.net/alan/pipelines/internal/protocol"
"github.com/charmbracelet/bubbles/textarea"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/x/ansi"
)
type runTick struct{}
@@ -39,6 +40,7 @@ func (m Model) sendRunRequest(request protocol.Message) (tea.Model, tea.Cmd) {
if request.Type == protocol.RunPipeline || request.Type == protocol.RetryRun || request.Type == protocol.CancelRun {
if !m.actionApproved {
m.actionConfirm = &request
m.actionConfirmTop = 0
return m, nil
}
m.actionApproved = false
@@ -47,6 +49,9 @@ func (m Model) sendRunRequest(request protocol.Message) (tea.Model, tea.Cmd) {
m.appendLine("not connected")
return m, nil
}
if request.Type == protocol.GetRun {
m.runError = ""
}
m.nextID++
request.ID = fmt.Sprintf("run-%d", m.nextID)
if request.Type == protocol.GetRun && m.requestedRunID != request.RunID {
@@ -170,26 +175,47 @@ func (m Model) runHasMutationTools() bool {
}
func (m Model) runFormView(height int) string {
lines := []string{"Run: task", "Repository: " + m.runWorkspace, "Enter newline · Ctrl+S run · Esc cancel"}
lines = append(lines, strings.Split(m.runPrompt.View(), "\n")...)
title := "Run pipeline"
if m.detail != nil {
for _, s := range m.detail.Graph.Stages {
if s.Type == "ntfy" {
lines = append(lines, s.Key+" action: publish Markdown to ntfy destination "+s.Configs["destination"])
continue
title = fmt.Sprintf("Run %s · v%d", m.detail.Name, m.detail.Version)
}
field := m.runPrompt
field.SetWidth(max(1, m.width-6))
field.SetHeight(max(1, height-6))
headers := []string{bar(title, "", max(1, m.width-4), true), ansi.Truncate("Repository: "+m.runWorkspace, max(1, m.width-4), "…")}
return panel(m.width, height, headers, strings.Split(field.View(), "\n"), m.runScopeLabel(), true)
}
func (m Model) runScopeLabel() string {
if m.detail == nil {
return "Scope: defined by the selected pipeline"
}
var tools, notifications []string
seen := map[string]bool{}
for _, s := range m.detail.Graph.Stages {
if s.Type == "ntfy" {
notifications = append(notifications, "publish Markdown to ntfy destination "+s.Configs["destination"])
continue
}
declared, explicit := s.Blocks["tools"]
if !explicit {
declared = "read glob grep edit shell"
}
for _, tool := range strings.Fields(declared) {
if !seen[tool] {
seen[tool] = true
tools = append(tools, tool)
}
tools, explicit := s.Blocks["tools"]
label := strings.Join(strings.Fields(tools), ", ")
if label == "" {
label = "none"
}
if !explicit {
label = "project read/edit and shell"
}
lines = append(lines, s.Key+" tools: "+label)
}
}
return popup(m.width, height, 100, lines)
label := "Stage tools: none"
if len(tools) > 0 {
label = "Stage tools: " + strings.Join(tools, ", ")
}
if len(notifications) > 0 {
label += " · " + strings.Join(notifications, "; ")
}
return label
}
func (m Model) updateRuns(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
@@ -237,19 +263,8 @@ func (m Model) updateRuns(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
return m, nil
}
if m.runDetail != nil && (msg.String() == "tab" || msg.String() == "shift+tab") {
pane := 0
if m.runDetailFocus {
pane = 1
}
if m.runGraphFocus {
pane = 2
}
if msg.String() == "tab" {
pane = (pane + 1) % 3
} else {
pane = (pane + 2) % 3
}
m.runDetailFocus, m.runGraphFocus = pane == 1, pane == 2
m.runGraphFocus = !m.runGraphFocus
m.runDetailFocus = !m.runGraphFocus
if m.runGraphFocus {
m.runGraphTop, m.runGraphPan = m.runGraphFollow()
}
@@ -258,6 +273,7 @@ func (m Model) updateRuns(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
runs := m.visibleRuns()
if msg.String() == "g" && m.runDetail != nil {
m.runGraphFocus = !m.runGraphFocus
m.runDetailFocus = !m.runGraphFocus
if m.runGraphFocus {
m.runGraphTop, m.runGraphPan = m.runGraphFollow()
}
@@ -320,16 +336,12 @@ func (m Model) updateRuns(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
case "j", "down":
if m.runDetail == nil {
m.runIndex = min(m.runIndex+1, max(0, len(runs)-1))
} else if !m.runDetailFocus {
m.selectRunStep(min(m.runStepIndex+1, len(m.runDetail.Steps)))
} else {
m.runTop++
}
case "k", "up":
if m.runDetail == nil {
m.runIndex = max(0, m.runIndex-1)
} else if !m.runDetailFocus {
m.selectRunStep(max(0, m.runStepIndex-1))
} else {
m.runTop = max(0, m.runTop-1)
}
@@ -341,9 +353,13 @@ func (m Model) updateRuns(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
m.runDetailFocus = true
}
case "h", "left":
m.runDetailFocus = false
if m.runDetail != nil {
m.selectRunStep(max(0, m.runStepIndex-1))
m.runDetailFocus = true
}
case "l", "right":
if m.runDetail != nil {
m.selectRunStep(min(len(m.runDetail.Steps), m.runStepIndex+1))
m.runDetailFocus = true
}
case "pgdown", "ctrl+d":
@@ -361,18 +377,14 @@ func (m Model) updateRuns(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
m.runIndex = max(0, m.runIndex-m.runPageSize())
}
case "home":
if m.runDetailFocus {
if m.runDetail != nil {
m.runTop = 0
} else if m.runDetail != nil {
m.selectRunStep(0)
} else {
m.runIndex = 0
}
case "end":
if m.runDetailFocus {
if m.runDetail != nil {
m.runTop = len(m.runSectionLines(m.runDetailWidth()))
} else if m.runDetail != nil {
m.selectRunStep(len(m.runDetail.Steps))
} else {
m.runIndex = max(0, len(runs)-1)
}
@@ -387,6 +399,21 @@ func (m Model) updateRuns(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
if m.runDetail != nil {
m.toggleRunSection(strings.Index("siotm", msg.String()))
}
case "d":
if m.runDetail != nil {
m.runGraphFocus = false
m.runDetailFocus = true
_, focused := runFocusedSection(m.runSectionLines(m.runDetailWidth()), m.runTop)
if m.runSectionClosed(5) || focused == "File changes" {
m.toggleRunSection(5)
}
for i, line := range m.runSectionLines(m.runDetailWidth()) {
if strings.HasPrefix(ansi.Strip(line), "[d]") {
m.runTop = i
break
}
}
}
case "x":
if m.runDetail != nil {
return m.runRequest(protocol.Message{Type: protocol.CancelRun, RunID: m.runDetail.ID})
+11 -13
View File
@@ -36,7 +36,7 @@ func TestRunFormAndInspection(t *testing.T) {
m.runStepIndex = 1
m.toggleRunSection(4)
text := strings.Join(m.runSectionLines(80), "\n")
for _, want := range []string{"Summary", "Output", "ses_audit", "error → #failure", "missing evidence"} {
for _, want := range []string{"Stage progress", "Result", "ses_audit", "error → #failure", "missing evidence"} {
if !strings.Contains(text, want) {
t.Fatal("missing audit detail", want)
}
@@ -49,6 +49,7 @@ func runInspectionModel() Model {
m.height = 28
m.runOpen = true
m.keys.runs = true
m.runDetailFocus = true
m.requestedRunID = 8
m.runDetail = &protocol.RunDetail{RunSummary: protocol.RunSummary{ID: 8, Name: "bug fix", Version: 4, Status: "running"}, Output: map[string]any{"summary": "Run summary"}, Steps: []protocol.RunStep{
{Sequence: 1, Stage: "implementer", Status: "completed", Outcome: "success", Target: "verifier", Input: map[string]any{"secret_test_marker": "hidden input"}, Output: map[string]any{"summary": "First attempt", "evidence": strings.Repeat("A long verification result with Unicode 宽. ", 100)}, SessionID: "ses_first"},
@@ -67,16 +68,16 @@ func runKey(m Model, key string) Model {
return updated.(Model)
}
func TestRunSidebarSectionsAndScrolling(t *testing.T) {
func TestRunVisitSelectorSectionsAndScrolling(t *testing.T) {
m := runInspectionModel()
m = runKey(m, "j")
m = runKey(m, "n")
if m.runStepIndex != 1 {
t.Fatal("sidebar did not select first attempt")
t.Fatal("visit selector did not select first attempt")
}
text := ansi.Strip(m.runsDetailsView(24))
for _, want := range []string{"Stages", "▸ 1.", "2.", "done", "running", "Details · implementer · step 1", "Summary", "Output", "First attempt"} {
for _, want := range []string{"1 implementer", "2 implementer", "done", "Details · implementer · step 1", "Result", "First attempt"} {
if !strings.Contains(text, want) {
t.Fatal("missing section/sidebar", want)
t.Fatal("missing section/visit", want)
}
}
if strings.Contains(text, "hidden input") || strings.Contains(text, "Second attempt") {
@@ -86,7 +87,6 @@ func TestRunSidebarSectionsAndScrolling(t *testing.T) {
if m.runSectionClosed(1) {
t.Fatal("input section did not expand")
}
m = runKey(m, "tab")
m = runKey(m, "pgdown")
if m.runTop != m.runPageSize() || !m.runDetailFocus {
t.Fatal("page scrolling failed")
@@ -100,12 +100,11 @@ func TestRunSidebarSectionsAndScrolling(t *testing.T) {
if m.runTop != 0 {
t.Fatal("Home did not reach top")
}
m = runKey(m, "h")
m = runKey(m, "j")
m = runKey(m, "n")
if m.runStepIndex != 2 || !m.runSectionClosed(1) {
t.Fatal("attempt state not independent")
}
m = runKey(m, "k")
m = runKey(m, "p")
if m.runSectionClosed(1) {
t.Fatal("expansion not retained when revisiting attempt")
}
@@ -113,8 +112,7 @@ func TestRunSidebarSectionsAndScrolling(t *testing.T) {
func TestRunPollingCannotReopenOrResetNavigation(t *testing.T) {
m := runInspectionModel()
m = runKey(m, "j")
m = runKey(m, "tab")
m = runKey(m, "n")
m = runKey(m, "pgdown")
top := m.runTop
refreshed := *m.runDetail
@@ -195,7 +193,7 @@ func TestRunSectionsOrderTitleAndNumberSelection(t *testing.T) {
m := runInspectionModel()
m = runKey(m, "1")
text := ansi.Strip(strings.Join(m.runSectionLines(70), "\n"))
if strings.Index(text, "Output") > strings.Index(text, "Input") {
if strings.Index(text, "Result") > strings.Index(text, "Task & input") {
t.Fatal("output must precede input")
}
if m.runSectionClosed(2) || !m.runSectionClosed(1) {
+29 -9
View File
@@ -6,6 +6,7 @@ import (
"git.a-wan.net/alan/pipelines/internal/statusview"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
"strings"
)
@@ -42,7 +43,7 @@ func (m Model) updateStatus(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
case "pgup":
m.statusTop -= max(1, m.height-10)
}
m.statusTop = max(0, min(m.statusTop, max(0, len(m.statusLines())-max(1, m.height-9))))
m.statusTop = max(0, min(m.statusTop, max(0, len(m.statusContent())-max(1, m.height-4))))
return m, nil
}
func (m Model) statusLines() []string {
@@ -62,7 +63,7 @@ func (m Model) statusLines() []string {
}
return lines
}
func (m Model) statusView(height int) string {
func (m Model) statusContent() []string {
server, ntfy := statusview.ServerLines(m.systemStatus), statusview.NtfyLines(m.systemStatus)
if m.systemStatus == nil && m.statusError != "" {
s := statusview.Offline(m.url)
@@ -75,14 +76,33 @@ func (m Model) statusView(height int) string {
server = append([]string{m.loading("Checking…")}, server...)
}
width := m.width
wrap := func(lines []string, w int) []string {
var rows []string
for _, line := range lines {
rows = append(rows, strings.Split(ansi.Wrap(line, max(1, w), ""), "\n")...)
}
return rows
}
if width >= 100 {
w := (width - 2) / 2
left := panel(w, max(4, height-2), []string{"Pipelines server"}, server, "", false)
right := panel(width-w-2, max(4, height-2), []string{"ntfy · phone connection"}, ntfy, "", false)
return fitBlock(append(strings.Split(lipgloss.JoinHorizontal(lipgloss.Top, left, " ", right), "\n"), "", "r refresh · Esc close"), width, height)
server, ntfy = wrap(server, w-4), wrap(ntfy, width-w-6)
cardHeight := max(len(server), len(ntfy)) + 4
left := panel(w, cardHeight, []string{"Pipelines server"}, server, "", false)
right := panel(width-w-2, cardHeight, []string{"ntfy · phone connection"}, ntfy, "", false)
return strings.Split(lipgloss.JoinHorizontal(lipgloss.Top, left, " ", right), "\n")
}
topHeight := max(4, (height-2)/2)
left := panel(width, topHeight, []string{"Pipelines server"}, server, "", false)
right := panel(width, max(4, height-topHeight-2), []string{"ntfy · phone connection"}, ntfy, "", false)
return fitBlock(append(strings.Split(left+"\n"+right, "\n"), "r refresh · Esc close"), width, height)
server, ntfy = wrap(server, width-4), wrap(ntfy, width-4)
left := panel(width, len(server)+4, []string{"Pipelines server"}, server, "", false)
right := panel(width, len(ntfy)+4, []string{"ntfy · phone connection"}, ntfy, "", false)
return strings.Split(left+"\n\n"+right, "\n")
}
func (m Model) statusView(height int) string {
lines := m.statusContent()
top := max(0, min(m.statusTop, max(0, len(lines)-height)))
visible := append([]string{}, lines[top:min(len(lines), top+height)]...)
if top+height < len(lines) && len(visible) > 0 {
visible[len(visible)-1] = bar("↓ More connection details", fmt.Sprintf("%d–%d / %d", top+1, top+height, len(lines)), m.width, false)
}
return fitBlock(visible, m.width, height)
}
+63 -11
View File
@@ -43,8 +43,8 @@ func TestTemplateSubmitNamesRetainsAndExplicitlyPublishesSelectedTemplate(t *tes
}
}
m.renderTemplate()
if !strings.Contains(m.templatesView(30), "Submit template") {
t.Fatal("missing visible submit button")
if !strings.Contains(m.templatesView(30), "Create pipeline") {
t.Fatal("missing visible create button")
}
stale, err := draft.Create("unrelated", "unrelated draft source", url, true, 0)
if err != nil {
@@ -53,8 +53,8 @@ func TestTemplateSubmitNamesRetainsAndExplicitlyPublishesSelectedTemplate(t *tes
m.pendingDraft = &editedMsg{name: stale.Name, source: "unrelated draft source", path: stale.Path, createOnly: true}
updated, cmd := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'s'}})
m = updated.(Model)
if cmd != nil || !m.confirmOpen || m.editorOpen || m.pendingDraft.name != "" || m.pendingDraft.path != "" || !m.pendingDraft.createOnly {
t.Fatal("Submit button did not open naming flow without launching an editor", m.pendingDraft)
if !m.confirmOpen || m.editorOpen || m.pendingDraft.name != m.templates[m.templateIndex].Name || m.draftNameInput.Value() != m.pendingDraft.name || m.pendingDraft.path != "" || !m.pendingDraft.createOnly {
t.Fatal("Create button did not open prefilled confirmation without an editor", m.pendingDraft)
}
expected := pipeline.WithDefaultModel(m.templates[m.templateIndex].Source, m.defaultModel)
if m.pendingDraft.source != expected {
@@ -68,13 +68,17 @@ func TestTemplateSubmitNamesRetainsAndExplicitlyPublishesSelectedTemplate(t *tes
}
updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyEnter})
m = updated.(Model)
updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyCtrlA})
m = updated.(Model)
updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyCtrlK})
m = updated.(Model)
updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("Simple summary")})
m = updated.(Model)
updated, cmd = m.Update(tea.KeyMsg{Type: tea.KeyEnter})
m = updated.(Model)
items, _ := store.List(ctx)
if cmd != nil || len(items) != 0 || !m.confirmOpen || m.pendingDraft.path == "" {
t.Fatal("naming published before confirmation or failed to retain draft")
if cmd == nil || len(items) != 0 || !m.confirmOpen || m.pendingDraft.path == "" {
t.Fatal("single create confirmation did not send or failed to retain draft")
}
retained, err := draft.Load(m.pendingDraft.path)
if err != nil || retained.Name != "Simple summary" || retained.Server != url || !retained.CreateOnly || retained.BaseVersion != 0 {
@@ -84,11 +88,6 @@ func TestTemplateSubmitNamesRetainsAndExplicitlyPublishesSelectedTemplate(t *tes
if err != nil || text != expected {
t.Fatal("template draft source lost", err)
}
updated, cmd = m.Update(tea.KeyMsg{Type: tea.KeyEnter})
m = updated.(Model)
if cmd == nil {
t.Fatal("publication confirmation did not send")
}
if _, ok := cmd().(sentMsg); !ok {
t.Fatal("publication send failed")
}
@@ -109,4 +108,57 @@ func TestTemplateSubmitNamesRetainsAndExplicitlyPublishesSelectedTemplate(t *tes
if _, err := draft.Load(retained.Path); err != nil {
t.Fatal("publication deleted retained draft", err)
}
// Unchanged defaults also work in one confirmation; duplicate names must never update.
for attempt := 0; attempt < 2; attempt++ {
m.templateOpen, m.keys.templates = true, true
updated, _ = m.updateTemplates(tea.KeyMsg{Type: tea.KeyEnter})
m = updated.(Model)
defaultName := m.templates[m.templateIndex].Name
if m.draftNameInput.Value() != defaultName {
t.Fatal("template name not prefilled")
}
updated, send := m.updateConfirm(tea.KeyMsg{Type: tea.KeyEnter})
m = updated.(Model)
if send == nil {
t.Fatal("default name needed extra confirmation")
}
send()
updated, _ = m.Update(m.read()())
m = updated.(Model)
if attempt == 0 && m.confirmOpen {
t.Fatal("default-name creation failed", m.submitNotice)
}
if attempt == 1 && (!m.confirmOpen || !strings.Contains(m.submitNotice, "already exists")) {
t.Fatal("duplicate name did not stay editable", m.submitNotice)
}
}
items, _ = store.List(ctx)
if len(items) != 2 {
t.Fatal("duplicate creation changed pipelines", items)
}
for _, item := range items {
if item.Version != 1 {
t.Fatal("template silently updated existing pipeline")
}
}
}
func TestPublicationWordingDistinguishesCreateAndUpdate(t *testing.T) {
m := New(context.Background(), "")
m.width = 120
for _, test := range []struct {
createOnly bool
base int
want string
}{{true, 0, "Create pipeline"}, {false, 3, "Update pipeline"}} {
m.pendingDraft = &editedMsg{name: "Workflow", createOnly: test.createOnly, baseVersion: test.base}
view := m.confirmView(24)
if !strings.Contains(view, test.want) || strings.Contains(view, "Submit edited pipeline") || strings.Contains(view, "s submit") {
t.Fatal("wrong publication wording", view)
}
m.confirmOpen = true
if !strings.Contains(m.footerContent(), strings.ToLower(test.want)) {
t.Fatal("wrong publication footer")
}
}
}
+97 -7
View File
@@ -20,6 +20,8 @@ func (m Model) openTemplates() (tea.Model, tea.Cmd) {
m.keys.templates = true
m.templateIndex = 0
m.templateTop = 0
m.templateGraphFocus = false
m.templateGraphTop, m.templateGraphPan = 0, 0
m.templateError = ""
m.nextID++
m.templateRequest = fmt.Sprint(m.nextID)
@@ -28,6 +30,7 @@ func (m Model) openTemplates() (tea.Model, tea.Cmd) {
func (m *Model) renderTemplate() {
m.templateTop = 0
m.templateGraphTop, m.templateGraphPan = 0, 0
m.templateLines = nil
if len(m.templates) == 0 {
return
@@ -49,17 +52,48 @@ func (m *Model) renderTemplate() {
}
func (m Model) updateTemplates(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
if m.templateGraphFocus {
handled := true
switch msg.String() {
case "j", "down":
m.templateGraphTop++
case "k", "up":
m.templateGraphTop = max(0, m.templateGraphTop-1)
case "h", "left":
m.templateGraphPan = max(0, m.templateGraphPan-4)
case "l", "right":
m.templateGraphPan += 4
case "c", "home":
m.templateGraphTop, m.templateGraphPan = 0, 0
case "pgdown", "ctrl+d":
m.templateGraphTop += max(1, m.height/3)
case "pgup", "ctrl+u":
m.templateGraphTop = max(0, m.templateGraphTop-max(1, m.height/3))
default:
handled = false
}
if handled {
return m.clampTemplateGraph(), nil
}
}
switch msg.String() {
case "tab", "shift+tab":
m.templateGraphFocus = !m.templateGraphFocus
case "s", "enter":
if len(m.templates) == 0 || m.submitID != "" {
return m, nil
}
m.pendingDraft = &editedMsg{source: pipeline.WithDefaultModel(m.templates[m.templateIndex].Source, m.defaultModel), createOnly: true}
t := m.templates[m.templateIndex]
source := pipeline.WithDefaultModel(t.Source, m.defaultModel)
m.pendingDraft = &editedMsg{name: t.Name, source: source, createOnly: true}
m.templateConfirm = true
m.confirmOpen = true
m.keys.confirm = true
m.submitNotice = ""
m.draftNameInput = newInput()
return m, nil
m.draftNameInput.Prompt = "Name: "
m.draftNameInput.SetValue(t.Name)
return m, m.draftNameInput.Focus()
case "e":
if len(m.templates) > 0 {
return m.newPipeline(m.templates[m.templateIndex].Source)
@@ -94,31 +128,87 @@ func (m Model) updateTemplates(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
case "end":
m.templateTop = len(m.templateLines)
}
m.templateTop = max(0, min(m.templateTop, max(0, len(m.templateLines)-max(1, m.height-11))))
return m, nil
descriptionHeight, _ := m.templatePaneHeights(max(0, m.height-4))
m.templateTop = max(0, min(m.templateTop, max(0, len(m.templateLines)-max(1, descriptionHeight-7))))
return m.clampTemplateGraph(), nil
}
func (m Model) clampTemplateGraph() Model {
if len(m.templates) == 0 {
return m
}
graph, err := pipeline.Parse(m.templates[m.templateIndex].Source)
if err != nil {
return m
}
lines := renderGraph(graph)
widest := 0
for _, line := range lines {
widest = max(widest, ansi.StringWidth(line))
}
_, height := m.templatePaneHeights(max(0, m.height-4))
m.templateGraphTop = max(0, min(m.templateGraphTop, max(0, len(lines)-max(0, height-5))))
m.templateGraphPan = max(0, min(m.templateGraphPan, max(0, widest-max(1, m.width-4))))
return m
}
func (m Model) templatesView(height int) string {
if len(m.templates) == 0 {
if m.templateError != "" {
return fitBlock([]string{"Templates unavailable", m.templateError, "Use :refresh to try again. Esc back."}, m.width, height)
}
return fitBlock([]string{"Templates", m.loading("Loading examples…"), m.templateError, "Esc back"}, m.width, height)
}
descriptionHeight, graphHeight := m.templatePaneHeights(height)
description := m.templateDescriptionView(descriptionHeight)
graph := m.templateGraphView(graphHeight)
return fitBlock(strings.Split(description+"\n"+graph, "\n"), m.width, height)
}
func (m Model) templatePaneHeights(height int) (int, int) {
if height < 14 {
if m.templateGraphFocus {
return min(2, height), max(0, height-2)
}
return max(0, height-2), min(2, height)
}
graph := max(6, height/3)
if m.templateGraphFocus {
graph = height - max(6, height/4)
}
return height - graph, graph
}
func (m Model) templateGraphView(height int) string {
if height <= 2 {
return fitBlock([]string{bar("Template graph", "Tab to expand", m.width, false)}, m.width, height)
}
t := m.templates[m.templateIndex]
graph, err := pipeline.Parse(pipeline.WithDefaultModel(t.Source, m.defaultModel))
if err != nil {
return panel(m.width, height, []string{"Template graph"}, []string{"Graph unavailable: " + err.Error()}, "", m.templateGraphFocus)
}
return graphViewport("Template graph", renderGraph(graph), m.width, height, m.templateGraphTop, m.templateGraphPan, m.templateGraphFocus, "Tab description · n/p template · hjkl pan · c center")
}
func (m Model) templateDescriptionView(height int) string {
t := m.templates[m.templateIndex]
mode := "Rendered Markdown"
if m.templateRaw {
mode = "Markdown source"
}
title := fmt.Sprintf("Templates · %d/%d · %s", m.templateIndex+1, len(m.templates), t.Name)
note := "Preview only · choose a name, then confirm publication."
note := "Preview only · create a pipeline with an editable, prefilled name."
if t.Scheduled {
note = "SCHEDULED: submission activates its schedule; edit/remove settings first."
}
rows := max(0, height-7)
top := max(0, min(m.templateTop, max(0, len(m.templateLines)-rows)))
end := min(len(m.templateLines), top+rows)
headers := []string{bar(title, mode, max(1, m.width-4), true), action("s Submit template", true) + " " + action("e Customize", false), lipgloss.NewStyle().Foreground(themeMuted).Render(note), bar("", fmt.Sprintf("%d–%d / %d", min(top+1, len(m.templateLines)), end, len(m.templateLines)), max(1, m.width-4), false)}
headers := []string{runPaneTitle(title, mode, max(1, m.width-4), !m.templateGraphFocus), action("s Create pipeline", true) + " " + action("e Customize", false), lipgloss.NewStyle().Foreground(themeMuted).Render(note), bar("", fmt.Sprintf("%d–%d / %d", min(top+1, len(m.templateLines)), end, len(m.templateLines)), max(1, m.width-4), false)}
body := m.templateLines[top:end]
if m.templateError != "" {
body = append([]string{m.templateError}, body...)
}
return panel(m.width, height, headers, body, "s/Enter submit · e customize · n/p template · v source · j/k scroll · Esc back", true)
return panel(m.width, height, headers, body, "s/Enter create · Tab graph · n/p template · v source · j/k scroll", !m.templateGraphFocus)
}
+55
View File
@@ -3,6 +3,7 @@ package tui
import (
"context"
"git.a-wan.net/alan/pipelines/examples"
"git.a-wan.net/alan/pipelines/internal/pipeline"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/x/ansi"
"os"
@@ -63,6 +64,60 @@ func TestTemplateMarkdownPreviewDraftAndKeyboardScope(t *testing.T) {
}
}
func TestTemplateGraphPreviewFocusNavigationAndSizes(t *testing.T) {
for _, size := range []struct{ w, h int }{{40, 16}, {80, 24}, {120, 36}, {160, 48}} {
m := New(context.Background(), "")
m.width, m.height = size.w, size.h
m.templateOpen = true
m.keys.templates = true
m.templates = examples.Catalog()
for i, item := range m.templates {
m.templateIndex = i
m.templateGraphFocus = false
m.renderTemplate()
description, graph := m.templatePaneHeights(size.h - 4)
if description <= graph {
t.Fatal("description should dominate initial preview", size, item.Key)
}
if !strings.Contains(ansi.Strip(m.View()), "Template graph") {
t.Fatal("graph preview missing", item.Key)
}
m = press(m, "tab")
description, graph = m.templatePaneHeights(size.h - 4)
if !m.templateGraphFocus || graph <= description {
t.Fatal("Tab did not expand graph", size, item.Key)
}
parsed, err := pipeline.Parse(item.Source)
if err != nil {
t.Fatal(err)
}
view := ansi.Strip(m.View())
if !strings.Contains(view, parsed.Stages[0].Key) {
t.Fatal("focused graph does not match selected template", size, item.Key, view)
}
oldIndex, oldTop := m.templateIndex, m.templateTop
m = press(m, "j")
m = press(m, "l")
if m.templateIndex != oldIndex || m.templateTop != oldTop {
t.Fatal("graph panning moved template or description")
}
m = press(m, "c")
if m.templateGraphTop != 0 || m.templateGraphPan != 0 {
t.Fatal("graph centering failed")
}
for _, line := range strings.Split(m.View(), "\n") {
if ansi.StringWidth(line) > size.w {
t.Fatal("focused preview overflow", size)
}
}
m = press(m, "shift+tab")
if m.templateGraphFocus {
t.Fatal("reverse Tab introduced another focus target")
}
}
}
}
func TestTemplateRenderingFitsSmallTerminals(t *testing.T) {
for _, width := range []int{1, 12, 40, 80, 120} {
m := New(context.Background(), "")
+53
View File
@@ -0,0 +1,53 @@
package tui
import (
"fmt"
"git.a-wan.net/alan/pipelines/internal/runinspect"
tea "github.com/charmbracelet/bubbletea"
"os/exec"
"path/filepath"
"time"
)
type transferFinishedMsg struct {
path string
imported bool
err error
}
func (m Model) transferPipelines(imported bool) (tea.Model, tea.Cmd) {
executable, err := runinspect.CLIExecutable()
if err != nil {
m.appendLine(err.Error())
return m, nil
}
command := "export"
path := ""
args := []string{"--url", m.url}
if imported {
command = "import"
} else {
path, err = filepath.Abs("pipelines-export-" + time.Now().Format("20060102-150405.000000000") + ".zip")
if err != nil {
m.appendLine(err.Error())
return m, nil
}
}
args = append(args, command)
if path != "" {
args = append(args, "--output", path)
}
return m, tea.ExecProcess(exec.Command(executable, args...), func(err error) tea.Msg { return transferFinishedMsg{path: path, imported: imported, err: err} })
}
func (m *Model) transferResult(msg transferFinishedMsg) {
if msg.err != nil {
m.appendLine(fmt.Sprintf("Pipeline transfer canceled or failed: %v", msg.err))
return
}
if msg.imported {
m.appendLine("Pipeline import completed; conflicts resolved and version history retained.")
} else {
m.appendLine("Export saved: " + msg.path)
}
}
+269
View File
@@ -0,0 +1,269 @@
package tui
import (
"context"
"encoding/json"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/draft"
"git.a-wan.net/alan/pipelines/internal/protocol"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/x/ansi"
)
func keyMessage(value string) tea.KeyMsg { return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(value)} }
func TestRunHasExactlyTwoVisibleFocusTargetsAtEverySize(t *testing.T) {
for _, size := range []struct{ width, height int }{{40, 16}, {80, 24}, {120, 36}} {
m := runInspectionModel()
m.width, m.height = size.width, size.height
m.runDetail = nil
r := runInspectionModel().runDetail
updated, _ := m.Update(receivedMsg(protocol.Message{Type: protocol.Run, RunDetail: r}))
m = updated.(Model)
if m.runGraphFocus || !m.runDetailFocus {
t.Fatal("initial result pane not focused")
}
for i := 0; i < 8; i++ {
m = runKey(m, "tab")
if m.runGraphFocus == m.runDetailFocus {
t.Fatal("invisible third target", size, i)
}
view := ansi.Strip(m.runsView(size.height - 4))
if m.runGraphFocus {
if !strings.Contains(view, "Run graph") || !strings.ContainsAny(view, "╭╔│║") {
t.Fatal("focused graph not visible", size, view)
}
} else if !strings.Contains(strings.ToLower(view), "result") {
t.Fatal("focused result not visible", size, view)
}
if strings.Contains(view, "▸ Stages") {
t.Fatal("third pane survived")
}
index := m.runStepIndex
top := m.runTop
m = runKey(m, "j")
if m.runStepIndex != index {
t.Fatal("scroll key changed the recorded visit")
}
if !m.runGraphFocus && m.runTop < top {
t.Fatal("detail scroll moved backwards")
}
}
m = runKey(m, "shift+tab")
if !m.runGraphFocus {
t.Fatal("reverse Tab did not toggle graph")
}
m = runKey(m, "shift+tab")
if !m.runDetailFocus || m.runGraphFocus {
t.Fatal("reverse Tab introduced third target")
}
}
}
func TestResultDocumentRendersProseListsAndNestedValuesLosslessly(t *testing.T) {
output := map[string]any{"summary": "## Accomplished\n\nUpdated **layout** and added checks.", "artifacts": []any{"screen.go", "report.md"}, "evidence": map[string]any{"command": "go test ./...", "count": json.Number("9007199254740993"), "passed": true}, "optional": nil}
before, _ := json.Marshal(output)
text := ansi.Strip(strings.Join(resultDocument(output, 72), "\n"))
for _, want := range []string{"Accomplished", "Updated layout", "• screen.go", "• report.md", "Command", "go test ./...", "9007199254740993", "true", "(none)"} {
if !strings.Contains(text, want) {
t.Fatal("result data lost", want, text)
}
}
if strings.Contains(text, "**layout**") || strings.Contains(text, `"command":`) {
t.Fatal("result still looks like raw transport data", text)
}
after, _ := json.Marshal(output)
if string(before) != string(after) {
t.Fatal("visualization altered retained data")
}
m := runInspectionModel()
m.runStepIndex = 1
m.runDetail.Steps[0].Output = output
if text = ansi.Strip(strings.Join(m.runSectionLines(76), "\n")); strings.Count(text, "Updated layout") != 1 {
t.Fatal("result summary duplicated", text)
}
}
func TestActionSafetyTextIsReachableAndControlsStayPinned(t *testing.T) {
m := New(context.Background(), "")
m.width, m.height = 40, 16
m.actionConfirm = &protocol.Message{Type: protocol.RetryRun, RunID: 1234}
var views []string
for i := 0; i < 40; i++ {
view := ansi.Strip(m.actionConfirmView(12))
views = append(views, strings.Join(strings.Fields(view), " "))
if !strings.Contains(view, "y confirm") || !strings.Contains(view, "Esc cancel") {
t.Fatal("safety controls disappeared", view)
}
updated, _ := m.updateActionConfirm(keyMessage("j"))
m = updated.(Model)
if m.actionConfirm == nil || m.actionApproved {
t.Fatal("reading warning executed action")
}
}
all := strings.Join(views, " ")
for _, warning := range []string{"NEW run", "original input", "pinned version", "Previous side effects are not undone", "commands/notifications may repeat"} {
if !strings.Contains(all, warning) {
t.Fatal("safety warning unreachable", warning, all)
}
}
}
func TestActiveContextsNeverAdvertiseBackgroundPageControls(t *testing.T) {
for _, test := range []struct {
name string
setup func(*Model)
want string
}{
{"run form", func(m *Model) { m.runForm = 1 }, "Ctrl+S run"},
{"name", func(m *Model) { m.confirmOpen = true; m.pendingDraft = &editedMsg{} }, "Enter save name"},
{"editor", func(m *Model) { m.editorOpen = true }, "Enter open"},
{"safety", func(m *Model) { m.actionConfirm = &protocol.Message{} }, "y confirm"},
{"status", func(m *Model) { m.statusOpen = true }, "r refresh"},
{"checking", func(m *Model) { m.editorChecking = true }, "draft retained"},
} {
t.Run(test.name, func(t *testing.T) {
m := New(context.Background(), "")
m.width = 100
test.setup(&m)
footer := ansi.Strip(m.footerContent())
if !strings.Contains(footer, test.want) || strings.Contains(footer, "/ search") || strings.Contains(footer, "LOGS") {
t.Fatal("wrong context footer", footer)
}
})
}
}
func TestTerminalErrorsReplaceLoadingAndKeepRecoveryInstructions(t *testing.T) {
m := New(context.Background(), "")
m.width = 80
m.templateOpen = true
m.templateError = "Server connection failed"
view := ansi.Strip(m.templatesView(20))
if strings.Contains(view, "Loading") || !strings.Contains(view, "connection failed") {
t.Fatal("template error retained loading", view)
}
m.runOpen = true
m.requestedRunID = 8
m.runError = "Run not found"
view = ansi.Strip(m.runsDetailsView(20))
if strings.Contains(view, "Loading") || !strings.Contains(view, "Run not found") {
t.Fatal("run error retained loading", view)
}
}
func TestNarrowStatusActuallyScrollsToPhoneConnection(t *testing.T) {
m := New(context.Background(), "ws://localhost/connect")
m.width, m.height = 40, 16
m.statusOpen = true
m.statusError = "Connection unavailable"
var views []string
for i := 0; i < 60; i++ {
views = append(views, ansi.Strip(m.statusView(12)))
updated, _ := m.updateStatus(keyMessage("j"))
m = updated.(Model)
}
if !strings.Contains(strings.Join(views, "\n"), "ntfy · phone connection") || m.statusTop == 0 {
t.Fatal("phone connection remains unreachable")
}
}
func TestNarrowRunShowsActualResultAndEssentialControls(t *testing.T) {
m := runInspectionModel()
m.width, m.height = 40, 16
m.runStepIndex = 1
m.runDetail.Steps[0].Output = map[string]any{"summary": "## Accomplished\n\nUpdated the layout.", "artifacts": []any{"screen.go"}}
view := ansi.Strip(m.View())
if !strings.Contains(view, "Updated the layout.") {
t.Fatal("actual result still below first viewport", view)
}
footer := ansi.Strip(m.footerContent())
for _, hint := range []string{"Tab graph", "n/p visit", "j/k read", "Esc"} {
if !strings.Contains(footer, hint) {
t.Fatal("essential run control hidden", hint, footer)
}
}
if strings.Contains(footer, "LOGS") {
t.Fatal("log badge displaced controls")
}
}
func TestPipelineStageFocusCollapsesUnusableGraphPreview(t *testing.T) {
for _, size := range []struct{ width, height int }{{40, 16}, {80, 24}, {120, 36}} {
m := panelModel(t)
m.width, m.height = size.width, size.height
m.stageFocus = true
g := m.pipelineGeometry(size.height - 4)
if g.graphHeight > 2 {
t.Fatal("inactive graph still shows severed box tops", g)
}
view := ansi.Strip(m.pipelineView(size.height - 4))
if strings.ContainsAny(view, "╭╔│║") {
t.Fatal("clipped graph displaced stage document", view)
}
if !strings.Contains(view, "Output for implementer") {
t.Fatal("focused stage output not visible", view)
}
}
}
func TestNarrowOverlayFootersAlwaysKeepEscapeVisible(t *testing.T) {
for _, setup := range []func(*Model){func(m *Model) { m.paletteOpen = true; m.searchOpen = true }, func(m *Model) { m.paletteOpen = true }, func(m *Model) { m.editorOpen = true }, func(m *Model) { m.versionsOpen = true }, func(m *Model) { m.runPicker = true }, func(m *Model) { m.runForm = 1 }} {
m := New(context.Background(), "")
m.width = 40
setup(&m)
footer := ansi.Strip(m.footerContent())
if !strings.Contains(footer, "Esc") || strings.Contains(footer, "LOGS") {
t.Fatal("overlay escape hidden", footer)
}
}
}
func TestDraftDeleteUsesWrappedSafetyTextWithoutDeletingWhileReading(t *testing.T) {
m := New(context.Background(), "")
m.width, m.height = 40, 16
m.draftOpen = true
m.keys.drafts = true
m.draftDeletingPath = "/Users/reviewer/Library/Caches/pipelines/retained-draft-with-a-long-name.md"
m.draftItems = []draft.Draft{{Name: "Layout review", Path: m.draftDeletingPath}}
var views []string
for i := 0; i < 35; i++ {
view := ansi.Strip(m.draftsView(12))
views = append(views, strings.Join(strings.Fields(view), " "))
if !strings.Contains(view, "y delete") || !strings.Contains(view, "Esc keep") {
t.Fatal("draft confirmation controls lost", view)
}
updated, _ := m.updateDrafts(keyMessage("j"))
m = updated.(Model)
if m.draftDeletingPath == "" {
t.Fatal("reading warning deleted/canceled draft")
}
}
all := strings.Join(views, " ")
for _, want := range []string{"Layout review", "Only this draft and its metadata are deleted", "Published pipelines/history stay intact", "File:", "name.md"} {
if !strings.Contains(all, want) {
t.Fatal("draft disclosure unreachable", want, all)
}
}
footer := ansi.Strip(m.footerContent())
if !strings.Contains(footer, "y delete") || strings.Contains(footer, "e edit") {
t.Fatal("wrong delete context", footer)
}
}
func TestLongLogDiagnosticsRemainReachableByHorizontalPan(t *testing.T) {
m := New(context.Background(), "")
m.width, m.height = 40, 16
m.appendLine(strings.Repeat("context ", 30) + "critical failure reason")
m.logOpen = true
for i := 0; i < 60; i++ {
updated, _ := m.updateLogs(keyMessage("right"))
m = updated.(Model)
}
view := ansi.Strip(m.logsView(12))
if m.logPan == 0 || !strings.Contains(view, "critical failure reason") {
t.Fatal("long log reason inaccessible", view)
}
}