package tui import ( "context" "fmt" "net/url" "strconv" "strings" "time" "github.com/charmbracelet/bubbles/help" "github.com/charmbracelet/bubbles/key" "github.com/charmbracelet/bubbles/spinner" "github.com/charmbracelet/bubbles/textarea" "github.com/charmbracelet/bubbles/textinput" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" "github.com/charmbracelet/x/ansi" "github.com/coder/websocket" "git.a-wan.net/alan/pipelines/internal/client" "git.a-wan.net/alan/pipelines/internal/draft" "git.a-wan.net/alan/pipelines/internal/pipeline" "git.a-wan.net/alan/pipelines/internal/protocol" ) type connectedMsg struct{ conn *websocket.Conn } type receivedMsg protocol.Message type sentMsg struct{ id string } type errorMsg struct { err error conn *websocket.Conn } type socketMsg struct { conn *websocket.Conn message protocol.Message } type reconnectMsg struct{} type keyMap struct { ping key.Binding quit key.Binding create key.Binding enter key.Binding cancel key.Binding commands key.Binding logs bool palette bool search key.Binding detail bool versions bool confirm bool runs bool templates bool drafts bool } 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} } 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} } if k.versions { return []key.Binding{key.NewBinding(key.WithKeys("j", "k"), key.WithHelp("j/k", "select")), k.enter, k.cancel} } if k.logs { return []key.Binding{key.NewBinding(key.WithKeys("j", "k"), key.WithHelp("j/k", "line")), key.NewBinding(key.WithKeys("h", "l"), key.WithHelp("h/l", "half page")), k.cancel} } if k.palette { return []key.Binding{k.enter, k.cancel} } if k.templates { return []key.Binding{key.NewBinding(key.WithKeys("n", "p"), key.WithHelp("n/p", "template")), key.NewBinding(key.WithKeys("v"), key.WithHelp("v", "render/source")), key.NewBinding(key.WithKeys("enter"), key.WithHelp("Enter", "use template")), k.cancel} } if k.runs { return []key.Binding{k.commands, 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("pgup", "pgdown"), key.WithHelp("PgUp/Dn", "page")), 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"))} } return []key.Binding{k.commands, k.search, k.create, key.NewBinding(key.WithKeys("d"), key.WithHelp("d", "drafts")), key.NewBinding(key.WithKeys("b"), key.WithHelp("b", "templates")), k.ping, k.quit} } func (k keyMap) FullHelp() [][]key.Binding { return [][]key.Binding{k.ShortHelp()} } type Model struct { 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 pendingDraft *editedMsg 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 runSpinner spinner.Model templates []protocol.Template templateOpen, templateRaw bool templateIndex, templateTop int templateLines []string templateRequest, templateError string } func New(ctx context.Context, url string) Model { return Model{ ctx: ctx, url: url, status: "Connecting…", width: 80, height: 24, help: newHelp(), runPrompt: textarea.New(), runSpinner: spinner.New(spinner.WithSpinner(spinner.Dot), spinner.WithStyle(lipgloss.NewStyle().Foreground(themeAccent))), keys: keyMap{ commands: key.NewBinding(key.WithKeys(":"), key.WithHelp(":", "commands")), search: key.NewBinding(key.WithKeys("/"), key.WithHelp("/", "search")), create: key.NewBinding(key.WithKeys("n"), key.WithHelp("n", "new pipeline")), enter: key.NewBinding(key.WithKeys("enter"), key.WithHelp("enter", "continue")), cancel: key.NewBinding(key.WithKeys("esc"), key.WithHelp("esc", "cancel")), ping: key.NewBinding(key.WithKeys("t"), key.WithHelp("t", "test ping")), quit: key.NewBinding(key.WithKeys("q", "ctrl+c"), key.WithHelp("q", "quit")), }, } } func (m Model) Init() tea.Cmd { return tea.Batch(m.connect(), runPoll(), m.runSpinner.Tick) } func (m Model) connect() tea.Cmd { return func() tea.Msg { ctx, cancel := context.WithTimeout(m.ctx, 5*time.Second) defer cancel() conn, err := client.Dial(ctx, m.url) if err != nil { return errorMsg{err: err} } // Ensure quitting also closes an idle connection. go func() { <-m.ctx.Done() conn.CloseNow() }() return connectedMsg{conn} } } func (m Model) read() tea.Cmd { return func() tea.Msg { response, err := client.Receive(m.ctx, m.conn) if err != nil { return errorMsg{err: err, conn: m.conn} } return socketMsg{conn: m.conn, message: response} } } func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case spinner.TickMsg: var cmd tea.Cmd m.runSpinner, cmd = m.runSpinner.Update(msg) return m, cmd case runTick: if m.conn == nil { return m, runPoll() } request := protocol.Message{Type: protocol.ListRuns} if m.runOpen && m.requestedRunID > 0 { request.Type = protocol.GetRun request.RunID = m.requestedRunID } if m.runOpen && m.runDetail != nil { request.Type = protocol.GetRun request.RunID = m.runDetail.ID } updated, cmd := m.runRequest(request) return updated, tea.Batch(cmd, runPoll()) case tea.WindowSizeMsg: m.width = max(1, msg.Width) m.height = max(1, msg.Height) 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))) } if m.templateOpen { oldTop := m.templateTop m.renderTemplate() m.templateTop = oldTop } if m.keys.detail { m.clampPipelineScroll() } if m.logOpen { m.logTop = min(m.logTop, max(0, len(m.lines)-m.logPageSize())) m.markVisibleLogs() } case connectedMsg: m.notificationEndpoints = nil if m.conn != nil && m.conn != msg.conn { m.conn.CloseNow() } m.conn = msg.conn m.reconnecting = false m.status = m.url if endpoint, err := url.Parse(m.url); err == nil { m.status = endpoint.Host } if m.keys.detail && m.requestedPipelineID > 0 { updated, send := m.requestPipeline(m.requestedPipelineID, m.requestedVersion) m = updated.(Model) return m, tea.Batch(m.read(), send) } return m, m.read() case reconnectMsg: if m.conn != nil || m.ctx.Err() != nil { return m, nil } return m, m.connect() case socketMsg: if msg.conn != m.conn { return m, nil } return m.Update(receivedMsg(msg.message)) case receivedMsg: if msg.Type == protocol.PipelineList || msg.Type == protocol.Submitted { m.notificationEndpoints = msg.NotificationEndpoints } if msg.Type == protocol.Templates && msg.ID == m.templateRequest { m.templates = msg.Templates m.templateIndex = 0 m.renderTemplate() } else if msg.Type == protocol.Runs { m.runs = msg.Runs m.runIndex = min(m.runIndex, max(0, len(m.visibleRuns())-1)) } else if msg.Type == protocol.Run || msg.Type == protocol.RunStarted { accepted := m.runOpen && msg.RunDetail != nil && ((msg.Type == protocol.Run && msg.RunDetail.ID == m.requestedRunID) || (msg.Type == protocol.RunStarted && msg.ID == m.runStartRequest)) if accepted { m.keys.runs = true m.runDetail = msg.RunDetail m.requestedRunID = msg.RunDetail.ID m.runError = "" m.runStepIndex = min(m.runStepIndex, len(msg.RunDetail.Steps)) } } else if msg.Type == protocol.Pong { m.appendLine(fmt.Sprintf("pong #%s: %s", msg.ID, msg.Time)) } else if msg.Type == protocol.Error { m.appendLine(fmt.Sprintf("server error #%s: %s", msg.ID, msg.Error)) if msg.ID == m.templateRequest { m.templateError = msg.Error } if strings.HasPrefix(msg.ID, "run-") && m.runOpen { m.runError = msg.Error } if msg.ID != "" && msg.ID == m.detailRequest { m.detailLoading = false m.detailError = msg.Error } if msg.ID != "" && msg.ID == m.submitID { m.submitID = "" m.submitNotice = msg.Error if m.pendingDraft != nil { m.confirmOpen = true m.keys.confirm = true } } } else if msg.Type == protocol.Submitted { 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)) m.pipelines = msg.Pipelines m.loaded = true if msg.ID == m.submitID { m.submitID = "" m.pendingDraft = nil m.confirmOpen = false m.keys.confirm = false m.submitNotice = fmt.Sprintf("Submitted version %d", msg.Version) } if msg.Detail != nil { m.detail = msg.Detail m.keys.detail = true m.detailLoading = false m.detailRequest = "" m.detailError = "" m.resetPipelineView() m.requestedPipelineID = msg.Detail.ID m.requestedVersion = msg.Detail.Version } } else if msg.Type == protocol.Pipeline { if msg.ID == m.detailRequest { if msg.Detail == nil || (m.requestedPipelineID > 0 && msg.Detail.ID != m.requestedPipelineID) || (m.requestedVersion > 0 && msg.Detail.Version != m.requestedVersion) { m.detailLoading = false m.detailError = "Server returned a different pipeline or version than requested" return m, m.read() } m.detail = msg.Detail m.keys.detail = true m.detailLoading = false m.detailError = "" m.resetPipelineView() if m.cliRun && !m.cliStarted { updated, cmd := m.configureCLIRun() return updated, tea.Batch(m.read(), cmd) } } } else if msg.Type == protocol.PipelineList { m.pipelines = msg.Pipelines m.loaded = true if m.cliRun && !m.cliStarted && m.cliOptions.Pipeline != "" { for _, p := range m.pipelines { if p.Name == m.cliOptions.Pipeline { m.runPicker = false updated, send := m.requestPipeline(p.ID, p.Version) return updated, tea.Batch(m.read(), send) } } } } else { m.appendLine("unexpected response: " + msg.Type) } return m, m.read() case draftValidationMsg: if len(m.draftItems) > 0 && m.draftItems[m.draftIndex].Path == msg.path { m.draftError = "Validation passed (structure only)." if msg.err != nil { m.draftError = "Validation: " + msg.err.Error() } } return m, nil case sentMsg: // Responses are displayed by the independent read loop. case editedMsg: m.appendLine("Draft: " + msg.path) if msg.err != nil { m.appendLine("editor: " + msg.err.Error()) return m, nil } if msg.unchanged { m.confirmOpen = false m.keys.confirm = false m.submitNotice = "No changes." m.appendLine("No changes; nothing to submit.") return m, nil } // Editor completion is never approval to publish, for either new or existing drafts. m.pendingDraft = &msg m.confirmOpen = true m.keys.confirm = true m.submitNotice = "" return m, nil case errorMsg: if msg.conn != nil && msg.conn != m.conn { return m, nil } if msg.conn == nil && m.conn != nil { return m, nil } m.status = "Reconnecting…" m.appendLine("error: " + msg.err.Error()) m.detailRequest = "" m.detailLoading = m.keys.detail && m.requestedPipelineID > 0 m.submitID = "" if m.pendingDraft != nil { m.submitNotice = "Connection lost; submission outcome unknown. Draft retained." } if m.conn != nil { m.conn.CloseNow() m.conn = nil } m.reconnecting = true return m, tea.Tick(time.Second, func(time.Time) tea.Msg { return reconnectMsg{} }) case tea.KeyMsg: if msg.String() == "ctrl+c" { return m, tea.Quit } if m.logOpen { return m.updateLogs(msg) } if m.paletteOpen { return m.updatePalette(msg) } if m.confirmOpen { return m.updateConfirm(msg) } if m.draftOpen { return m.updateDrafts(msg) } if m.runPicker { return m.updateRunPicker(msg) } if m.runForm != 0 { return m.updateRunForm(msg) } if m.runOpen && msg.String() != ":" { return m.updateRuns(msg) } if m.versionsOpen { return m.updateVersions(msg) } if m.templateOpen { return m.updateTemplates(msg) } switch { case m.homePage() && msg.String() == "d": return m.openDrafts() case m.homePage() && msg.String() == "b": return m.openTemplates() case key.Matches(msg, m.keys.commands), key.Matches(msg, m.keys.search): m.paletteOpen = true m.searchOpen = key.Matches(msg, m.keys.search) m.keys.palette = true m.commandIndex = 0 m.commandInput = newInput() if m.searchOpen { m.commandInput.Placeholder = "Search pipelines…" } else { m.commandInput.Placeholder = ":logs" m.commandInput.SetValue(":") } return m, m.commandInput.Focus() case m.homePage() && key.Matches(msg, m.keys.quit): return m, tea.Quit case m.homePage() && key.Matches(msg, m.keys.create): if m.conn == nil { m.appendLine("not connected") return m, nil } return m, editDraftMode("", pipeline.Template([]string{"worker"}, true), true, true, draft.Draft{Server: m.url}) case m.homePage() && key.Matches(msg, m.keys.ping): if m.conn == nil { m.appendLine("not connected") return m, nil } m.nextID++ id := strconv.FormatUint(m.nextID, 10) m.appendLine("ping #" + id) return m, func() tea.Msg { ctx, cancel := context.WithTimeout(m.ctx, 5*time.Second) defer cancel() if err := client.Send(ctx, m.conn, protocol.Message{Type: protocol.Ping, ID: id}); err != nil { return errorMsg{err: err, conn: m.conn} } return sentMsg{id} } case m.keys.detail: return m.updatePipeline(msg) case msg.String() == "j" || msg.String() == "down": m.homeTop = min(m.homeTop+1, max(0, len(m.homeLines())-max(1, m.height-4))) case msg.String() == "k" || msg.String() == "up": m.homeTop = max(0, m.homeTop-1) } } if m.runForm != 0 { var cmd tea.Cmd if m.runForm == 1 { m.runPrompt, cmd = m.runPrompt.Update(msg) return m, cmd } m.runInput, cmd = m.runInput.Update(msg) return m, cmd } if m.paletteOpen { var cmd tea.Cmd m.commandInput, cmd = m.commandInput.Update(msg) return m, cmd } if m.runPicker { var cmd tea.Cmd m.runPickerInput, cmd = m.runPickerInput.Update(msg) return m, cmd } return m, nil } func (m *Model) appendLine(line string) { follow := m.logOpen && m.logTop >= max(0, len(m.lines)-m.logPageSize()) for _, part := range strings.Split(line, "\n") { m.lines = append(m.lines, ansi.Strip(part)) m.logSeen = append(m.logSeen, false) m.unread++ } if m.logOpen { if follow { m.logTop = max(0, len(m.lines)-m.logPageSize()) } m.markVisibleLogs() } } func (m Model) View() string { connection := m.status 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 = m.status + " · 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 { name := "Pipelines" if m.keys.detail && m.detail != nil { name = fmt.Sprintf("%s · v%d", m.detail.Name, m.detail.Version) } if m.detailLoading { name = "Loading pipeline" if m.requestedVersion > 0 { name = fmt.Sprintf("Loading v%d", m.requestedVersion) } } if m.runOpen { name = "Runs" if m.requestedRunID > 0 { name = fmt.Sprintf("Run #%d", m.requestedRunID) } } if m.templateOpen { name = "Templates" } if m.draftOpen { name = "Drafts" } title = ansi.Truncate(name, titleWidth, "…") } gap := max(0, m.width-lipgloss.Width(title)-lipgloss.Width(status)) headerLine := lipgloss.NewStyle().Bold(true).Foreground(themeAccent).Render(title) + strings.Repeat(" ", gap) + lipgloss.NewStyle().Foreground(themeMuted).Render(status) header := lipgloss.NewStyle(). BorderStyle(lipgloss.NormalBorder()).BorderBottom(true). BorderForeground(themeMuted). Width(m.width).Render(headerLine) footer := lipgloss.NewStyle(). BorderStyle(lipgloss.NormalBorder()).BorderTop(true). BorderForeground(themeMuted). Width(m.width).Render(m.footerContent()) if m.height < 4 { return lipgloss.NewStyle().MaxHeight(m.height).Render(header + "\n" + footer) } bodyHeight := max(0, m.height-lipgloss.Height(header)-lipgloss.Height(footer)) lines := m.homeLines() top := m.homeTop top = min(top, max(0, len(lines)-bodyHeight)) lines = lines[top:min(len(lines), top+bodyHeight)] body := make([]string, bodyHeight) for i, line := range lines { body[i] = ansi.Truncate(line, m.width, "…") } parts := []string{header} if bodyHeight > 0 { content := strings.Join(body, "\n") if m.keys.detail { content = m.pipelineView(bodyHeight) } if m.runOpen { content = m.runsView(bodyHeight) } if m.templateOpen { content = m.templatesView(bodyHeight) } if m.draftOpen { content = m.draftsView(bodyHeight) } if m.runForm != 0 { content = m.runFormView(bodyHeight) } if m.runPicker { content = m.runPickerView(bodyHeight) } if m.logOpen { content = m.logsView(bodyHeight) } else if m.paletteOpen { content = m.paletteView(bodyHeight) } else if m.versionsOpen { content = m.versionsView(bodyHeight) } else if m.confirmOpen { content = m.confirmView(bodyHeight) } parts = append(parts, content) } return strings.Join(append(parts, footer), "\n") }