xonecas.io
6119
My

mysis / files

mysis / internal / tui / conversation.go

6.5 KB
1package tui
2
3import (
4	"encoding/json"
5	"fmt"
6	"strings"
7
8	"github.com/charmbracelet/bubbles/viewport"
9	"github.com/charmbracelet/lipgloss"
10	"github.com/xonecas/mysis/internal/provider"
11	"github.com/xonecas/mysis/internal/styles"
12)
13
14// Conversation manages the conversation log viewport.
15type Conversation struct {
16	viewport viewport.Model
17	messages []provider.Message
18	width    int
19	height   int
20}
21
22// NewConversation creates a new conversation viewport.
23func NewConversation(width, height int) Conversation {
24	vp := viewport.New(width, height)
25	vp.Style = LogStyle
26
27	// Ensure viewport fills with background color
28	vp.SetContent("")
29
30	return Conversation{
31		viewport: vp,
32		messages: []provider.Message{},
33		width:    width,
34		height:   height,
35	}
36}
37
38// SetSize updates the viewport size.
39func (c *Conversation) SetSize(width, height int) {
40	c.width = width
41	c.height = height
42	c.viewport.Width = width
43	c.viewport.Height = height
44	// Re-render content with new width
45	c.updateContent()
46}
47
48// SetMessages updates the conversation messages and re-renders.
49func (c *Conversation) SetMessages(messages []provider.Message) {
50	c.messages = messages
51	c.updateContent()
52}
53
54// AddMessage appends a message and re-renders.
55func (c *Conversation) AddMessage(msg provider.Message) {
56	c.messages = append(c.messages, msg)
57	c.updateContent()
58}
59
60// updateContent renders all messages and sets viewport content.
61func (c *Conversation) updateContent() {
62	if len(c.messages) == 0 {
63		c.viewport.SetContent(DimmedStyle.Render("No conversation history."))
64		return
65	}
66
67	// Remember if user was at bottom before updating
68	wasAtBottom := c.viewport.AtBottom()
69
70	var lines []string
71	for _, msg := range c.messages {
72		lines = append(lines, c.renderMessage(msg)...)
73		// Blank line with background - must fill width
74		blankStyle := lipgloss.NewStyle().
75			Background(styles.ColorBg).
76			Width(c.width)
77		lines = append(lines, blankStyle.Render(""))
78	}
79
80	content := strings.Join(lines, "\n")
81	c.viewport.SetContent(content)
82
83	// Auto-scroll to bottom if user was already there
84	if wasAtBottom {
85		c.viewport.GotoBottom()
86	}
87}
88
89// renderMessage renders a single message with role, content, and tool calls.
90func (c Conversation) renderMessage(msg provider.Message) []string {
91	var lines []string
92
93	// Timestamp first, then role label
94	var roleLabelText string
95
96	// Add timestamp if present
97	if !msg.CreatedAt.IsZero() {
98		timestamp := msg.CreatedAt.Format("15:04:05")
99		timestampStyled := DimmedStyle.Render("[" + timestamp + "] ")
100		roleLabelText = timestampStyled
101	}
102
103	// Add role label
104	roleLabelText += RoleLabel(msg.Role)
105
106	roleLineStyle := lipgloss.NewStyle().
107		Background(styles.ColorBg).
108		Width(c.width)
109	lines = append(lines, roleLineStyle.Render(roleLabelText))
110
111	// Reasoning (if present, for assistant messages)
112	if msg.Reasoning != "" {
113		reasoningLines := c.renderReasoning(msg.Reasoning)
114		lines = append(lines, reasoningLines...)
115	}
116
117	// Content (if present)
118	if msg.Content != "" {
119		contentLines := c.renderContent(msg.Content, msg.Role)
120		lines = append(lines, contentLines...)
121	}
122
123	// Tool calls (if present)
124	if len(msg.ToolCalls) > 0 {
125		toolLines := c.renderToolCalls(msg.ToolCalls)
126		lines = append(lines, toolLines...)
127	}
128
129	return lines
130}
131
132// truncateContent truncates content similar to CLI behavior.
133// - Tool results: truncated to 100 chars
134// - Reasoning: truncated to 200 chars
135// - Regular content: no truncation (but word-wrapped)
136func (c Conversation) truncateContent(content string, role string) string {
137	// Tool results get truncated aggressively (like CLI)
138	if role == "tool" {
139		if len(content) > 100 {
140			return content[:97] + "..."
141		}
142		return content
143	}
144
145	// No truncation for other roles, just return as-is
146	// (word wrapping handles long content)
147	return content
148}
149
150// renderReasoning renders reasoning/thinking content with truncation.
151// Per design spec: truncate from end (show last 200 chars), no word wrap.
152func (c Conversation) renderReasoning(reasoning string) []string {
153	// Trim and collapse whitespace
154	reasoning = strings.TrimSpace(reasoning)
155	reasoning = strings.Join(strings.Fields(reasoning), " ")
156
157	// Truncate from end if too long (keep last 200 chars)
158	if len(reasoning) > 200 {
159		reasoning = "..." + reasoning[len(reasoning)-197:]
160	}
161
162	// Apply dimmed style with symbol prefix
163	style := DimmedStyle.Width(c.width)
164	return []string{style.Render("  ∴ " + reasoning)}
165}
166
167// renderContent renders message content with truncation but no word wrap per design spec.
168func (c Conversation) renderContent(content string, role string) []string {
169	// Truncate content based on role (like CLI does)
170	truncated := c.truncateContent(content, role)
171
172	// Apply role style with background to entire line including padding
173	// Set width to fill the viewport so background extends to edge
174	// No word wrap per design spec: "No word wrap for reasoning, user messages, or agent replies"
175	style := RoleStyle(role).Width(c.width)
176
177	// Split by newlines only (no word wrapping)
178	splitLines := strings.Split(truncated, "\n")
179	lines := make([]string, 0, len(splitLines))
180	for _, line := range splitLines {
181		// Render padding + content with full width so background fills line
182		lines = append(lines, style.Render("  "+line))
183	}
184
185	return lines
186}
187
188// renderToolCalls renders tool calls in a compact format.
189func (c Conversation) renderToolCalls(toolCalls []provider.ToolCall) []string {
190	lines := make([]string, 0, len(toolCalls))
191
192	for _, tc := range toolCalls {
193		// Build tool line content
194		content := fmt.Sprintf("  ⚙ %s", tc.Name)
195
196		// Arguments (truncated)
197		var args map[string]interface{}
198		if err := json.Unmarshal(tc.Arguments, &args); err == nil {
199			argsJSON, _ := json.Marshal(args)
200			argsStr := string(argsJSON)
201			if len(argsStr) > 60 {
202				argsStr = argsStr[:57] + "..."
203			}
204			content += " " + argsStr
205		}
206
207		// Render with width so background fills line
208		toolStyle := ToolStyle.Width(c.width)
209		lines = append(lines, toolStyle.Render(content))
210	}
211
212	return lines
213}
214
215// Update handles viewport updates (scrolling, etc).
216func (c Conversation) Update(msg interface{}) (Conversation, bool) {
217	c.viewport, _ = c.viewport.Update(msg)
218	return c, false
219}
220
221// View renders the conversation viewport.
222func (c Conversation) View() string {
223	// The viewport already has LogStyle which includes background
224	// Just return it directly - the parent will handle sizing
225	return c.viewport.View()
226}
227
228// GotoBottom scrolls to the bottom.
229func (c *Conversation) GotoBottom() {
230	c.viewport.GotoBottom()
231}
232
233// ScrollPercent returns the current scroll percentage.
234func (c Conversation) ScrollPercent() float64 {
235	return c.viewport.ScrollPercent()
236}