xonecas.io
60255
Zn

Zoea-Nova / files

Zoea-Nova / internal / tui / dashboard.go

18.8 KB
1package tui
2
3import (
4	"encoding/json"
5	"fmt"
6	"sort"
7	"strings"
8	"time"
9
10	"github.com/charmbracelet/lipgloss"
11	"github.com/xonecas/zoea-nova/internal/constants"
12	"github.com/xonecas/zoea-nova/internal/core"
13	"github.com/xonecas/zoea-nova/internal/store"
14)
15
16const (
17	// Mysis list row prefix widths
18	cursorDisplayWidth         = 4 // "[→ ]" with backgrounds
19	stateIndicatorDisplayWidth = 1 // Single Unicode character
20	rowPrefixSpacing           = 3 // Spaces around indicator (1 before + 2 after)
21)
22
23// MysisInfo holds display info for a mysis.
24type MysisInfo struct {
25	ID              string
26	Name            string
27	State           string
28	Activity        string // Current activity (idle, llm_call, mcp_call, traveling, etc.)
29	Provider        string
30	AccountUsername string          // NEW: game account username
31	LastMessage     string          // Most recent message (user or assistant) - DEPRECATED, kept for compatibility
32	LastMessageAt   time.Time       // Timestamp of most recent message
33	RecentMemories  []*store.Memory // Recent memories for message row formatting
34	CreatedAt       time.Time       // When mysis was created
35	LastError       string          // Last error string (if errored)
36}
37
38// SwarmMessageInfo holds display info for a broadcast message.
39type SwarmMessageInfo struct {
40	SenderID   string
41	SenderName string
42	Content    string
43	CreatedAt  time.Time
44}
45
46// RenderDashboard renders the main dashboard view.
47func RenderDashboard(myses []MysisInfo, swarmMessages []SwarmMessageInfo, selectedIdx int, width, height int, loadingSet map[string]bool, spinnerView string, currentTick int64, err error) string {
48	var sections []string
49
50	// Header - retro-futuristic command center banner with hexagonal motif (matching logo)
51	if width < 20 {
52		width = 20
53	}
54
55	// Define custom border with empty sides but diamonds in corners
56	// We enable all borders to get the corners, but set sides to empty strings
57	headerBorder := lipgloss.Border{
58		Top:         "═",
59		Bottom:      "═",
60		Left:        " ",
61		Right:       " ",
62		TopLeft:     "⬥",
63		TopRight:    "⬥",
64		BottomLeft:  "⬥",
65		BottomRight: "⬥",
66	}
67
68	headerStyle := lipgloss.NewStyle().
69		Bold(true).
70		Foreground(colorBrand).
71		Background(colorBgAlt).
72		Width(width-2). // Subtract 2 for the corner characters
73		Align(lipgloss.Center).
74		Border(headerBorder, true, true, true, true).
75		BorderForeground(colorBrand)
76
77	titleText := "⬡ Z O E A   N O V A ⬡   COMMAND CENTER"
78	header := headerStyle.Render(titleText)
79	sections = append(sections, header)
80
81	// Swarm message history - always visible with fixed height
82	swarmHeader := renderSectionTitle("SWARM BROADCAST", width)
83	sections = append(sections, swarmHeader)
84
85	const maxSwarmMessages = 10
86	var msgLines []string
87	if len(swarmMessages) == 0 {
88		// Show placeholder when empty
89		msgLines = append(msgLines, dimmedStyle.Render("No broadcasts yet. Press 'b' to broadcast."))
90	} else {
91		// Show up to maxSwarmMessages (most recent first)
92		displayCount := len(swarmMessages)
93		if displayCount > maxSwarmMessages {
94			displayCount = maxSwarmMessages
95		}
96		for i := 0; i < displayCount; i++ {
97			msg := swarmMessages[i]
98			timeStr := formatTickTimestamp(currentTick, msg.CreatedAt)
99			senderLabel := formatSenderLabel(msg.SenderID, msg.SenderName)
100			senderText := ""
101			if senderLabel != "" {
102				senderText = " [" + senderLabel + "]"
103			}
104			content := strings.ReplaceAll(msg.Content, "\n", " ")
105			maxLen := width - 15 - lipgloss.Width(senderText)
106			if maxLen < 1 {
107				maxLen = 1
108			}
109			if lipgloss.Width(content) > maxLen {
110				if maxLen > 3 {
111					content = truncateToWidth(content, maxLen-3) + "..."
112				} else {
113					content = truncateToWidth(content, maxLen)
114				}
115			}
116			line := fmt.Sprintf("%s%s %s", dimmedStyle.Render(timeStr), highlightStyle.Render(senderText), content)
117			msgLines = append(msgLines, line)
118		}
119	}
120	swarmContent := strings.Join(msgLines, "\n")
121	sections = append(sections, swarmContent)
122
123	// Mysis list header
124	mysisHeader := renderSectionTitle("MYSIS SWARM", width)
125	sections = append(sections, mysisHeader)
126
127	// Calculate height used by other elements to fill remaining space
128	// Header: 3 lines + margin, Swarm: header + content, Mysis header: 1 line, Footer: 1 line
129	usedHeight := 5 // header (3 + margin) + mysis header (1) + footer (1)
130	// Swarm section: header (1) + content lines (at least 1 for placeholder or messages)
131	usedHeight += 1 + len(msgLines)
132	// Account for panel borders (top + bottom = 2 lines)
133	usedHeight += 2
134
135	mysisListHeight := height - usedHeight
136	// Each mysis takes 2 lines (info + message), minimum 4 lines for 2 rows
137	if mysisListHeight < 4 {
138		mysisListHeight = 4
139	}
140
141	// Mysis list - DoubleBorder adds 2 chars each side, so content width is width-4
142	contentWidth := width - 4
143	if contentWidth < 20 {
144		contentWidth = 20
145	}
146
147	if len(myses) == 0 {
148		emptyMsg := dimmedStyle.Render("No myses. Press 'n' to create one.")
149		mysisList := mysisListStyle.Width(width - 2).Height(mysisListHeight).Render(emptyMsg)
150		sections = append(sections, mysisList)
151	} else {
152		var mysisLines []string
153		for i, m := range myses {
154			isLoading := loadingSet[m.ID]
155			lines := renderMysisLine(m, i == selectedIdx, isLoading, spinnerView, contentWidth, currentTick)
156			// lines[0] = info row, lines[1] = message row
157			mysisLines = append(mysisLines, lines[0])
158			mysisLines = append(mysisLines, lines[1])
159		}
160		content := strings.Join(mysisLines, "\n")
161		mysisList := mysisListStyle.Width(width - 2).Height(mysisListHeight).Render(content)
162		sections = append(sections, mysisList)
163	}
164
165	// Footer with hint and error status
166	hint := renderHintWithError("[ ? ] HELP  ·  [ n ] NEW MYSIS  ·  [ b ] BROADCAST", err, width)
167	sections = append(sections, hint)
168
169	return lipgloss.JoinVertical(lipgloss.Left, sections...)
170}
171
172func renderMysisLine(m MysisInfo, selected, isLoading bool, spinnerView string, width int, currentTick int64) []string {
173	// Build info row (first line)
174	infoRow := buildInfoRow(m, selected, isLoading, spinnerView, width)
175
176	// Build message row (second line)
177	messageRow := buildMessageRow(m, width, currentTick)
178
179	return []string{infoRow, messageRow}
180}
181
182func buildInfoRow(m MysisInfo, selected, isLoading bool, spinnerView string, width int) string {
183	// State indicator: activity-specific for running myses, static for others
184	var stateIndicator string
185	if isLoading {
186		stateIndicator = spinnerView
187	} else {
188		switch m.State {
189		case "running":
190			// Show activity-specific indicator for running myses
191			switch m.Activity {
192			case "llm_call":
193				// Purple ellipsis for LLM thinking
194				stateIndicator = lipgloss.NewStyle().Foreground(colorBrand).Render("⋯")
195			case "mcp_call":
196				// Teal gear for MCP tool execution
197				stateIndicator = lipgloss.NewStyle().Foreground(colorTeal).Render("⚙")
198			case "traveling":
199				// Teal arrow for traveling
200				stateIndicator = lipgloss.NewStyle().Foreground(colorTeal).Render("→")
201			case "mining":
202				// Yellow pickaxe for mining
203				stateIndicator = lipgloss.NewStyle().Foreground(lipgloss.Color("#FFCC00")).Render("⛏")
204			case "in_combat":
205				// Red crossed swords for combat
206				stateIndicator = lipgloss.NewStyle().Foreground(lipgloss.Color("#FF0000")).Render("⚔")
207			case "cooldown":
208				// Dimmed hourglass for cooldown
209				stateIndicator = lipgloss.NewStyle().Foreground(lipgloss.Color("#888888")).Render("⏳")
210			default:
211				// Default spinner for idle or unknown activity
212				stateIndicator = spinnerView
213			}
214		case "idle":
215			stateIndicator = stateIdleStyle.Render("◦")
216		case "stopped":
217			stateIndicator = stateStoppedStyle.Render("◌")
218		case "errored":
219			stateIndicator = stateErroredStyle.Render("✖")
220		default:
221			stateIndicator = "?"
222		}
223	}
224
225	// Build line - use display width for truncation
226	name := m.Name
227	if lipgloss.Width(name) > 8 {
228		name = truncateToWidth(name, 5) + "..."
229	}
230
231	// Format provider without brackets and pad to 12 chars
232	providerFormatted := m.Provider
233	if lipgloss.Width(providerFormatted) > 12 {
234		providerFormatted = truncateToWidth(providerFormatted, 9) + "..."
235	}
236	providerFormatted = fmt.Sprintf("%-12s", providerFormatted)
237	provider := dimmedStyle.Render(providerFormatted)
238
239	stateText := StateStyle(m.State).Render(fmt.Sprintf("%-8s", m.State))
240
241	// Account username display - fixed width 12 chars
242	var accountFormatted string
243	if m.AccountUsername != "" {
244		accountFormatted = fmt.Sprintf("@%s", m.AccountUsername)
245	} else {
246		accountFormatted = "logged out"
247	}
248	// Truncate if longer than 12 chars
249	if lipgloss.Width(accountFormatted) > 12 {
250		accountFormatted = truncateToWidth(accountFormatted, 9) + "..."
251	}
252	// Pad to 12 chars
253	accountFormatted = fmt.Sprintf("%-12s", accountFormatted)
254	accountText := dimmedStyle.Render(accountFormatted)
255
256	// Content part: name + provider + state + account (NO message content)
257	// Order: name (8) + space + provider (12) + space + state (8) + space + account (12)
258	contentPart := fmt.Sprintf("%-8s %s %s %s", name, provider, stateText, accountText)
259
260	// Calculate prefix width
261	// Format: "[→ ] ⠋  " or "[  ] ⠋  " = 4 (bracket) + 1 (space) + 1 (indicator) + 2 (spaces) = 8 chars total
262	prefixWidth := cursorDisplayWidth + 1 + stateIndicatorDisplayWidth + 2
263
264	// Content width: width - prefix
265	contentStyleWidth := width - prefixWidth
266
267	if selected {
268		// Dim purple background, bright purple foreground on [→ ] (4 chars), then normal space
269		cursorStyle := lipgloss.NewStyle().Background(colorBrandDim).Foreground(colorBrand)
270		cursorBracketOpen := cursorStyle.Render("[")
271		cursorArrow := cursorStyle.Render("→")
272		cursorSpace := cursorStyle.Render(" ")
273		cursorBracketClose := cursorStyle.Render("]")
274		cursor := cursorBracketOpen + cursorArrow + cursorSpace + cursorBracketClose
275		return cursor + " " + stateIndicator + "  " + mysisItemSelectedStyle.PaddingLeft(0).PaddingRight(1).Width(contentStyleWidth).Render(contentPart)
276	}
277	// Unselected: [  ] with dim purple brackets, no background
278	unselectedBracketStyle := lipgloss.NewStyle().Foreground(colorBrandDim)
279	unselectedCursor := unselectedBracketStyle.Render("[") + "  " + unselectedBracketStyle.Render("]")
280	return unselectedCursor + " " + stateIndicator + "  " + mysisItemStyle.PaddingLeft(0).PaddingRight(1).Width(contentStyleWidth).Render(contentPart)
281}
282
283func buildMessageRow(m MysisInfo, width int, currentTick int64) string {
284	prefix := "  └─ " // 2 spaces + corner + dash + space = 5 chars
285	prefixWidth := 5
286
287	// Calculate available width for message content
288	// Subtract prefix (5) and borders (2)
289	availableWidth := width - prefixWidth - 2
290	if availableWidth < 10 {
291		availableWidth = 10
292	}
293
294	// Get message content using existing formatMessageRow
295	messageContent := formatMessageRow(m, currentTick, availableWidth)
296
297	if messageContent == "" {
298		messageContent = dimmedStyle.Render("(no recent activity)")
299	}
300
301	return dimmedStyle.Render(prefix) + messageContent
302}
303
304// formatMessageRow formats the message row based on message type and priority.
305// Priority order: 1) Errors, 2) AI replies, 3) Tool calls, 4) User messages/broadcasts
306func formatMessageRow(m MysisInfo, currentTick int64, maxWidth int) string {
307	// Priority 1: Errors (if state is errored and LastError is set)
308	if m.State == "errored" && m.LastError != "" {
309		return formatErrorMessage(m.LastError, currentTick, m.LastMessageAt, maxWidth)
310	}
311
312	// If no recent memories but we have LastMessage (backward compatibility for tests),
313	// show it as a simple message
314	if len(m.RecentMemories) == 0 {
315		if m.LastMessage != "" {
316			return formatLegacyMessage(m.LastMessage, currentTick, m.LastMessageAt, maxWidth)
317		}
318		return ""
319	}
320
321	// Priority 2: AI replies (not tool calls)
322	for _, mem := range m.RecentMemories {
323		if mem.Role == store.MemoryRoleAssistant && !strings.HasPrefix(mem.Content, constants.ToolCallStoragePrefix) {
324			return formatAIReply(mem, currentTick, maxWidth)
325		}
326	}
327
328	// Priority 3: Tool calls
329	for _, mem := range m.RecentMemories {
330		if mem.Role == store.MemoryRoleAssistant && strings.HasPrefix(mem.Content, constants.ToolCallStoragePrefix) {
331			return formatToolCall(mem, currentTick, maxWidth)
332		}
333	}
334
335	// Priority 4: User messages/broadcasts
336	for _, mem := range m.RecentMemories {
337		if mem.Role == store.MemoryRoleUser {
338			return formatUserMessage(mem, currentTick, maxWidth)
339		}
340	}
341
342	return "" // No message to display
343}
344
345// formatLegacyMessage formats a simple message (backward compatibility for tests).
346func formatLegacyMessage(msg string, currentTick int64, timestamp time.Time, maxWidth int) string {
347	prefix := ""
348	if !timestamp.IsZero() {
349		prefix = formatTickTimestamp(currentTick, timestamp) + " "
350	}
351	prefixWidth := lipgloss.Width(prefix)
352	availableWidth := maxWidth - prefixWidth
353
354	content := strings.ReplaceAll(msg, "\n", " ")
355	if lipgloss.Width(content) > availableWidth {
356		content = truncateToWidth(content, availableWidth-3) + "..."
357	}
358
359	return dimmedStyle.Render(prefix + content)
360}
361
362// formatErrorMessage formats error messages.
363func formatErrorMessage(errMsg string, currentTick int64, timestamp time.Time, maxWidth int) string {
364	prefix := "Error: "
365	if !timestamp.IsZero() {
366		prefix = formatTickTimestamp(currentTick, timestamp) + " " + prefix
367	}
368	prefixWidth := lipgloss.Width(prefix)
369	availableWidth := maxWidth - prefixWidth
370
371	msg := strings.ReplaceAll(errMsg, "\n", " ")
372	if lipgloss.Width(msg) > availableWidth {
373		msg = truncateToWidth(msg, availableWidth-3) + "..."
374	}
375
376	return dimmedStyle.Render(prefix + msg)
377}
378
379// formatAIReply formats AI assistant replies.
380func formatAIReply(mem *store.Memory, currentTick int64, maxWidth int) string {
381	prefix := formatTickTimestamp(currentTick, mem.CreatedAt) + " [AI] "
382	prefixWidth := lipgloss.Width(prefix)
383	availableWidth := maxWidth - prefixWidth
384
385	msg := strings.ReplaceAll(mem.Content, "\n", " ")
386	if lipgloss.Width(msg) > availableWidth {
387		msg = truncateToWidth(msg, availableWidth-3) + "..."
388	}
389
390	return dimmedStyle.Render(prefix + msg)
391}
392
393// formatToolCall formats tool call messages.
394func formatToolCall(mem *store.Memory, currentTick int64, maxWidth int) string {
395	// Parse tool call from storage format
396	stored := strings.TrimPrefix(mem.Content, constants.ToolCallStoragePrefix)
397	if stored == "" {
398		return ""
399	}
400
401	// Parse first tool call record
402	parts := strings.Split(stored, constants.ToolCallStorageRecordDelimiter)
403	if len(parts) == 0 {
404		return ""
405	}
406
407	fields := strings.SplitN(parts[0], constants.ToolCallStorageFieldDelimiter, constants.ToolCallStorageFieldCount)
408	if len(fields) < constants.ToolCallStorageFieldCount {
409		return ""
410	}
411
412	toolName := fields[1]
413	argsJSON := fields[2]
414
415	// Format args (remove outer braces, simplify nested structures)
416	argsFormatted := formatToolArgs(argsJSON)
417
418	// Build message: timestamp + label + function_name(args)
419	timestamp := formatTickTimestamp(currentTick, mem.CreatedAt)
420	label := lipgloss.NewStyle().Foreground(colorTool).Render("→ call")
421	funcName := lipgloss.NewStyle().Foreground(colorTool).Bold(true).Render(toolName)
422	argsStyled := lipgloss.NewStyle().Foreground(colorTool).Render("(" + argsFormatted + ")")
423
424	prefix := timestamp + " " + label + " "
425	prefixWidth := lipgloss.Width(prefix)
426	funcWidth := lipgloss.Width(toolName) + lipgloss.Width(argsFormatted) + 2 // +2 for parentheses
427
428	availableWidth := maxWidth - prefixWidth
429	if funcWidth > availableWidth {
430		// Truncate args
431		argsAvailable := availableWidth - lipgloss.Width(toolName) - 5 // -5 for "(...)"
432		if argsAvailable < 3 {
433			argsFormatted = "..."
434		} else {
435			argsFormatted = truncateToWidth(argsFormatted, argsAvailable-3) + "..."
436		}
437		argsStyled = lipgloss.NewStyle().Foreground(colorTool).Render("(" + argsFormatted + ")")
438	}
439
440	return prefix + funcName + argsStyled
441}
442
443// formatToolArgs formats tool arguments for display.
444func formatToolArgs(argsJSON string) string {
445	if argsJSON == "{}" {
446		return ""
447	}
448
449	var args map[string]interface{}
450	if err := json.Unmarshal([]byte(argsJSON), &args); err != nil {
451		return "..."
452	}
453
454	if len(args) == 0 {
455		return ""
456	}
457
458	// Sort keys for deterministic output
459	var keys []string
460	for k := range args {
461		keys = append(keys, k)
462	}
463	sort.Strings(keys)
464
465	var parts []string
466	for _, k := range keys {
467		v := args[k]
468		valStr := formatArgValue(v)
469		parts = append(parts, k+": "+valStr)
470	}
471
472	return strings.Join(parts, ", ")
473}
474
475// formatArgValue formats a single argument value.
476func formatArgValue(v interface{}) string {
477	switch v := v.(type) {
478	case string:
479		return fmt.Sprintf("%q", v)
480	case float64, int, bool:
481		return fmt.Sprintf("%v", v)
482	case map[string]interface{}:
483		return "{...}"
484	case []interface{}:
485		return "[...]"
486	default:
487		return "{...}"
488	}
489}
490
491// formatUserMessage formats user messages and broadcasts.
492func formatUserMessage(mem *store.Memory, currentTick int64, maxWidth int) string {
493	var sourceLabel string
494	if mem.Source == store.MemorySourceBroadcast {
495		sourceLabel = "[SWARM]"
496	} else {
497		sourceLabel = "[YOU]"
498	}
499
500	prefix := formatTickTimestamp(currentTick, mem.CreatedAt) + " " + sourceLabel + " "
501	prefixWidth := lipgloss.Width(prefix)
502	availableWidth := maxWidth - prefixWidth
503
504	msg := strings.ReplaceAll(mem.Content, "\n", " ")
505	if lipgloss.Width(msg) > availableWidth {
506		msg = truncateToWidth(msg, availableWidth-3) + "..."
507	}
508
509	return dimmedStyle.Render(prefix + msg)
510}
511
512// MysisInfoFromCore converts a core.Mysis to MysisInfo.
513func MysisInfoFromCore(m *core.Mysis) MysisInfo {
514	return MysisInfo{
515		ID:              m.ID(),
516		Name:            m.Name(),
517		State:           string(m.State()),
518		Activity:        string(m.ActivityState()), // NEW: copy activity state
519		Provider:        m.ProviderName(),
520		AccountUsername: m.CurrentAccountUsername(), // NEW: copy account username
521		CreatedAt:       m.CreatedAt(),
522		LastError:       formatCoreError(m.LastError()),
523	}
524}
525
526func formatCoreError(err error) string {
527	if err == nil {
528		return ""
529	}
530	return err.Error()
531}
532
533// renderHintWithError renders a hint line with optional error status on the right.
534func renderHintWithError(hintText string, err error, width int) string {
535	if err == nil {
536		return dimmedStyle.Render(hintText)
537	}
538
539	// Format error message
540	errMsg := fmt.Sprintf("Error: %v", err)
541	styledError := stateErroredStyle.Render(errMsg)
542
543	// Calculate available space
544	hintWidth := lipgloss.Width(hintText)
545	errorWidth := lipgloss.Width(styledError)
546	separator := "  "
547	sepWidth := lipgloss.Width(separator)
548
549	// If error is too long, truncate it
550	maxErrorWidth := width - hintWidth - sepWidth
551	if maxErrorWidth < 15 {
552		// Not enough space for meaningful error, just show hint
553		return dimmedStyle.Render(hintText)
554	}
555
556	if errorWidth > maxErrorWidth {
557		// Truncate error message
558		plainErr := fmt.Sprintf("Error: %v", err)
559		if maxErrorWidth > 10 {
560			plainErr = truncateToWidth(plainErr, maxErrorWidth-3) + "..."
561		} else {
562			plainErr = truncateToWidth(plainErr, maxErrorWidth)
563		}
564		styledError = stateErroredStyle.Render(plainErr)
565		errorWidth = lipgloss.Width(styledError)
566	}
567
568	// Calculate padding between hint and error
569	padding := width - hintWidth - errorWidth
570	if padding < sepWidth {
571		padding = sepWidth
572	}
573
574	return dimmedStyle.Render(hintText) + strings.Repeat(" ", padding-sepWidth) + separator + styledError
575}