@@ -1,12 +1,16 @@
11 package tui
22
33 import (
4+ "encoding/json"
45 "fmt"
6+ "sort"
57 "strings"
68 "time"
79
810 "github.com/charmbracelet/lipgloss"
11+ "github.com/xonecas/zoea-nova/internal/constants"
912 "github.com/xonecas/zoea-nova/internal/core"
13+ "github.com/xonecas/zoea-nova/internal/store"
1014 )
1115
1216 const (
@@ -23,11 +27,12 @@ type MysisInfo struct {
2327 State string
2428 Activity string // Current activity (idle, llm_call, mcp_call, traveling, etc.)
2529 Provider string
26- AccountUsername string // NEW: game account username
27- LastMessage string // Most recent message (user or assistant)
28- LastMessageAt time.Time // Timestamp of most recent message
29- CreatedAt time.Time // When mysis was created
30- LastError string // Last error string (if errored)
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)
3136 }
3237
3338 // SwarmMessageInfo holds display info for a broadcast message.
@@ -260,33 +265,8 @@ func renderMysisLine(m MysisInfo, selected, isLoading bool, spinnerView string,
260265 msgWidth = 10
261266 }
262267
263- // Format last message (truncated) - use display width
264- var msgPart string
265- messageContent := m.LastMessage
266- if messageContent == "" && m.State == "errored" && m.LastError != "" {
267- messageContent = "Error: " + m.LastError
268- }
269- if messageContent != "" {
270- msg := strings.ReplaceAll(messageContent, "\n", " ")
271- msgPrefix := ""
272- if !m.LastMessageAt.IsZero() {
273- msgPrefix = formatTickTimestamp(currentTick, m.LastMessageAt) + " "
274- }
275- prefixWidth := lipgloss.Width(msgPrefix)
276- availableWidth := msgWidth - prefixWidth
277- if availableWidth < 10 {
278- msgPrefix = ""
279- availableWidth = msgWidth
280- }
281- if lipgloss.Width(msg) > availableWidth {
282- if availableWidth > 3 {
283- msg = truncateToWidth(msg, availableWidth-3) + "..."
284- } else {
285- msg = truncateToWidth(msg, availableWidth)
286- }
287- }
288- msgPart = dimmedStyle.Render(" │ " + msgPrefix + msg)
289- }
268+ // Format last message using dedicated rendering with priority system
269+ msgPart := formatMessageRow(m, currentTick, msgWidth)
290270
291271 line := contentPart + msgPart
292272
@@ -312,6 +292,214 @@ func renderMysisLine(m MysisInfo, selected, isLoading bool, spinnerView string,
312292 return unselectedCursor + " " + stateIndicator + " " + mysisItemStyle.PaddingLeft(0).PaddingRight(1).Width(contentStyleWidth).Render(line)
313293 }
314294
295+// formatMessageRow formats the message row based on message type and priority.
296+// Priority order: 1) Errors, 2) AI replies, 3) Tool calls, 4) User messages/broadcasts
297+func formatMessageRow(m MysisInfo, currentTick int64, maxWidth int) string {
298+ // Priority 1: Errors (if state is errored and LastError is set)
299+ if m.State == "errored" && m.LastError != "" {
300+ return formatErrorMessage(m.LastError, currentTick, m.LastMessageAt, maxWidth)
301+ }
302+
303+ // If no recent memories but we have LastMessage (backward compatibility for tests),
304+ // show it as a simple message
305+ if len(m.RecentMemories) == 0 {
306+ if m.LastMessage != "" {
307+ return formatLegacyMessage(m.LastMessage, currentTick, m.LastMessageAt, maxWidth)
308+ }
309+ return ""
310+ }
311+
312+ // Priority 2: AI replies (not tool calls)
313+ for _, mem := range m.RecentMemories {
314+ if mem.Role == store.MemoryRoleAssistant && !strings.HasPrefix(mem.Content, constants.ToolCallStoragePrefix) {
315+ return formatAIReply(mem, currentTick, maxWidth)
316+ }
317+ }
318+
319+ // Priority 3: Tool calls
320+ for _, mem := range m.RecentMemories {
321+ if mem.Role == store.MemoryRoleAssistant && strings.HasPrefix(mem.Content, constants.ToolCallStoragePrefix) {
322+ return formatToolCall(mem, currentTick, maxWidth)
323+ }
324+ }
325+
326+ // Priority 4: User messages/broadcasts
327+ for _, mem := range m.RecentMemories {
328+ if mem.Role == store.MemoryRoleUser {
329+ return formatUserMessage(mem, currentTick, maxWidth)
330+ }
331+ }
332+
333+ return "" // No message to display
334+}
335+
336+// formatLegacyMessage formats a simple message (backward compatibility for tests).
337+func formatLegacyMessage(msg string, currentTick int64, timestamp time.Time, maxWidth int) string {
338+ prefix := ""
339+ if !timestamp.IsZero() {
340+ prefix = formatTickTimestamp(currentTick, timestamp) + " "
341+ }
342+ prefixWidth := lipgloss.Width(prefix)
343+ availableWidth := maxWidth - prefixWidth
344+
345+ content := strings.ReplaceAll(msg, "\n", " ")
346+ if lipgloss.Width(content) > availableWidth {
347+ content = truncateToWidth(content, availableWidth-3) + "..."
348+ }
349+
350+ return dimmedStyle.Render(" │ " + prefix + content)
351+}
352+
353+// formatErrorMessage formats error messages.
354+func formatErrorMessage(errMsg string, currentTick int64, timestamp time.Time, maxWidth int) string {
355+ prefix := "Error: "
356+ if !timestamp.IsZero() {
357+ prefix = formatTickTimestamp(currentTick, timestamp) + " " + prefix
358+ }
359+ prefixWidth := lipgloss.Width(prefix)
360+ availableWidth := maxWidth - prefixWidth
361+
362+ msg := strings.ReplaceAll(errMsg, "\n", " ")
363+ if lipgloss.Width(msg) > availableWidth {
364+ msg = truncateToWidth(msg, availableWidth-3) + "..."
365+ }
366+
367+ return dimmedStyle.Render(" │ " + prefix + msg)
368+}
369+
370+// formatAIReply formats AI assistant replies.
371+func formatAIReply(mem *store.Memory, currentTick int64, maxWidth int) string {
372+ prefix := formatTickTimestamp(currentTick, mem.CreatedAt) + " [AI] "
373+ prefixWidth := lipgloss.Width(prefix)
374+ availableWidth := maxWidth - prefixWidth
375+
376+ msg := strings.ReplaceAll(mem.Content, "\n", " ")
377+ if lipgloss.Width(msg) > availableWidth {
378+ msg = truncateToWidth(msg, availableWidth-3) + "..."
379+ }
380+
381+ return dimmedStyle.Render(" │ " + prefix + msg)
382+}
383+
384+// formatToolCall formats tool call messages.
385+func formatToolCall(mem *store.Memory, currentTick int64, maxWidth int) string {
386+ // Parse tool call from storage format
387+ stored := strings.TrimPrefix(mem.Content, constants.ToolCallStoragePrefix)
388+ if stored == "" {
389+ return ""
390+ }
391+
392+ // Parse first tool call record
393+ parts := strings.Split(stored, constants.ToolCallStorageRecordDelimiter)
394+ if len(parts) == 0 {
395+ return ""
396+ }
397+
398+ fields := strings.SplitN(parts[0], constants.ToolCallStorageFieldDelimiter, constants.ToolCallStorageFieldCount)
399+ if len(fields) < constants.ToolCallStorageFieldCount {
400+ return ""
401+ }
402+
403+ toolName := fields[1]
404+ argsJSON := fields[2]
405+
406+ // Format args (remove outer braces, simplify nested structures)
407+ argsFormatted := formatToolArgs(argsJSON)
408+
409+ // Build message: timestamp + label + function_name(args)
410+ timestamp := formatTickTimestamp(currentTick, mem.CreatedAt)
411+ label := lipgloss.NewStyle().Foreground(colorTool).Render("→ call")
412+ funcName := lipgloss.NewStyle().Foreground(colorTool).Bold(true).Render(toolName)
413+ argsStyled := lipgloss.NewStyle().Foreground(colorTool).Render("(" + argsFormatted + ")")
414+
415+ prefix := timestamp + " " + label + " "
416+ prefixWidth := lipgloss.Width(prefix)
417+ funcWidth := lipgloss.Width(toolName) + lipgloss.Width(argsFormatted) + 2 // +2 for parentheses
418+
419+ availableWidth := maxWidth - prefixWidth
420+ if funcWidth > availableWidth {
421+ // Truncate args
422+ argsAvailable := availableWidth - lipgloss.Width(toolName) - 5 // -5 for "(...)"
423+ if argsAvailable < 3 {
424+ argsFormatted = "..."
425+ } else {
426+ argsFormatted = truncateToWidth(argsFormatted, argsAvailable-3) + "..."
427+ }
428+ argsStyled = lipgloss.NewStyle().Foreground(colorTool).Render("(" + argsFormatted + ")")
429+ }
430+
431+ return dimmedStyle.Render(" │ ") + prefix + funcName + argsStyled
432+}
433+
434+// formatToolArgs formats tool arguments for display.
435+func formatToolArgs(argsJSON string) string {
436+ if argsJSON == "{}" {
437+ return ""
438+ }
439+
440+ var args map[string]interface{}
441+ if err := json.Unmarshal([]byte(argsJSON), &args); err != nil {
442+ return "..."
443+ }
444+
445+ if len(args) == 0 {
446+ return ""
447+ }
448+
449+ // Sort keys for deterministic output
450+ var keys []string
451+ for k := range args {
452+ keys = append(keys, k)
453+ }
454+ sort.Strings(keys)
455+
456+ var parts []string
457+ for _, k := range keys {
458+ v := args[k]
459+ valStr := formatArgValue(v)
460+ parts = append(parts, k+": "+valStr)
461+ }
462+
463+ return strings.Join(parts, ", ")
464+}
465+
466+// formatArgValue formats a single argument value.
467+func formatArgValue(v interface{}) string {
468+ switch v := v.(type) {
469+ case string:
470+ return fmt.Sprintf("%q", v)
471+ case float64, int, bool:
472+ return fmt.Sprintf("%v", v)
473+ case map[string]interface{}:
474+ return "{...}"
475+ case []interface{}:
476+ return "[...]"
477+ default:
478+ return "{...}"
479+ }
480+}
481+
482+// formatUserMessage formats user messages and broadcasts.
483+func formatUserMessage(mem *store.Memory, currentTick int64, maxWidth int) string {
484+ var sourceLabel string
485+ if mem.Source == store.MemorySourceBroadcast {
486+ sourceLabel = "[SWARM]"
487+ } else {
488+ sourceLabel = "[YOU]"
489+ }
490+
491+ prefix := formatTickTimestamp(currentTick, mem.CreatedAt) + " " + sourceLabel + " "
492+ prefixWidth := lipgloss.Width(prefix)
493+ availableWidth := maxWidth - prefixWidth
494+
495+ msg := strings.ReplaceAll(mem.Content, "\n", " ")
496+ if lipgloss.Width(msg) > availableWidth {
497+ msg = truncateToWidth(msg, availableWidth-3) + "..."
498+ }
499+
500+ return dimmedStyle.Render(" │ " + prefix + msg)
501+}
502+
315503 // MysisInfoFromCore converts a core.Mysis to MysisInfo.
316504 func MysisInfoFromCore(m *core.Mysis) MysisInfo {
317505 return MysisInfo{