xonecas.io
6119
My

mysis / files

mysis / internal / tui / app.go

8.0 KB
1// Package tui provides the terminal user interface for Mysis.
2package tui
3
4import (
5	"context"
6	"fmt"
7	"strings"
8	"sync"
9
10	"github.com/charmbracelet/bubbles/key"
11	tea "github.com/charmbracelet/bubbletea"
12	"github.com/charmbracelet/lipgloss"
13	"github.com/rs/zerolog/log"
14	"github.com/xonecas/mysis/internal/provider"
15	"github.com/xonecas/mysis/internal/styles"
16)
17
18// Model is the main TUI model.
19type Model struct {
20	conversation Conversation
21	input        Input
22	statusBar    StatusBar
23
24	width  int
25	height int
26
27	// State
28	autoplayActive  bool
29	autoplayMessage string
30	lastError       string
31
32	// Callback to send messages
33	onSendMessage func(string) error
34
35	// Callback to execute commands
36	onCommand func(string) error
37
38	// Synchronization for conversation history access
39	// Shared with Runner to protect concurrent access from background goroutines
40	historyMu *sync.Mutex
41
42	ready bool
43	ctx   context.Context
44}
45
46// NewModel creates a new TUI model.
47func NewModel(ctx context.Context) Model {
48	return Model{
49		ctx:          ctx,
50		conversation: NewConversation(80, 20),
51		input:        NewInput(80),
52		statusBar:    NewStatusBar(80),
53	}
54}
55
56// SetOnSendMessage sets the callback for sending messages.
57func (m *Model) SetOnSendMessage(fn func(string) error) {
58	m.onSendMessage = fn
59}
60
61// SetOnCommand sets the callback for executing commands.
62func (m *Model) SetOnCommand(fn func(string) error) {
63	m.onCommand = fn
64}
65
66// Init initializes the model.
67func (m Model) Init() tea.Cmd {
68	return tea.Batch(
69		m.statusBar.Init(),
70		m.input.Focus(),
71	)
72}
73
74// Update handles messages and updates the model.
75func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
76	var cmds []tea.Cmd
77
78	switch msg := msg.(type) {
79	case tea.WindowSizeMsg:
80		m.width = msg.Width
81		m.height = msg.Height
82
83		// Calculate component heights
84		// Layout: Conversation (fills) + Input (3 lines) + Status (2 lines)
85		inputHeight := 3
86		statusHeight := 1
87		conversationHeight := m.height - inputHeight - statusHeight
88		if conversationHeight < 5 {
89			conversationHeight = 5
90		}
91
92		m.conversation.SetSize(m.width, conversationHeight)
93		m.input.SetWidth(m.width)
94		m.statusBar.SetWidth(m.width)
95
96		m.ready = true
97
98	case tea.KeyMsg:
99		// Global keys
100		switch {
101		case key.Matches(msg, keys.Quit):
102			return m, tea.Quit
103
104		case key.Matches(msg, keys.Escape):
105			// ESC stops autoplay if active
106			if m.autoplayActive {
107				// Stop autoplay in backend
108				if m.onCommand != nil {
109					_ = m.onCommand("/autoplay stop")
110				}
111				// Update local state
112				m.autoplayActive = false
113				m.statusBar.ClearAutoplayText()
114			}
115			return m, nil
116
117		case key.Matches(msg, keys.Enter):
118			// Send message or execute command
119			value := strings.TrimSpace(m.input.Value())
120			if value != "" {
121				m.input.AddToHistory(value)
122				m.input.Reset()
123
124				// Check if it's a command
125				if strings.HasPrefix(value, "/") {
126					return m, m.executeCommand(value)
127				}
128
129				// Regular message
130				return m, m.sendMessage(value)
131			}
132			return m, nil
133		}
134
135		// Pass to input for editing
136		var cmd tea.Cmd
137		m.input, cmd = m.input.Update(msg)
138		cmds = append(cmds, cmd)
139
140	case tea.MouseMsg:
141		// Pass mouse events to conversation for scrolling
142		var updated bool
143		m.conversation, updated = m.conversation.Update(msg)
144		if updated {
145			return m, nil
146		}
147
148	case StatusBarTickMsg:
149		// Update status bar animation
150		var cmd tea.Cmd
151		m.statusBar, cmd = m.statusBar.Update(msg)
152		cmds = append(cmds, cmd)
153
154	case MessageReceivedMsg:
155		// Add message to conversation (protected by mutex for concurrent access)
156		m.historyMu.Lock()
157		m.conversation.AddMessage(msg.Message)
158		m.historyMu.Unlock()
159		cmds = append(cmds, m.statusBar.AnimateInfo())
160		m.statusBar.ClearError()
161
162	case ConversationUpdateMsg:
163		// Trigger re-render of conversation (messages already added elsewhere)
164		m.historyMu.Lock()
165		m.conversation.updateContent()
166		m.historyMu.Unlock()
167		cmds = append(cmds, m.statusBar.AnimateInfo())
168		m.statusBar.ClearError()
169
170	case ErrorMsg:
171		// Show error in status bar
172		m.lastError = msg.Error
173		cmds = append(cmds, m.statusBar.SetError(truncate(msg.Error, 100)))
174		m.statusBar.ClearWarning() // Error takes priority
175
176	case WarningMsg:
177		// Show warning in status bar
178		cmds = append(cmds, m.statusBar.SetWarning(truncate(msg.Warning, 100)))
179
180	case AutoplayStartedMsg:
181		m.autoplayActive = true
182		m.autoplayMessage = msg.Message
183		cmds = append(cmds, m.statusBar.SetAutoplayText(truncate(msg.Message, 50)))
184
185	case AutoplayStoppedMsg:
186		m.autoplayActive = false
187		m.statusBar.ClearAutoplayText()
188
189	case LLMActivityMsg:
190		// Animate LLM connection icon
191		cmds = append(cmds, m.statusBar.AnimateLLM())
192
193	case MCPActivityMsg:
194		// Animate MCP connection icon
195		cmds = append(cmds, m.statusBar.AnimateMCP())
196	}
197
198	return m, tea.Batch(cmds...)
199}
200
201// View renders the UI.
202func (m Model) View() string {
203	if !m.ready {
204		return "Initializing..."
205	}
206
207	// Check minimum terminal size
208	const minWidth = 80
209	const minHeight = 20
210	if m.width < minWidth || m.height < minHeight {
211		warning := fmt.Sprintf(
212			"Terminal too small!\n\nMinimum: %dx%d\nCurrent: %dx%d\n\nPlease resize.",
213			minWidth, minHeight, m.width, m.height,
214		)
215		return ErrorMsg{Error: warning}.Error
216	}
217
218	// Build UI content first
219	conversation := m.conversation.View()
220	input := m.input.View()
221	status := m.statusBar.View()
222
223	// Join all sections
224	content := conversation + "\n" + input + "\n" + status
225
226	// Apply base style with background to fill entire terminal
227	// This is the recommended way per bubbletea docs
228	baseStyle := lipgloss.NewStyle().
229		Background(styles.ColorBg).
230		Width(m.width).
231		Height(m.height)
232
233	return baseStyle.Render(content)
234}
235
236// sendMessage sends a message through the callback.
237func (m Model) sendMessage(content string) tea.Cmd {
238	return func() tea.Msg {
239		if m.onSendMessage == nil {
240			return ErrorMsg{Error: "no message handler configured"}
241		}
242
243		if err := m.onSendMessage(content); err != nil {
244			log.Error().Err(err).Msg("Failed to send message")
245			return ErrorMsg{Error: err.Error()}
246		}
247
248		return nil
249	}
250}
251
252// executeCommand executes a slash command.
253func (m Model) executeCommand(cmd string) tea.Cmd {
254	return func() tea.Msg {
255		// Handle built-in commands
256		parts := strings.Fields(cmd)
257		if len(parts) == 0 {
258			return nil
259		}
260
261		switch parts[0] {
262		case "/autoplay":
263			// Pass to runner for backend execution
264			if m.onCommand != nil {
265				if err := m.onCommand(cmd); err != nil {
266					return ErrorMsg{Error: err.Error()}
267				}
268			}
269			return nil
270
271		case "/exit", "/quit":
272			return tea.Quit()
273
274		default:
275			// Pass to external command handler
276			if m.onCommand != nil {
277				if err := m.onCommand(cmd); err != nil {
278					return ErrorMsg{Error: err.Error()}
279				}
280			}
281		}
282
283		return nil
284	}
285}
286
287// AddMessage adds a message to the conversation (called from external code).
288func (m *Model) AddMessage(msg provider.Message) {
289	m.conversation.AddMessage(msg)
290}
291
292// SetMessages sets all conversation messages.
293func (m *Model) SetMessages(messages []provider.Message) {
294	m.conversation.SetMessages(messages)
295}
296
297// Key bindings
298var keys = struct {
299	Quit   key.Binding
300	Escape key.Binding
301	Enter  key.Binding
302}{
303	Quit:   key.NewBinding(key.WithKeys("ctrl+c")),
304	Escape: key.NewBinding(key.WithKeys("esc")),
305	Enter:  key.NewBinding(key.WithKeys("enter")),
306}
307
308// Message types for external communication
309type (
310	// MessageReceivedMsg is sent when a new message is received.
311	MessageReceivedMsg struct {
312		Message provider.Message
313	}
314
315	// ConversationUpdateMsg triggers a re-render without adding messages (already added).
316	ConversationUpdateMsg struct{}
317
318	// ErrorMsg is sent when an error occurs.
319	ErrorMsg struct {
320		Error string
321	}
322
323	// WarningMsg is sent when a warning occurs.
324	WarningMsg struct {
325		Warning string
326	}
327
328	// AutoplayStartedMsg is sent when autoplay starts.
329	AutoplayStartedMsg struct {
330		Message string
331	}
332
333	// AutoplayStoppedMsg is sent when autoplay stops.
334	AutoplayStoppedMsg struct{}
335
336	// LLMActivityMsg is sent when LLM activity occurs.
337	LLMActivityMsg struct{}
338
339	// MCPActivityMsg is sent when MCP activity occurs.
340	MCPActivityMsg struct{}
341)
342
343// Helper functions
344
345func truncate(s string, maxLen int) string {
346	if len(s) <= maxLen {
347		return s
348	}
349	return s[:maxLen-3] + "..."
350}