The open source coding agent.
TypeScript
improve status message handling
Kujtim Hoxhaf463ce669414
diff --git a/cmd/root.go b/cmd/root.goindex 3ed809328f9..0c7c145b721 100644--- a/cmd/root.go+++ b/cmd/root.go@@ -107,6 +107,16 @@ func setupSubscriptions(app *app.App) (chan tea.Msg, func()) {wg.Done()}()}+ {+ sub := app.Status.Subscribe(ctx)+ wg.Add(1)+ go func() {+ for ev := range sub {+ ch <- ev+ }+ wg.Done()+ }()+ }return ch, func() {cancel()wg.Wait()diff --git a/internal/app/services.go b/internal/app/services.goindex 60838cccaf5..3e5d92afde6 100644--- a/internal/app/services.go+++ b/internal/app/services.go@@ -11,7 +11,9 @@ import ("github.com/kujtimiihoxha/termai/internal/lsp/watcher""github.com/kujtimiihoxha/termai/internal/message""github.com/kujtimiihoxha/termai/internal/permission"+ "github.com/kujtimiihoxha/termai/internal/pubsub""github.com/kujtimiihoxha/termai/internal/session"+ "github.com/kujtimiihoxha/termai/internal/tui/util")type App struct {@@ -25,6 +27,7 @@ type App struct {Logger logging.Interface+ Status *pubsub.Broker[util.InfoMsg]ceanups []func()}@@ -43,6 +46,7 @@ func New(ctx context.Context, conn *sql.DB) *App {Messages: messages,Permissions: permission.Default,Logger: log,+ Status: pubsub.NewBroker[util.InfoMsg](),LSPClients: make(map[string]*lsp.Client),}diff --git a/internal/llm/agent/agent.go b/internal/llm/agent/agent.goindex cb123e78cbf..baf78be6574 100644--- a/internal/llm/agent/agent.go+++ b/internal/llm/agent/agent.go@@ -15,6 +15,8 @@ import ("github.com/kujtimiihoxha/termai/internal/llm/provider""github.com/kujtimiihoxha/termai/internal/llm/tools""github.com/kujtimiihoxha/termai/internal/message"+ "github.com/kujtimiihoxha/termai/internal/pubsub"+ "github.com/kujtimiihoxha/termai/internal/tui/util")type Agent interface {@@ -92,9 +94,24 @@ func (c *agent) processEvent(assistantMsg.AppendContent(event.Content)return c.Messages.Update(*assistantMsg)case provider.EventError:+ // TODO: remove when realeaselog.Println("error", event.Error)+ c.App.Status.Publish(pubsub.UpdatedEvent, util.InfoMsg{+ Type: util.InfoTypeError,+ Msg: event.Error.Error(),+ })return event.Error-+ case provider.EventWarning:+ c.App.Status.Publish(pubsub.UpdatedEvent, util.InfoMsg{+ Type: util.InfoTypeWarn,+ Msg: event.Info,+ })+ return nil+ case provider.EventInfo:+ c.App.Status.Publish(pubsub.UpdatedEvent, util.InfoMsg{+ Type: util.InfoTypeInfo,+ Msg: event.Info,+ })case provider.EventComplete:assistantMsg.SetToolCalls(event.Response.ToolCalls)assistantMsg.AddFinish(event.Response.FinishReason)diff --git a/internal/llm/provider/anthropic.go b/internal/llm/provider/anthropic.goindex f42c601a577..239d6760616 100644--- a/internal/llm/provider/anthropic.go+++ b/internal/llm/provider/anthropic.go@@ -149,8 +149,8 @@ func (a *anthropicProvider) StreamResponse(ctx context.Context, messages []messa// Inform user we're retrying with attempt numbereventChan <- ProviderEvent{- Type: EventContentDelta,- Content: fmt.Sprintf("\n\n[Retrying due to rate limit... attempt %d of %d]\n\n", attempts, maxRetries),+ Type: EventWarning,+ Info: fmt.Sprintf("[Retrying due to rate limit... attempt %d of %d]", attempts, maxRetries),}// Calculate backoff with exponential backoff and jitter@@ -380,4 +380,3 @@ func (a *anthropicProvider) convertToAnthropicMessages(messages []message.Messagreturn anthropicMessages}-diff --git a/internal/llm/provider/provider.go b/internal/llm/provider/provider.goindex f40429738a2..cd3a7aa0593 100644--- a/internal/llm/provider/provider.go+++ b/internal/llm/provider/provider.go@@ -17,6 +17,8 @@ const (EventContentStop EventType = "content_stop"EventComplete EventType = "complete"EventError EventType = "error"+ EventWarning EventType = "warning"+ EventInfo EventType = "info")type TokenUsage struct {@@ -40,6 +42,9 @@ type ProviderEvent struct {ToolCall *message.ToolCallError errorResponse *ProviderResponse++ // Used for giving users info on e.x retry+ Info string}type Provider interface {diff --git a/internal/tui/components/core/status.go b/internal/tui/components/core/status.goindex bd36293196b..eb1aca2eb04 100644--- a/internal/tui/components/core/status.go+++ b/internal/tui/components/core/status.go@@ -13,10 +13,9 @@ import ()type statusCmp struct {- err error- info string- width int- messageTTL time.Duration+ info *util.InfoMsg+ width int+ messageTTL time.Duration}// clearMessageCmd is a command that clears status messages after a timeout@@ -34,17 +33,12 @@ func (m statusCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {switch msg := msg.(type) {case tea.WindowSizeMsg:m.width = msg.Width- case util.ErrorMsg:- m.err = msg- m.info = ""return m, m.clearMessageCmd()case util.InfoMsg:- m.info = string(msg)- m.err = nil+ m.info = &msgreturn m, m.clearMessageCmd()case util.ClearStatusMsg:- m.info = ""- m.err = nil+ m.info = nil}return m, nil}@@ -56,25 +50,25 @@ var (func (m statusCmp) View() string {status := styles.Padded.Background(styles.Grey).Foreground(styles.Text).Render("? help")-- if m.err != nil {- status += styles.Regular.Padding(0, 1).- Background(styles.Red).- Foreground(styles.Text).- Width(m.availableFooterMsgWidth()).- Render(m.err.Error())- } else if m.info != "" {- status += styles.Padded.+ if m.info != nil {+ infoStyle := styles.Padded.Foreground(styles.Base).- Background(styles.Green).- Width(m.availableFooterMsgWidth()).- Render(m.info)+ Width(m.availableFooterMsgWidth())+ switch m.info.Type {+ case util.InfoTypeInfo:+ infoStyle = infoStyle.Background(styles.Blue)+ case util.InfoTypeWarn:+ infoStyle = infoStyle.Background(styles.Peach)+ case util.InfoTypeError:+ infoStyle = infoStyle.Background(styles.Red)+ }+ status += infoStyle.Render(m.info.Msg)} else {status += styles.Padded.Foreground(styles.Base).Background(styles.LightGrey).Width(m.availableFooterMsgWidth()).- Render(m.info)+ Render("")}status += m.model()status += versionWidgetdiff --git a/internal/tui/components/dialog/permission.go b/internal/tui/components/dialog/permission.goindex 17b3fba0781..465f475d54e 100644--- a/internal/tui/components/dialog/permission.go+++ b/internal/tui/components/dialog/permission.go@@ -69,13 +69,13 @@ type permissionDialogCmp struct {func formatDiff(diffText string) string {lines := strings.Split(diffText, "\n")var formattedLines []string-+// Define styles for different line typesaddStyle := lipgloss.NewStyle().Foreground(styles.Green)removeStyle := lipgloss.NewStyle().Foreground(styles.Red)headerStyle := lipgloss.NewStyle().Bold(true).Foreground(styles.Blue)contextStyle := lipgloss.NewStyle().Foreground(styles.SubText0)-+// Process each linefor _, line := range lines {if strings.HasPrefix(line, "+") {@@ -90,7 +90,7 @@ func formatDiff(diffText string) string {formattedLines = append(formattedLines, line)}}-+// Join all formatted linesreturn strings.Join(formattedLines, "\n")}@@ -112,13 +112,13 @@ func (p *permissionDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {p.selectOption.Blur()// Add a visual indicator for focus changecmds = append(cmds, tea.Batch(- util.CmdHandler(util.InfoMsg("Viewing content - use arrow keys to scroll")),+ util.ReportInfo("Viewing content - use arrow keys to scroll"),))} else {p.selectOption.Focus()// Add a visual indicator for focus changecmds = append(cmds, tea.Batch(- util.CmdHandler(util.InfoMsg("Select an action")),+ util.CmdHandler(util.ReportInfo("Select an action")),))}return p, tea.Batch(cmds...)@@ -162,44 +162,44 @@ func (p *permissionDialogCmp) render() string {lipgloss.JoinHorizontal(lipgloss.Left, keyStyle.Render("Path:"), " ", valueStyle.Render(p.permission.Path))," ",}-+// Create the header content first so it can be used in all casesheaderContent := lipgloss.NewStyle().Padding(0, 1).Render(lipgloss.JoinVertical(lipgloss.Left, headerParts...))-+r, _ := glamour.NewTermRenderer(glamour.WithStyles(styles.CatppuccinMarkdownStyle()),glamour.WithWordWrap(p.width-10),glamour.WithEmoji(),)-+// Handle different tool typesswitch p.permission.ToolName {case tools.BashToolName:pr := p.permission.Params.(tools.BashPermissionsParams)headerParts = append(headerParts, keyStyle.Render("Command:"))content := fmt.Sprintf("```bash\n%s\n```", pr.Command)-+renderedContent, _ := r.Render(content)p.contentViewPort.Width = p.width - 2 - 2-+// Calculate content height dynamically based on contentcontentLines := len(strings.Split(renderedContent, "\n"))// Set a reasonable min/max for the viewport heightminContentHeight := 3maxContentHeight := p.height - lipgloss.Height(headerContent) - lipgloss.Height(form) - 2 - 2 - 1-+// Add some padding to the content linescontentHeight := contentLines + 2contentHeight = max(contentHeight, minContentHeight)contentHeight = min(contentHeight, maxContentHeight)p.contentViewPort.Height = contentHeight-+p.contentViewPort.SetContent(renderedContent)-+// Style the viewportvar contentBorder lipgloss.Bordervar borderColor lipgloss.TerminalColor-+if p.isViewportFocus {contentBorder = lipgloss.DoubleBorder()borderColor = styles.Blue@@ -207,47 +207,47 @@ func (p *permissionDialogCmp) render() string {contentBorder = lipgloss.RoundedBorder()borderColor = styles.Flamingo}-+contentStyle := lipgloss.NewStyle().MarginTop(1).Padding(0, 1).Border(contentBorder).BorderForeground(borderColor)-+if p.isViewportFocus {contentStyle = contentStyle.BorderBackground(styles.Surface0)}-+contentFinal := contentStyle.Render(p.contentViewPort.View())-+return lipgloss.JoinVertical(lipgloss.Top,headerContent,contentFinal,form,)-+case tools.EditToolName:pr := p.permission.Params.(tools.EditPermissionsParams)headerParts = append(headerParts, keyStyle.Render("Update"))// Recreate header content with the updated headerPartsheaderContent = lipgloss.NewStyle().Padding(0, 1).Render(lipgloss.JoinVertical(lipgloss.Left, headerParts...))-+// Format the diff with colorsformattedDiff := formatDiff(pr.Diff)-+// Set up viewport for the diff contentp.contentViewPort.Width = p.width - 2 - 2-+// Calculate content height dynamically based on window sizemaxContentHeight := p.height - lipgloss.Height(headerContent) - lipgloss.Height(form) - 2 - 2 - 1p.contentViewPort.Height = maxContentHeightp.contentViewPort.SetContent(formattedDiff)-+// Style the viewportvar contentBorder lipgloss.Bordervar borderColor lipgloss.TerminalColor-+if p.isViewportFocus {contentBorder = lipgloss.DoubleBorder()borderColor = styles.Blue@@ -255,47 +255,47 @@ func (p *permissionDialogCmp) render() string {contentBorder = lipgloss.RoundedBorder()borderColor = styles.Flamingo}-+contentStyle := lipgloss.NewStyle().MarginTop(1).Padding(0, 1).Border(contentBorder).BorderForeground(borderColor)-+if p.isViewportFocus {contentStyle = contentStyle.BorderBackground(styles.Surface0)}-+contentFinal := contentStyle.Render(p.contentViewPort.View())-+return lipgloss.JoinVertical(lipgloss.Top,headerContent,contentFinal,form,)-+case tools.WriteToolName:pr := p.permission.Params.(tools.WritePermissionsParams)headerParts = append(headerParts, keyStyle.Render("Content"))// Recreate header content with the updated headerPartsheaderContent = lipgloss.NewStyle().Padding(0, 1).Render(lipgloss.JoinVertical(lipgloss.Left, headerParts...))-+// Format the diff with colorsformattedDiff := formatDiff(pr.Content)-+// Set up viewport for the contentp.contentViewPort.Width = p.width - 2 - 2-+// Calculate content height dynamically based on window sizemaxContentHeight := p.height - lipgloss.Height(headerContent) - lipgloss.Height(form) - 2 - 2 - 1p.contentViewPort.Height = maxContentHeightp.contentViewPort.SetContent(formattedDiff)-+// Style the viewportvar contentBorder lipgloss.Bordervar borderColor lipgloss.TerminalColor-+if p.isViewportFocus {contentBorder = lipgloss.DoubleBorder()borderColor = styles.Blue@@ -303,75 +303,75 @@ func (p *permissionDialogCmp) render() string {contentBorder = lipgloss.RoundedBorder()borderColor = styles.Flamingo}-+contentStyle := lipgloss.NewStyle().MarginTop(1).Padding(0, 1).Border(contentBorder).BorderForeground(borderColor)-+if p.isViewportFocus {contentStyle = contentStyle.BorderBackground(styles.Surface0)}-+contentFinal := contentStyle.Render(p.contentViewPort.View())-+return lipgloss.JoinVertical(lipgloss.Top,headerContent,contentFinal,form,)-+case tools.FetchToolName:pr := p.permission.Params.(tools.FetchPermissionsParams)headerParts = append(headerParts, keyStyle.Render("URL: "+pr.URL))content := p.permission.Description-+renderedContent, _ := r.Render(content)p.contentViewPort.Width = p.width - 2 - 2p.contentViewPort.Height = p.height - lipgloss.Height(headerContent) - lipgloss.Height(form) - 2 - 2 - 1p.contentViewPort.SetContent(renderedContent)-+// Style the viewportcontentStyle := lipgloss.NewStyle().MarginTop(1).Padding(0, 1).Border(lipgloss.RoundedBorder()).BorderForeground(styles.Flamingo)-+contentFinal := contentStyle.Render(p.contentViewPort.View())if renderedContent == "" {contentFinal = ""}-+return lipgloss.JoinVertical(lipgloss.Top,headerContent,contentFinal,form,)-+default:content := p.permission.Description-+renderedContent, _ := r.Render(content)p.contentViewPort.Width = p.width - 2 - 2p.contentViewPort.Height = p.height - lipgloss.Height(headerContent) - lipgloss.Height(form) - 2 - 2 - 1p.contentViewPort.SetContent(renderedContent)-+// Style the viewportcontentStyle := lipgloss.NewStyle().MarginTop(1).Padding(0, 1).Border(lipgloss.RoundedBorder()).BorderForeground(styles.Flamingo)-+contentFinal := contentStyle.Render(p.contentViewPort.View())if renderedContent == "" {contentFinal = ""}-+return lipgloss.JoinVertical(lipgloss.Top,headerContent,diff --git a/internal/tui/components/repl/editor.go b/internal/tui/components/repl/editor.goindex cce966ca78a..d3e8d2c788d 100644--- a/internal/tui/components/repl/editor.go+++ b/internal/tui/components/repl/editor.go@@ -140,7 +140,7 @@ func (m *editorCmp) Send() tea.Cmd {return func() tea.Msg {messages, _ := m.app.Messages.List(m.sessionID)if hasUnfinishedMessages(messages) {- return util.InfoMsg("Assistant is still working on the previous message")+ return util.ReportWarn("Assistant is still working on the previous message")}a, _ := agent.NewCoderAgent(m.app)diff --git a/internal/tui/tui.go b/internal/tui/tui.goindex 8785b5ab230..0845b624509 100644--- a/internal/tui/tui.go+++ b/internal/tui/tui.go@@ -77,6 +77,8 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {switch msg := msg.(type) {case pubsub.Event[permission.PermissionRequest]:return a, dialog.NewPermissionDialogCmd(msg.Payload)+ case pubsub.Event[util.InfoMsg]:+ a.status, _ = a.status.Update(msg)case dialog.PermissionResponseMsg:switch msg.Action {case dialog.PermissionAllow:@@ -121,8 +123,6 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {return a, a.moveToPage(msg.ID)case util.InfoMsg:a.status, _ = a.status.Update(msg)- case util.ErrorMsg:- a.status, _ = a.status.Update(msg)case tea.KeyMsg:if a.editorMode == vimtea.ModeNormal {switch {@@ -141,7 +141,7 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {if a.currentPage == page.ReplPage {sessions, err := a.app.Sessions.List()if err != nil {- return a, util.CmdHandler(util.ErrorMsg(err))+ return a, util.CmdHandler(util.ReportError(err))}lastSession := sessions[0]if lastSession.MessageCount == 0 {@@ -149,7 +149,7 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {}s, err := a.app.Sessions.Create("New Session")if err != nil {- return a, util.CmdHandler(util.ErrorMsg(err))+ return a, util.CmdHandler(util.ReportError(err))}return a, util.CmdHandler(repl.SelectedSessionMsg{SessionID: s.ID})}diff --git a/internal/tui/util/util.go b/internal/tui/util/util.goindex f6cf20d6052..e006cbb432b 100644--- a/internal/tui/util/util.go+++ b/internal/tui/util/util.go@@ -9,12 +9,39 @@ func CmdHandler(msg tea.Msg) tea.Cmd {}func ReportError(err error) tea.Cmd {- return CmdHandler(ErrorMsg(err))+ return CmdHandler(InfoMsg{+ Type: InfoTypeError,+ Msg: err.Error(),+ })+}++type InfoType int++const (+ InfoTypeInfo InfoType = iota+ InfoTypeWarn+ InfoTypeError+)++func ReportInfo(info string) tea.Cmd {+ return CmdHandler(InfoMsg{+ Type: InfoTypeInfo,+ Msg: info,+ })+}++func ReportWarn(warn string) tea.Cmd {+ return CmdHandler(InfoMsg{+ Type: InfoTypeWarn,+ Msg: warn,+ })}type (- InfoMsg string- ErrorMsg error+ InfoMsg struct {+ Type InfoType+ Msg string+ }ClearStatusMsg struct{})