60255
Zn
Zoea-Nova / files
Zoea-Nova / internal / tui / focus.go
29.3 KB
1package tui 2 3import ( 4 "encoding/json" 5 "fmt" 6 "strings" 7 "time" 8 9 "github.com/charmbracelet/bubbles/viewport" 10 "github.com/charmbracelet/lipgloss" 11 "github.com/xonecas/zoea-nova/internal/constants" 12 "github.com/xonecas/zoea-nova/internal/gamestate" 13 "github.com/xonecas/zoea-nova/internal/store" 14) 15 16// LogEntry represents a log entry for display. 17type LogEntry struct { 18 Role string 19 Source string 20 SenderID string 21 SenderName string 22 Content string 23 Reasoning string // NEW: reasoning content from LLM 24 Timestamp time.Time 25} 26 27// wrapText wraps text to fit within maxWidth display columns, preserving words. 28// Uses lipgloss.Width() for proper Unicode character width calculation. 29// Long words that exceed maxWidth are hard-wrapped to prevent overflow. 30func wrapText(text string, maxWidth int) []string { 31 if maxWidth <= 0 { 32 maxWidth = 80 33 } 34 35 var lines []string 36 paragraphs := strings.Split(text, "\n") 37 38 for _, para := range paragraphs { 39 if para == "" { 40 lines = append(lines, "") 41 continue 42 } 43 44 words := strings.Fields(para) 45 if len(words) == 0 { 46 lines = append(lines, "") 47 continue 48 } 49 50 currentLine := "" 51 for _, word := range words { 52 wordWidth := lipgloss.Width(word) 53 54 // If word itself is too long, hard-wrap it 55 if wordWidth > maxWidth { 56 // Flush current line first 57 if currentLine != "" { 58 lines = append(lines, currentLine) 59 currentLine = "" 60 } 61 // Hard-wrap the long word 62 for len(word) > 0 { 63 chunk := truncateToWidth(word, maxWidth) 64 lines = append(lines, chunk) 65 // Remove the chunk from word 66 chunkRunes := []rune(chunk) 67 wordRunes := []rune(word) 68 if len(chunkRunes) < len(wordRunes) { 69 word = string(wordRunes[len(chunkRunes):]) 70 } else { 71 word = "" 72 } 73 } 74 continue 75 } 76 77 // Normal word wrapping 78 if currentLine == "" { 79 currentLine = word 80 } else { 81 lineWidth := lipgloss.Width(currentLine) 82 if lineWidth+1+wordWidth <= maxWidth { 83 currentLine += " " + word 84 } else { 85 lines = append(lines, currentLine) 86 currentLine = word 87 } 88 } 89 } 90 if currentLine != "" { 91 lines = append(lines, currentLine) 92 } 93 } 94 95 return lines 96} 97 98// RenderFocusView renders the detailed mysis view (legacy, without viewport). 99func RenderFocusView(mysis MysisInfo, logs []LogEntry, width, height int, isLoading bool, spinnerView string, verbose bool, focusIndex, totalMyses int, currentTick int64, err error) string { 100 var sections []string 101 102 // Header with mysis name - spans full width (2 lines) 103 header := renderFocusHeader(mysis, focusIndex, totalMyses, width, spinnerView) 104 sections = append(sections, header) 105 106 // Mysis info panel (State, Provider, Account only - ID/Created/Error moved to header) 107 stateDisplay := StateStyle(mysis.State).Render(mysis.State) 108 if isLoading { 109 stateDisplay += " " + spinnerView + " thinking..." 110 } 111 112 infoLines := []string{ 113 fmt.Sprintf("%s %s", labelStyle.Render("State:"), stateDisplay), 114 fmt.Sprintf("%s %s", labelStyle.Render("Provider:"), valueStyle.Render(mysis.Provider)), 115 } 116 117 // Add account info if available 118 if mysis.AccountUsername != "" { 119 infoLines = append(infoLines, fmt.Sprintf("%s %s", labelStyle.Render("Account:"), valueStyle.Render(mysis.AccountUsername))) 120 } else { 121 infoLines = append(infoLines, fmt.Sprintf("%s %s", labelStyle.Render("Account:"), dimmedStyle.Render("(not logged in)"))) 122 } 123 124 infoContent := strings.Join(infoLines, " ") 125 infoPanel := panelStyle.Width(width - 2).Render(infoContent) 126 sections = append(sections, infoPanel) 127 128 // Logs panel - use full-width section title 129 logTitle := renderSectionTitle("CONVERSATION LOG", width) 130 sections = append(sections, logTitle) 131 132 // Calculate available height for logs 133 usedHeight := lipgloss.Height(strings.Join(sections, "\n")) + 4 // +4 for footer 134 logHeight := height - usedHeight - 2 135 if logHeight < 5 { 136 logHeight = 5 137 } 138 139 var logLines []string 140 // Panel is rendered with logStyle.Width(width - 2).Padding(0, 2) 141 // Content width = width - 2, minus 4 for padding (2 each side) = width - 6 142 panelContentWidth := width - 6 143 if len(logs) == 0 { 144 logLines = append(logLines, dimmedStyle.Render("No conversation history.")) 145 } else { 146 // Render all log entries to fill panel content area 147 for _, entry := range logs { 148 entryLines := renderLogEntryImpl(entry, panelContentWidth, verbose, currentTick) 149 logLines = append(logLines, entryLines...) 150 } 151 152 // Show most recent lines that fit 153 if len(logLines) > logHeight { 154 logLines = logLines[len(logLines)-logHeight:] 155 } 156 } 157 158 logContent := strings.Join(logLines, "\n") 159 logPanel := logStyle.Width(width-2).Height(logHeight).Padding(0, 2).Render(logContent) 160 sections = append(sections, logPanel) 161 162 // Footer with hint and error status 163 hint := renderHintWithError("[ ESC ] BACK · [ m ] MESSAGE · [ r ] RELAUNCH · [ s ] STOP", err, width) 164 sections = append(sections, hint) 165 166 return lipgloss.JoinVertical(lipgloss.Left, sections...) 167} 168 169// RenderFocusViewWithViewport renders the detailed mysis view using a scrollable viewport. 170func RenderFocusViewWithViewport(mysis MysisInfo, vp viewport.Model, width int, isLoading bool, spinnerView string, verbose bool, totalLines int, focusIndex, totalMyses int, currentTick int64, gameStateSnapshots []*store.GameStateSnapshot, sidebarScrollOffset int, err error) string { 171 var sections []string 172 173 // Header with mysis name - spans full width (2 lines) 174 header := renderFocusHeader(mysis, focusIndex, totalMyses, width, spinnerView) 175 sections = append(sections, header) 176 177 // Mysis info panel (State, Provider, Account only - ID/Created/Error moved to header) 178 stateDisplay := StateStyle(mysis.State).Render(mysis.State) 179 if isLoading { 180 stateDisplay += " " + spinnerView + " thinking..." 181 } 182 183 infoLines := []string{ 184 fmt.Sprintf("%s %s", labelStyle.Render("State:"), stateDisplay), 185 fmt.Sprintf("%s %s", labelStyle.Render("Provider:"), valueStyle.Render(mysis.Provider)), 186 } 187 188 // Add account info if available 189 if mysis.AccountUsername != "" { 190 infoLines = append(infoLines, fmt.Sprintf("%s %s", labelStyle.Render("Account:"), valueStyle.Render(mysis.AccountUsername))) 191 } else { 192 infoLines = append(infoLines, fmt.Sprintf("%s %s", labelStyle.Render("Account:"), dimmedStyle.Render("(not logged in)"))) 193 } 194 195 infoContent := strings.Join(infoLines, " ") 196 infoPanel := panelStyle.Width(width - 2).Render(infoContent) 197 sections = append(sections, infoPanel) 198 199 // Two-column layout: Game State Sidebar | Conversation Log 200 // Sidebar takes 33% of terminal width (multiply first to avoid precision loss) 201 sidebarWidth := (width * 33) / 100 // Total width including border 202 const columnGap = 3 // Gap between columns (space + │ + space) 203 conversationWidth := width - sidebarWidth - columnGap 204 205 // Conversation title with scroll indicator 206 scrollInfo := "" 207 if !vp.AtBottom() && totalLines > 0 { 208 currentLine := vp.YOffset + 1 209 if currentLine > totalLines { 210 currentLine = totalLines 211 } 212 scrollInfo = fmt.Sprintf(" LINE %d/%d", currentLine, totalLines) 213 } 214 logTitle := renderSectionTitleWithSuffix("CONVERSATION LOG", scrollInfo, conversationWidth) 215 216 // Game state title 217 gameStateTitle := renderSectionTitle("GAME STATE", sidebarWidth) 218 219 // Render game state sidebar content directly (no border, just content + scrollbar) 220 // Content width: sidebarWidth - leftPadding(1) - scrollbar(1) 221 const sidebarScrollbarWidth = 1 // "█" or "│" 222 const sidebarLeftPadding = 1 // Space on left edge 223 sidebarContentWidth := sidebarWidth - sidebarLeftPadding - sidebarScrollbarWidth 224 gameStateSidebarAllContent := renderGameStateSidebar(gameStateSnapshots, currentTick, sidebarContentWidth) 225 sidebarTotalLines := len(gameStateSidebarAllContent) 226 227 // Clip sidebar content to viewport height 228 sidebarHeight := vp.Height 229 gameStateSidebarContent := gameStateSidebarAllContent 230 231 // Clip to visible area if content exceeds height 232 if len(gameStateSidebarAllContent) > sidebarHeight { 233 startLine := sidebarScrollOffset 234 endLine := sidebarScrollOffset + sidebarHeight 235 if startLine < 0 { 236 startLine = 0 237 } 238 if endLine > len(gameStateSidebarAllContent) { 239 endLine = len(gameStateSidebarAllContent) 240 startLine = endLine - sidebarHeight 241 if startLine < 0 { 242 startLine = 0 243 } 244 } 245 gameStateSidebarContent = gameStateSidebarAllContent[startLine:endLine] 246 } 247 248 // Render sidebar scrollbar 249 sidebarScrollbarStr := renderScrollbar(sidebarHeight, sidebarTotalLines, sidebarScrollOffset) 250 sidebarScrollbarLines := strings.Split(sidebarScrollbarStr, "\n") 251 252 // Build sidebar lines with scrollbar (no border) 253 gameStateSidebarLines := make([]string, sidebarHeight) 254 255 for i := 0; i < sidebarHeight; i++ { 256 var contentLine string 257 if i < len(gameStateSidebarContent) { 258 contentLine = gameStateSidebarContent[i] 259 } else { 260 contentLine = "" 261 } 262 263 // Pad content to fill width 264 contentWidth := lipgloss.Width(contentLine) 265 padding := sidebarContentWidth - contentWidth 266 if padding < 0 { 267 padding = 0 268 } 269 contentLine = contentLine + strings.Repeat(" ", padding) 270 271 // Add scrollbar 272 var scrollLine string 273 if i < len(sidebarScrollbarLines) { 274 scrollLine = sidebarScrollbarLines[i] 275 } else { 276 scrollLine = " " 277 } 278 279 // Add left padding space 280 gameStateSidebarLines[i] = " " + contentLine + scrollLine 281 } 282 283 // Render scrollbar based on viewport state 284 scrollOffset := vp.YOffset 285 scrollbarStr := renderScrollbar(vp.Height, totalLines, scrollOffset) 286 scrollbarLines := strings.Split(scrollbarStr, "\n") 287 288 // Get viewport content lines 289 vpContentLines := strings.Split(vp.View(), "\n") 290 291 // Combine viewport content with scrollbar 292 conversationLines := make([]string, vp.Height) 293 for i := 0; i < vp.Height; i++ { 294 var contentLine string 295 if i < len(vpContentLines) { 296 contentLine = vpContentLines[i] 297 } 298 var scrollLine string 299 if i < len(scrollbarLines) { 300 scrollLine = " " + scrollbarLines[i] // Space before scrollbar 301 } else { 302 scrollLine = " " // Empty if no scrollbar line 303 } 304 conversationLines[i] = contentLine + scrollLine 305 } 306 307 // Render conversation log (no border, just content) 308 // The conversation log doesn't have a border, so we use the full conversationWidth 309 conversationContent := strings.Join(conversationLines, "\n") 310 conversationView := logStyle.Width(conversationWidth).Render(conversationContent) 311 conversationViewLines := strings.Split(conversationView, "\n") 312 313 // Vertical border between columns 314 verticalBorderStyle := lipgloss.NewStyle().Foreground(colorBorder) // Purple-tinted border 315 verticalBorder := verticalBorderStyle.Render("│") 316 317 // Combine titles with vertical border 318 titleRow := lipgloss.JoinHorizontal(lipgloss.Top, 319 gameStateTitle, 320 " "+verticalBorder+" ", 321 logTitle, 322 ) 323 sections = append(sections, titleRow) 324 325 // Combine sidebar and conversation content side by side 326 maxLines := len(gameStateSidebarLines) 327 if len(conversationViewLines) > maxLines { 328 maxLines = len(conversationViewLines) 329 } 330 331 for i := 0; i < maxLines; i++ { 332 var leftLine, rightLine string 333 334 if i < len(gameStateSidebarLines) { 335 leftLine = gameStateSidebarLines[i] 336 } else { 337 leftLine = strings.Repeat(" ", sidebarWidth) 338 } 339 340 if i < len(conversationViewLines) { 341 rightLine = conversationViewLines[i] 342 } else { 343 rightLine = strings.Repeat(" ", conversationWidth) 344 } 345 346 combinedLine := lipgloss.JoinHorizontal(lipgloss.Top, 347 leftLine, 348 " "+verticalBorder+" ", 349 rightLine, 350 ) 351 sections = append(sections, combinedLine) 352 } 353 354 // Bottom borders for both sidebar and conversation log with vertical border 355 sidebarBottomBorder := renderSectionTitle("", sidebarWidth) 356 logBottomBorder := renderSectionTitle("", conversationWidth) 357 bottomRow := lipgloss.JoinHorizontal(lipgloss.Top, 358 sidebarBottomBorder, 359 " "+verticalBorder+" ", 360 logBottomBorder, 361 ) 362 sections = append(sections, bottomRow) 363 364 // Footer with scroll hints, verbose toggle, and error status 365 verboseHint := "" 366 if verbose { 367 verboseHint = " · [ v ] VERBOSE: ON" 368 } else { 369 verboseHint = " · [ v ] VERBOSE: OFF" 370 } 371 hintText := fmt.Sprintf("[ ESC ] BACK · [ m ] MESSAGE · [ ↑↓ ] SCROLL · [ G ] BOTTOM%s", verboseHint) 372 hint := renderHintWithError(hintText, err, width) 373 sections = append(sections, hint) 374 375 return lipgloss.JoinVertical(lipgloss.Left, sections...) 376} 377 378// renderToolCallsCompact formats tool calls in compact format. 379// Format: ⚙ tool_name(args...) - truncated, no huge JSON 380func renderToolCallsCompact(content string, contentWidth int) []string { 381 // Parse tool calls from storage format 382 stored := strings.TrimPrefix(content, constants.ToolCallStoragePrefix) 383 if stored == "" { 384 return []string{dimmedStyle.Render("⚠ Empty tool call")} 385 } 386 387 var result []string 388 toolIconStyle := lipgloss.NewStyle().Foreground(colorTool) 389 toolNameStyle := lipgloss.NewStyle().Foreground(colorTool).Bold(true) 390 toolArgStyle := lipgloss.NewStyle().Foreground(colorMuted) 391 392 // Parse each tool call record 393 parts := strings.Split(stored, constants.ToolCallStorageRecordDelimiter) 394 for _, part := range parts { 395 fields := strings.SplitN(part, constants.ToolCallStorageFieldDelimiter, constants.ToolCallStorageFieldCount) 396 if len(fields) < constants.ToolCallStorageFieldCount { 397 continue 398 } 399 400 toolName := fields[1] 401 argsJSON := fields[2] 402 403 // Format: ⚙ tool_name(args...) 404 var argsDisplay string 405 if argsJSON == "{}" { 406 argsDisplay = "()" 407 } else { 408 // Parse JSON and create compact inline format 409 var args map[string]interface{} 410 if err := json.Unmarshal([]byte(argsJSON), &args); err == nil && len(args) > 0 { 411 // Sort keys for deterministic output 412 var keys []string 413 for k := range args { 414 keys = append(keys, k) 415 } 416 // Simple lexicographic sort 417 for i := 0; i < len(keys); i++ { 418 for j := i + 1; j < len(keys); j++ { 419 if keys[i] > keys[j] { 420 keys[i], keys[j] = keys[j], keys[i] 421 } 422 } 423 } 424 425 var argParts []string 426 for _, k := range keys { 427 v := args[k] 428 // Format value based on type 429 var valStr string 430 switch v := v.(type) { 431 case string: 432 // Truncate long strings 433 if len(v) > 20 { 434 valStr = fmt.Sprintf("%q", v[:20]+"...") 435 } else { 436 valStr = fmt.Sprintf("%q", v) 437 } 438 case float64, int, bool: 439 valStr = fmt.Sprintf("%v", v) 440 default: 441 // Complex types: use ellipsis 442 valStr = "{...}" 443 } 444 argParts = append(argParts, fmt.Sprintf("%s=%s", k, valStr)) 445 } 446 argsDisplay = "(" + strings.Join(argParts, ", ") + ")" 447 } else { 448 argsDisplay = "(...)" 449 } 450 } 451 452 // Truncate if too long 453 toolLine := toolIconStyle.Render("⚙") + " " + toolNameStyle.Render(toolName) + toolArgStyle.Render(argsDisplay) 454 if lipgloss.Width(toolLine) > contentWidth { 455 // Truncate args 456 maxArgsWidth := contentWidth - lipgloss.Width(toolIconStyle.Render("⚙")+" "+toolName) - 5 457 if maxArgsWidth < 5 { 458 maxArgsWidth = 5 459 } 460 argsDisplay = truncateWithEllipsis(argsDisplay, maxArgsWidth) 461 toolLine = toolIconStyle.Render("⚙") + " " + toolNameStyle.Render(toolName) + toolArgStyle.Render(argsDisplay) 462 } 463 464 result = append(result, toolLine) 465 } 466 467 return result 468} 469 470// renderToolResultCompact formats tool results compactly. 471// Success: just ✓ Success 472// Error: ✗ Error: message 473func renderToolResultCompact(content string, contentWidth int, verbose bool) []string { 474 // Strip tool call ID prefix if present (format: "call_xxx:json") 475 jsonContent := content 476 if idx := strings.Index(jsonContent, ":"); idx > 0 && strings.HasPrefix(jsonContent, "call_") { 477 jsonContent = jsonContent[idx+1:] 478 } 479 480 trimmed := strings.TrimSpace(jsonContent) 481 482 successStyle := lipgloss.NewStyle().Foreground(colorSuccess) 483 errorStyle := lipgloss.NewStyle().Foreground(colorError) 484 485 // Check for plain-text error formats 486 if strings.HasPrefix(trimmed, "Error calling ") || strings.HasPrefix(trimmed, "Error: ") { 487 errorLine := errorStyle.Render("✗") + " " + errorStyle.Render(trimmed) 488 if verbose { 489 return wrapText(errorLine, contentWidth) 490 } 491 if lipgloss.Width(errorLine) > contentWidth { 492 maxErrWidth := contentWidth - 10 493 if maxErrWidth < 10 { 494 maxErrWidth = 10 495 } 496 errMsg := truncateWithEllipsis(trimmed, maxErrWidth) 497 errorLine = errorStyle.Render("✗") + " " + errorStyle.Render(errMsg) 498 } 499 return []string{errorLine} 500 } 501 502 // Check if it's an error (JSON) 503 if strings.Contains(jsonContent, "\"error\"") || strings.Contains(jsonContent, "\"isError\"") { 504 // Parse error message 505 var data map[string]interface{} 506 if err := json.Unmarshal([]byte(jsonContent), &data); err == nil { 507 if errMsg, ok := data["error"].(string); ok { 508 // Show error message 509 errorLine := errorStyle.Render("✗") + " " + errorStyle.Render("Error: "+errMsg) 510 if verbose { 511 // In verbose mode, show full error 512 return wrapText(errorLine, contentWidth) 513 } 514 // Truncate error message 515 if lipgloss.Width(errorLine) > contentWidth { 516 maxErrWidth := contentWidth - 10 517 if maxErrWidth < 10 { 518 maxErrWidth = 10 519 } 520 errMsg = truncateWithEllipsis(errMsg, maxErrWidth) 521 errorLine = errorStyle.Render("✗") + " " + errorStyle.Render("Error: "+errMsg) 522 } 523 return []string{errorLine} 524 } 525 } 526 // Fallback: generic error 527 return []string{errorStyle.Render("✗ Error")} 528 } 529 530 // Success: just show checkmark 531 return []string{successStyle.Render("✓ Success")} 532} 533 534func renderLogEntryImpl(entry LogEntry, maxWidth int, verbose bool, currentTick int64) []string { 535 // Get the role's foreground color 536 roleColor := RoleColor(entry.Role) 537 prefixStyle := lipgloss.NewStyle(). 538 Foreground(roleColor) 539 540 // Content style - no styling (transparent background) 541 contentStyle := lipgloss.NewStyle() 542 543 var rolePrefix string 544 switch entry.Role { 545 case "user": 546 if entry.Source == "broadcast_self" { 547 rolePrefix = "YOU (BROADCAST):" 548 } else if entry.Source == "broadcast" { 549 label := formatSenderLabel(entry.SenderID, entry.SenderName) 550 if label != "" { 551 rolePrefix = fmt.Sprintf("SWARM (%s):", label) 552 } else { 553 rolePrefix = "SWARM:" 554 } 555 roleColor = lipgloss.Color("214") 556 } else { 557 rolePrefix = "YOU:" 558 } 559 case "assistant": 560 rolePrefix = "AI:" 561 case "system": 562 rolePrefix = "SYS:" 563 case "tool": 564 rolePrefix = "TOOL:" 565 default: 566 rolePrefix = "???:" 567 } 568 569 timePrefix := "T0 ⬡ [--:--]" 570 if !entry.Timestamp.IsZero() { 571 timePrefix = formatTickTimestamp(currentTick, entry.Timestamp) 572 } 573 574 prefix := fmt.Sprintf("%s %s", timePrefix, rolePrefix) 575 // Update prefix style with final role color 576 prefixStyle = prefixStyle.Foreground(roleColor) 577 578 // Inside padding: 1 space on left and right of all content 579 const padLeft = 1 580 const padRight = 1 581 const contentIndent = 4 // 4 spaces indent for content below header 582 583 // Calculate content width (accounting for indent and padding) 584 contentWidth := maxWidth - contentIndent - padLeft - padRight 585 if contentWidth < 20 { 586 contentWidth = 20 587 } 588 589 // Detect special content types and render appropriately 590 var wrappedLines []string 591 592 // Check for tool calls (assistant messages with [TOOL_CALLS] prefix) 593 if entry.Role == "assistant" && strings.HasPrefix(entry.Content, constants.ToolCallStoragePrefix) { 594 // Render tool calls with compact format 595 wrappedLines = renderToolCallsCompact(entry.Content, contentWidth) 596 } else if entry.Role == "tool" { 597 // Tool results: only show errors, success is just a checkmark 598 wrappedLines = renderToolResultCompact(entry.Content, contentWidth, verbose) 599 } else { 600 // Normal text wrapping (user messages, assistant replies) 601 wrappedLines = wrapText(entry.Content, contentWidth) 602 } 603 604 var result []string 605 606 // Add top padding (empty line with background) 607 emptyLine := contentStyle.Width(maxWidth).Render("") 608 result = append(result, emptyLine) 609 610 // Render header line: timestamp + role + horizontal separator 611 leftPad := contentStyle.Render(strings.Repeat(" ", padLeft)) 612 styledPrefix := prefixStyle.Render(prefix) 613 614 // Calculate remaining width for separator after prefix 615 prefixDisplayWidth := lipgloss.Width(prefix) 616 separatorWidth := maxWidth - padLeft - prefixDisplayWidth - 1 - padRight // -1 for space after prefix 617 if separatorWidth < 0 { 618 separatorWidth = 0 619 } 620 621 // Create dimmed horizontal separator 622 dimmedStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("240")) // Dim gray 623 separator := strings.Repeat("─", separatorWidth) 624 styledSeparator := dimmedStyle.Render(" " + separator) 625 626 // Pad to full width 627 headerPadding := strings.Repeat(" ", padRight) 628 headerLine := leftPad + styledPrefix + styledSeparator + headerPadding 629 result = append(result, headerLine) 630 631 // Render content lines (4 spaces indented below header) 632 for _, line := range wrappedLines { 633 // Pad the line content to fill remaining width 634 lineLen := lipgloss.Width(line) 635 remainingWidth := maxWidth - padLeft - contentIndent - lineLen - padRight 636 if remainingWidth < 0 { 637 remainingWidth = 0 638 } 639 paddedLine := line + strings.Repeat(" ", remainingWidth) 640 641 // All content lines: left pad + 4 space indent + content 642 contentLeftPad := contentStyle.Render(strings.Repeat(" ", padLeft)) 643 indent := contentStyle.Render(strings.Repeat(" ", contentIndent)) 644 styledContent := contentStyle.Render(paddedLine) 645 rightPad := contentStyle.Render(strings.Repeat(" ", padRight)) 646 result = append(result, contentLeftPad+indent+styledContent+rightPad) 647 } 648 649 // Render reasoning if present 650 if entry.Reasoning != "" { 651 // Add spacing line 652 emptyLine := contentStyle.Width(maxWidth).Render("") 653 result = append(result, emptyLine) 654 655 // Reasoning header in dimmed purple/magenta 656 reasoningHeaderStyle := lipgloss.NewStyle(). 657 Foreground(lipgloss.Color("170")) // Dimmed purple 658 659 reasoningStyle := lipgloss.NewStyle(). 660 Foreground(lipgloss.Color("213")) // Lighter purple for reasoning text 661 662 dimmedStyle := lipgloss.NewStyle(). 663 Foreground(lipgloss.Color("240")) // Dim gray for truncation indicator 664 665 // Format reasoning header with timestamp (same format as main message) 666 reasoningLabel := "REASONING:" 667 reasoningHeader := fmt.Sprintf("%s %s", timePrefix, reasoningLabel) 668 reasoningHeaderWidth := lipgloss.Width(reasoningHeader) + 1 // +1 for space after 669 reasoningContentWidth := maxWidth - reasoningHeaderWidth - padLeft - padRight 670 if reasoningContentWidth < 20 { 671 reasoningContentWidth = 20 672 } 673 674 // Render header line with separator (matching main message pattern) 675 leftPad := contentStyle.Render(strings.Repeat(" ", padLeft)) 676 styledReasoningHeader := reasoningHeaderStyle.Render(reasoningHeader) 677 reasoningPrefixDisplayWidth := lipgloss.Width(reasoningHeader) 678 reasoningSeparatorWidth := maxWidth - padLeft - reasoningPrefixDisplayWidth - 1 - padRight // -1 for space after prefix 679 if reasoningSeparatorWidth < 0 { 680 reasoningSeparatorWidth = 0 681 } 682 reasoningSeparator := strings.Repeat("─", reasoningSeparatorWidth) 683 styledReasoningSeparator := dimmedStyle.Render(" " + reasoningSeparator) 684 reasoningHeaderPadding := strings.Repeat(" ", padRight) 685 reasoningHeaderLine := leftPad + styledReasoningHeader + styledReasoningSeparator + reasoningHeaderPadding 686 result = append(result, reasoningHeaderLine) 687 688 // Wrap reasoning text 689 wrappedReasoning := wrapText(entry.Reasoning, reasoningContentWidth) 690 691 // Smart truncation: show first line, "[x more]", last 2 lines if verbose is false and > 3 lines 692 const reasoningTruncateThreshold = 3 693 const reasoningShowLast = 2 694 shouldTruncate := !verbose && len(wrappedReasoning) > reasoningTruncateThreshold 695 696 var linesToShow []int 697 if shouldTruncate { 698 // First line 699 linesToShow = append(linesToShow, 0) 700 // Last 2 lines 701 for i := len(wrappedReasoning) - reasoningShowLast; i < len(wrappedReasoning); i++ { 702 linesToShow = append(linesToShow, i) 703 } 704 } else { 705 // Show all lines 706 for i := 0; i < len(wrappedReasoning); i++ { 707 linesToShow = append(linesToShow, i) 708 } 709 } 710 711 truncatedCount := len(wrappedReasoning) - len(linesToShow) 712 713 for idx, i := range linesToShow { 714 line := wrappedReasoning[i] 715 lineLen := lipgloss.Width(line) 716 remainingWidth := reasoningContentWidth - lineLen 717 if remainingWidth < 0 { 718 remainingWidth = 0 719 } 720 paddedLine := line + strings.Repeat(" ", remainingWidth+padRight) 721 722 // Insert truncation indicator after first line 723 if shouldTruncate && idx == 1 { 724 truncMsg := fmt.Sprintf("[%d more]", truncatedCount) 725 truncMsgLen := lipgloss.Width(truncMsg) 726 truncRemainingWidth := reasoningContentWidth - truncMsgLen 727 if truncRemainingWidth < 0 { 728 truncRemainingWidth = 0 729 } 730 truncPaddedLine := truncMsg + strings.Repeat(" ", truncRemainingWidth) 731 732 contentLeftPad := contentStyle.Render(strings.Repeat(" ", padLeft)) 733 indent := contentStyle.Render(strings.Repeat(" ", contentIndent)) 734 styledTrunc := dimmedStyle.Render(truncPaddedLine) 735 rightPad := contentStyle.Render(strings.Repeat(" ", padRight)) 736 result = append(result, contentLeftPad+indent+styledTrunc+rightPad) 737 } 738 739 // All lines: left pad + 4 space indent + content (matches main message rendering) 740 contentLeftPad := contentStyle.Render(strings.Repeat(" ", padLeft)) 741 indent := contentStyle.Render(strings.Repeat(" ", contentIndent)) 742 styledContent := reasoningStyle.Render(paddedLine) 743 rightPad := contentStyle.Render(strings.Repeat(" ", padRight)) 744 result = append(result, contentLeftPad+indent+styledContent+rightPad) 745 } 746 } 747 748 return result 749} 750 751// LogEntryFromMemory converts a store.Memory to LogEntry. 752func LogEntryFromMemory(m *store.Memory, currentMysisID, senderName string) LogEntry { 753 source := string(m.Source) 754 if m.Source == store.MemorySourceBroadcast && m.SenderID == currentMysisID { 755 source = "broadcast_self" 756 } 757 return LogEntry{ 758 Role: string(m.Role), 759 Source: source, 760 SenderID: m.SenderID, 761 SenderName: senderName, 762 Content: m.Content, 763 Reasoning: m.Reasoning, // NEW: copy reasoning field 764 Timestamp: m.CreatedAt, 765 } 766} 767 768// renderFocusHeader renders the focus view header spanning full width (2 lines). 769// Line 1: Mysis name and position 770// Line 2: ID and Created timestamp 771func renderFocusHeader(mysis MysisInfo, focusIndex, totalMyses int, width int, spinnerView string) string { 772 // Line 1: Mysis name with position 773 countText := "" 774 if totalMyses > 0 && focusIndex > 0 { 775 countText = fmt.Sprintf(" (%d/%d)", focusIndex, totalMyses) 776 } 777 titleText := " ⬡ MYSIS: " + mysis.Name + countText + " ⬡ " 778 titleDisplayWidth := lipgloss.Width(titleText) 779 // Total fixed chars: space (1) + ⬥ (1) on left, ⬥ (1) on right = 3 780 availableWidth := width - titleDisplayWidth - 3 781 if availableWidth < 4 { 782 availableWidth = 4 783 } 784 leftDashes := availableWidth / 2 785 rightDashes := availableWidth - leftDashes 786 787 line1 := " ⬥" + strings.Repeat("─", leftDashes) + titleText + strings.Repeat("─", rightDashes) + "⬥" 788 789 // Line 2: ID and Created (or error) 790 var line2 string 791 if mysis.State == "errored" && mysis.LastError != "" { 792 // Show simplified error with animated red icon 793 errorIcon := lipgloss.NewStyle().Foreground(lipgloss.Color("#FF0000")).Render(spinnerView) 794 line2 = " " + labelStyle.Render("ERROR") + " " + errorIcon 795 } else { 796 // Show ID and Created 797 idText := fmt.Sprintf("%s %s", labelStyle.Render("ID:"), dimmedStyle.Render(mysis.ID)) 798 createdText := dimmedStyle.Render("(unknown)") 799 if !mysis.CreatedAt.IsZero() { 800 createdText = dimmedStyle.Render(mysis.CreatedAt.Local().Format("2006-01-02 15:04")) 801 } 802 createdDisplay := fmt.Sprintf("%s %s", labelStyle.Render("Created:"), createdText) 803 line2 = " " + idText + " " + createdDisplay 804 } 805 806 // Combine both lines 807 header := line1 + "\n" + line2 808 return headerStyle.Width(width).Render(header) 809} 810 811// isJSON checks if a string appears to be JSON. 812// Handles tool result format: "tool_call_id:json_content" 813func isJSON(s string) bool { 814 s = strings.TrimSpace(s) 815 816 // Strip tool call ID prefix if present (format: "call_xxx:json") 817 if idx := strings.Index(s, ":"); idx > 0 && strings.HasPrefix(s, "call_") { 818 s = s[idx+1:] 819 s = strings.TrimSpace(s) 820 } 821 822 return (strings.HasPrefix(s, "{") && strings.HasSuffix(s, "}")) || 823 (strings.HasPrefix(s, "[") && strings.HasSuffix(s, "]")) 824} 825 826// renderGameStateSidebar renders the game state sidebar showing all snapshots. 827func renderGameStateSidebar(snapshots []*store.GameStateSnapshot, currentTick int64, width int) []string { 828 var lines []string 829 830 if len(snapshots) == 0 { 831 lines = append(lines, dimmedStyle.Render("No game state")) 832 lines = append(lines, dimmedStyle.Render("available")) 833 return lines 834 } 835 836 // Group snapshots by category (same as buildGameStateSummary) 837 statusTools := []string{"get_status", "get_player"} 838 shipTools := []string{"get_ship", "get_cargo"} 839 locationTools := []string{"get_system", "get_location", "get_poi"} 840 mapTools := []string{"get_map", "get_galaxy"} 841 842 // Helper to render a snapshot group 843 renderGroup := func(toolNames []string) { 844 for _, snapshot := range snapshots { 845 for _, toolName := range toolNames { 846 if snapshot.ToolName == toolName { 847 // Tool name with recency 848 recency := snapshot.RecencyMessage(currentTick) 849 toolHeader := labelStyle.Render(toolName) 850 recencyText := dimmedStyle.Render(fmt.Sprintf(" (%s)", recency)) 851 lines = append(lines, toolHeader+recencyText) 852 853 // Extract and show compact info using TUI-specific formatter 854 linesRaw := gamestate.SnapshotLinesTUI(snapshot.Content) 855 for _, line := range linesRaw { 856 if line == "" { 857 continue 858 } 859 lineText := " " + line 860 wrapped := wrapText(lineText, width-2) 861 for _, wrappedLine := range wrapped { 862 lines = append(lines, dimmedStyle.Render(wrappedLine)) 863 } 864 } 865 lines = append(lines, "") // Empty line between groups 866 } 867 } 868 } 869 } 870 871 renderGroup(statusTools) 872 renderGroup(shipTools) 873 renderGroup(locationTools) 874 renderGroup(mapTools) 875 876 // Remove trailing empty line if present 877 if len(lines) > 0 && lines[len(lines)-1] == "" { 878 lines = lines[:len(lines)-1] 879 } 880 881 return lines 882}