xonecas.io
60255
Zn

Zoea-Nova / commit 6f6f3ce

feat(tui): add JSON tree rendering for tool results

- Implement Unicode tree rendering with smart truncation
- Show first 3 and last 3 items for large arrays
- Add verbose toggle (v key) for full JSON display
- Automatically detect and render JSON in tool messages
- Add comprehensive test coverage for tree rendering

xonecas2026-02-05 6f6f3ce8df657d1b118bc0bc9df5e32902b821c9 parent 44fd43c

5 files changed

internal/tui/app.go+43−34
@@ -35,6 +35,7 @@ type Model struct {
3535 height int
3636 selectedIdx int
3737 showHelp bool
38+ verboseJSON bool // show full JSON trees without truncation
3839
3940 input InputModel
4041 myses []MysisInfo
@@ -235,7 +236,7 @@ func (m Model) View() string {
235236 if m.showHelp {
236237 content = RenderHelp(m.width, contentHeight)
237238 } else if m.view == ViewFocus {
238- content = RenderFocusViewWithViewport(m.mysisByID(m.focusID), m.viewport, m.width, isLoading, m.spinner.View(), m.autoScroll)
239+ content = RenderFocusViewWithViewport(m.mysisByID(m.focusID), m.viewport, m.width, isLoading, m.spinner.View(), m.autoScroll, m.verboseJSON)
239240 } else {
240241 // Convert swarm messages for display (reversed so most recent is first)
241242 swarmInfos := make([]SwarmMessageInfo, len(m.swarmMessages))
@@ -414,6 +415,12 @@ func (m Model) handleFocusKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
414415 m.viewport.GotoBottom()
415416 m.autoScroll = true
416417 return m, nil
418+
419+ case key.Matches(msg, keys.VerboseToggle):
420+ m.verboseJSON = !m.verboseJSON
421+ // Re-render viewport content with new verbose setting
422+ m.updateViewportContent()
423+ return m, nil
417424 }
418425
419426 // Pass other keys to viewport for scrolling
@@ -637,7 +644,7 @@ func (m *Model) updateViewportContent() {
637644
638645 var lines []string
639646 for _, entry := range m.logs {
640- entryLines := renderLogEntry(entry, panelContentWidth)
647+ entryLines := renderLogEntryImpl(entry, panelContentWidth, m.verboseJSON)
641648 lines = append(lines, entryLines...)
642649 }
643650
@@ -685,37 +692,39 @@ func (m Model) listenForEvents() tea.Cmd {
685692
686693 // Key bindings
687694 var keys = struct {
688- Quit key.Binding
689- Help key.Binding
690- Escape key.Binding
691- Enter key.Binding
692- Tab key.Binding
693- ShiftTab key.Binding
694- Up key.Binding
695- Down key.Binding
696- NewMysis key.Binding
697- Delete key.Binding
698- Relaunch key.Binding
699- Stop key.Binding
700- Broadcast key.Binding
701- Message key.Binding
702- Configure key.Binding
703- End key.Binding
695+ Quit key.Binding
696+ Help key.Binding
697+ Escape key.Binding
698+ Enter key.Binding
699+ Tab key.Binding
700+ ShiftTab key.Binding
701+ Up key.Binding
702+ Down key.Binding
703+ NewMysis key.Binding
704+ Delete key.Binding
705+ Relaunch key.Binding
706+ Stop key.Binding
707+ Broadcast key.Binding
708+ Message key.Binding
709+ Configure key.Binding
710+ End key.Binding
711+ VerboseToggle key.Binding
704712 }{
705- Quit: key.NewBinding(key.WithKeys("q", "ctrl+c")),
706- Help: key.NewBinding(key.WithKeys("?")),
707- Escape: key.NewBinding(key.WithKeys("esc")),
708- Enter: key.NewBinding(key.WithKeys("enter")),
709- Tab: key.NewBinding(key.WithKeys("tab")),
710- ShiftTab: key.NewBinding(key.WithKeys("shift+tab")),
711- Up: key.NewBinding(key.WithKeys("up", "k")),
712- Down: key.NewBinding(key.WithKeys("down", "j")),
713- NewMysis: key.NewBinding(key.WithKeys("n")),
714- Delete: key.NewBinding(key.WithKeys("d")),
715- Relaunch: key.NewBinding(key.WithKeys("r")),
716- Stop: key.NewBinding(key.WithKeys("s")),
717- Broadcast: key.NewBinding(key.WithKeys("b")),
718- Message: key.NewBinding(key.WithKeys("m")),
719- Configure: key.NewBinding(key.WithKeys("c")),
720- End: key.NewBinding(key.WithKeys("end", "G")),
713+ Quit: key.NewBinding(key.WithKeys("q", "ctrl+c")),
714+ Help: key.NewBinding(key.WithKeys("?")),
715+ Escape: key.NewBinding(key.WithKeys("esc")),
716+ Enter: key.NewBinding(key.WithKeys("enter")),
717+ Tab: key.NewBinding(key.WithKeys("tab")),
718+ ShiftTab: key.NewBinding(key.WithKeys("shift+tab")),
719+ Up: key.NewBinding(key.WithKeys("up", "k")),
720+ Down: key.NewBinding(key.WithKeys("down", "j")),
721+ NewMysis: key.NewBinding(key.WithKeys("n")),
722+ Delete: key.NewBinding(key.WithKeys("d")),
723+ Relaunch: key.NewBinding(key.WithKeys("r")),
724+ Stop: key.NewBinding(key.WithKeys("s")),
725+ Broadcast: key.NewBinding(key.WithKeys("b")),
726+ Message: key.NewBinding(key.WithKeys("m")),
727+ Configure: key.NewBinding(key.WithKeys("c")),
728+ End: key.NewBinding(key.WithKeys("end", "G")),
729+ VerboseToggle: key.NewBinding(key.WithKeys("v")),
721730 }
internal/tui/focus.go+35−8
@@ -61,7 +61,7 @@ func wrapText(text string, maxWidth int) []string {
6161 }
6262
6363 // RenderFocusView renders the detailed mysis view (legacy, without viewport).
64-func RenderFocusView(mysis MysisInfo, logs []LogEntry, width, height int, isLoading bool, spinnerView string) string {
64+func RenderFocusView(mysis MysisInfo, logs []LogEntry, width, height int, isLoading bool, spinnerView string, verbose bool) string {
6565 var sections []string
6666
6767 // Header with mysis name - spans full width
@@ -111,7 +111,7 @@ func RenderFocusView(mysis MysisInfo, logs []LogEntry, width, height int, isLoad
111111 } else {
112112 // Render all log entries to fill panel content area
113113 for _, entry := range logs {
114- entryLines := renderLogEntry(entry, panelContentWidth)
114+ entryLines := renderLogEntryImpl(entry, panelContentWidth, verbose)
115115 logLines = append(logLines, entryLines...)
116116 }
117117
@@ -133,7 +133,7 @@ func RenderFocusView(mysis MysisInfo, logs []LogEntry, width, height int, isLoad
133133 }
134134
135135 // RenderFocusViewWithViewport renders the detailed mysis view using a scrollable viewport.
136-func RenderFocusViewWithViewport(mysis MysisInfo, vp viewport.Model, width int, isLoading bool, spinnerView string, autoScroll bool) string {
136+func RenderFocusViewWithViewport(mysis MysisInfo, vp viewport.Model, width int, isLoading bool, spinnerView string, autoScroll bool, verbose bool) string {
137137 var sections []string
138138
139139 // Header with mysis name - spans full width
@@ -176,8 +176,14 @@ func RenderFocusViewWithViewport(mysis MysisInfo, vp viewport.Model, width int,
176176 vpView := logStyle.Width(width-2).Padding(0, 2).Render(vp.View())
177177 sections = append(sections, vpView)
178178
179- // Footer with scroll hints
180- hint := dimmedStyle.Render("[ ESC ] BACK · [ m ] MESSAGE · [ ↑↓ ] SCROLL · [ G ] BOTTOM")
179+ // Footer with scroll hints and verbose toggle
180+ verboseHint := ""
181+ if verbose {
182+ verboseHint = " · [ v ] VERBOSE: ON"
183+ } else {
184+ verboseHint = " · [ v ] VERBOSE: OFF"
185+ }
186+ hint := dimmedStyle.Render(fmt.Sprintf("[ ESC ] BACK · [ m ] MESSAGE · [ ↑↓ ] SCROLL · [ G ] BOTTOM%s", verboseHint))
181187 sections = append(sections, hint)
182188
183189 return lipgloss.JoinVertical(lipgloss.Left, sections...)
@@ -186,7 +192,7 @@ func RenderFocusViewWithViewport(mysis MysisInfo, vp viewport.Model, width int,
186192 // logBgColor is the background color for log entries (same as colorBgPanel)
187193 var logBgColor = colorBgPanel
188194
189-func renderLogEntry(entry LogEntry, maxWidth int) []string {
195+func renderLogEntryImpl(entry LogEntry, maxWidth int, verbose bool) []string {
190196 // Get the role's foreground color and create a style with background
191197 roleColor := RoleColor(entry.Role)
192198 prefixStyle := lipgloss.NewStyle().
@@ -229,8 +235,22 @@ func renderLogEntry(entry LogEntry, maxWidth int) []string {
229235 contentWidth = 20
230236 }
231237
232- // Wrap the content
233- wrappedLines := wrapText(entry.Content, contentWidth)
238+ // Detect JSON content in tool messages and render as tree
239+ var wrappedLines []string
240+ if entry.Role == "tool" && isJSON(entry.Content) {
241+ // Render JSON as tree structure
242+ treeStr, err := renderJSONTree(entry.Content, verbose)
243+ if err == nil {
244+ // Tree rendering succeeded
245+ wrappedLines = strings.Split(treeStr, "\n")
246+ } else {
247+ // Fall back to normal wrapping if JSON parsing fails
248+ wrappedLines = wrapText(entry.Content, contentWidth)
249+ }
250+ } else {
251+ // Normal text wrapping
252+ wrappedLines = wrapText(entry.Content, contentWidth)
253+ }
234254
235255 var result []string
236256 indent := strings.Repeat(" ", prefixWidth)
@@ -349,3 +369,10 @@ func renderFocusHeader(mysisName string, width int) string {
349369 line := "◆" + strings.Repeat("─", leftDashes) + titleText + strings.Repeat("─", rightDashes) + "◆"
350370 return headerStyle.Width(width).Render(line)
351371 }
372+
373+// isJSON checks if a string appears to be JSON
374+func isJSON(s string) bool {
375+ s = strings.TrimSpace(s)
376+ return (strings.HasPrefix(s, "{") && strings.HasSuffix(s, "}")) ||
377+ (strings.HasPrefix(s, "[") && strings.HasSuffix(s, "]"))
378+}
internal/tui/focus_test.go+30−1
@@ -92,7 +92,7 @@ func TestRenderLogEntryWithReasoning(t *testing.T) {
9292 }
9393
9494 maxWidth := 80
95- lines := renderLogEntry(entry, maxWidth)
95+ lines := renderLogEntryImpl(entry, maxWidth, false)
9696
9797 // Should have content lines + reasoning section
9898 if len(lines) < 4 {
@@ -113,3 +113,32 @@ func TestRenderLogEntryWithReasoning(t *testing.T) {
113113 t.Error("Expected ANSI escape codes (styling) in output")
114114 }
115115 }
116+
117+func TestRenderLogEntryToolWithJSON(t *testing.T) {
118+ lipgloss.SetColorProfile(termenv.TrueColor)
119+ defer lipgloss.SetColorProfile(termenv.Ascii)
120+
121+ jsonPayload := `{"ship_id": "abc123", "cargo": [{"item": "iron", "quantity": 50}, {"item": "gold", "quantity": 10}], "fuel": 100}`
122+
123+ entry := LogEntry{
124+ Role: "tool",
125+ Source: "tool",
126+ Content: jsonPayload,
127+ Timestamp: time.Now(),
128+ }
129+
130+ maxWidth := 80
131+ lines := renderLogEntryImpl(entry, maxWidth, false)
132+
133+ output := strings.Join(lines, "\n")
134+
135+ // Should have tree structure
136+ if !strings.Contains(output, "├─") && !strings.Contains(output, "└─") {
137+ t.Error("Expected tree box characters in tool JSON output")
138+ }
139+
140+ // Should contain field names
141+ if !strings.Contains(output, "ship_id") || !strings.Contains(output, "cargo") {
142+ t.Error("Expected JSON field names in tree output")
143+ }
144+}
internal/tui/json_tree.go+195−0
@@ -0,0 +1,195 @@
1+package tui
2+
3+import (
4+ "encoding/json"
5+ "fmt"
6+ "strings"
7+
8+ "github.com/charmbracelet/lipgloss"
9+)
10+
11+const (
12+ // Tree box-drawing characters
13+ treeEdge = "├─"
14+ treeLast = "└─"
15+ treeVert = "│ "
16+ treeSpace = " "
17+
18+ // Truncation limits
19+ arrayTruncateThreshold = 6 // Show first 3 and last 3 if array has more than this
20+ arrayShowFirst = 3
21+ arrayShowLast = 3
22+)
23+
24+// renderJSONTree renders JSON as a Unicode tree structure with smart truncation.
25+// If verbose is true, all items are shown. Otherwise, arrays with more than 6 items
26+// show first 3, "[x more]", and last 3.
27+func renderJSONTree(jsonStr string, verbose bool) (string, error) {
28+ var data interface{}
29+ if err := json.Unmarshal([]byte(jsonStr), &data); err != nil {
30+ return "", fmt.Errorf("invalid JSON: %w", err)
31+ }
32+
33+ var lines []string
34+ renderValue(data, "", true, verbose, &lines)
35+ return strings.Join(lines, "\n"), nil
36+}
37+
38+// renderValue recursively renders a JSON value as tree lines
39+func renderValue(value interface{}, prefix string, isLast bool, verbose bool, lines *[]string) {
40+ switch v := value.(type) {
41+ case map[string]interface{}:
42+ renderObject(v, prefix, isLast, verbose, lines)
43+ case []interface{}:
44+ renderArray(v, prefix, isLast, verbose, lines)
45+ default:
46+ // Primitive value
47+ *lines = append(*lines, prefix+fmt.Sprintf("%v", v))
48+ }
49+}
50+
51+// renderObject renders a JSON object
52+func renderObject(obj map[string]interface{}, prefix string, isLast bool, verbose bool, lines *[]string) {
53+ if len(obj) == 0 {
54+ *lines = append(*lines, prefix+"{}")
55+ return
56+ }
57+
58+ *lines = append(*lines, prefix+"{")
59+
60+ // Get keys in deterministic order (sorted)
61+ keys := make([]string, 0, len(obj))
62+ for k := range obj {
63+ keys = append(keys, k)
64+ }
65+ // Note: Not sorting to preserve JSON order, but could add sort.Strings(keys) here
66+
67+ for i, key := range keys {
68+ isLastField := i == len(keys)-1
69+ fieldPrefix := prefix
70+ if isLast {
71+ fieldPrefix += treeSpace
72+ } else {
73+ fieldPrefix += treeVert
74+ }
75+
76+ var connector string
77+ if isLastField {
78+ connector = treeLast
79+ } else {
80+ connector = treeEdge
81+ }
82+
83+ keyStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("214")) // Orange for keys
84+ valuePrefix := fieldPrefix + connector + keyStyle.Render(fmt.Sprintf("%q: ", key))
85+
86+ val := obj[key]
87+ switch v := val.(type) {
88+ case map[string]interface{}:
89+ *lines = append(*lines, valuePrefix)
90+ renderObject(v, fieldPrefix+treeSpace, isLastField, verbose, lines)
91+ case []interface{}:
92+ *lines = append(*lines, valuePrefix)
93+ renderArray(v, fieldPrefix+treeSpace, isLastField, verbose, lines)
94+ default:
95+ *lines = append(*lines, valuePrefix+fmt.Sprintf("%v", v))
96+ }
97+ }
98+
99+ closingPrefix := prefix
100+ if !isLast {
101+ closingPrefix += treeVert
102+ } else {
103+ closingPrefix += treeSpace
104+ }
105+ *lines = append(*lines, closingPrefix+"}")
106+}
107+
108+// renderArray renders a JSON array with smart truncation
109+func renderArray(arr []interface{}, prefix string, isLast bool, verbose bool, lines *[]string) {
110+ if len(arr) == 0 {
111+ *lines = append(*lines, prefix+"[]")
112+ return
113+ }
114+
115+ *lines = append(*lines, prefix+"[")
116+
117+ shouldTruncate := !verbose && len(arr) > arrayTruncateThreshold
118+
119+ itemsToShow := len(arr)
120+ if shouldTruncate {
121+ itemsToShow = arrayShowFirst + arrayShowLast
122+ }
123+
124+ showItems := make([]int, 0, itemsToShow)
125+ if shouldTruncate {
126+ // First 3 items
127+ for i := 0; i < arrayShowFirst; i++ {
128+ showItems = append(showItems, i)
129+ }
130+ // Last 3 items
131+ for i := len(arr) - arrayShowLast; i < len(arr); i++ {
132+ showItems = append(showItems, i)
133+ }
134+ } else {
135+ // Show all items
136+ for i := 0; i < len(arr); i++ {
137+ showItems = append(showItems, i)
138+ }
139+ }
140+
141+ truncatedCount := len(arr) - len(showItems)
142+
143+ for idx, i := range showItems {
144+ isLastItem := idx == len(showItems)-1
145+
146+ // Insert truncation indicator between first and last items
147+ if shouldTruncate && idx == arrayShowFirst {
148+ truncPrefix := prefix
149+ if isLast {
150+ truncPrefix += treeSpace
151+ } else {
152+ truncPrefix += treeVert
153+ }
154+ dimmedStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("240"))
155+ *lines = append(*lines, truncPrefix+treeEdge+dimmedStyle.Render(fmt.Sprintf("[%d more]", truncatedCount)))
156+ }
157+
158+ itemPrefix := prefix
159+ if isLast {
160+ itemPrefix += treeSpace
161+ } else {
162+ itemPrefix += treeVert
163+ }
164+
165+ var connector string
166+ if isLastItem && !shouldTruncate {
167+ connector = treeLast
168+ } else {
169+ connector = treeEdge
170+ }
171+
172+ indexStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("240")) // Dim gray for indices
173+ itemLine := itemPrefix + connector + indexStyle.Render(fmt.Sprintf("[%d] ", i))
174+
175+ val := arr[i]
176+ switch v := val.(type) {
177+ case map[string]interface{}:
178+ *lines = append(*lines, itemLine)
179+ renderObject(v, itemPrefix+treeSpace, isLastItem, verbose, lines)
180+ case []interface{}:
181+ *lines = append(*lines, itemLine)
182+ renderArray(v, itemPrefix+treeSpace, isLastItem, verbose, lines)
183+ default:
184+ *lines = append(*lines, itemLine+fmt.Sprintf("%v", v))
185+ }
186+ }
187+
188+ closingPrefix := prefix
189+ if !isLast {
190+ closingPrefix += treeVert
191+ } else {
192+ closingPrefix += treeSpace
193+ }
194+ *lines = append(*lines, closingPrefix+"]")
195+}
internal/tui/json_tree_test.go+94−0
@@ -0,0 +1,94 @@
1+package tui
2+
3+import (
4+ "encoding/json"
5+ "strings"
6+ "testing"
7+)
8+
9+func TestRenderJSONTree_SimpleObject(t *testing.T) {
10+ jsonStr := `{"name": "mysis-1", "state": "running", "id": "abc123"}`
11+
12+ tree, err := renderJSONTree(jsonStr, false)
13+ if err != nil {
14+ t.Fatalf("Failed to render JSON tree: %v", err)
15+ }
16+
17+ // Should use tree structure
18+ if !strings.Contains(tree, "├─") && !strings.Contains(tree, "└─") {
19+ t.Error("Expected tree box characters in output")
20+ }
21+
22+ // Should contain field names
23+ if !strings.Contains(tree, "name") || !strings.Contains(tree, "state") {
24+ t.Error("Expected field names in output")
25+ }
26+}
27+
28+func TestRenderJSONTree_ArrayTruncation(t *testing.T) {
29+ items := make([]map[string]interface{}, 10)
30+ for i := 0; i < 10; i++ {
31+ items[i] = map[string]interface{}{"id": i, "value": i * 100}
32+ }
33+ jsonBytes, _ := json.Marshal(items)
34+
35+ tree, err := renderJSONTree(string(jsonBytes), false)
36+ if err != nil {
37+ t.Fatalf("Failed to render JSON tree: %v", err)
38+ }
39+
40+ // Should show truncation indicator
41+ if !strings.Contains(tree, "[4 more]") {
42+ t.Error("Expected '[4 more]' truncation indicator for 10-item array")
43+ }
44+
45+ // Should show first 3 items (0, 1, 2)
46+ if !strings.Contains(tree, `"id": 0`) || !strings.Contains(tree, `"id": 1`) || !strings.Contains(tree, `"id": 2`) {
47+ t.Error("Expected first 3 items to be shown")
48+ }
49+
50+ // Should show last 3 items (7, 8, 9)
51+ if !strings.Contains(tree, `"id": 7`) || !strings.Contains(tree, `"id": 8`) || !strings.Contains(tree, `"id": 9`) {
52+ t.Error("Expected last 3 items to be shown")
53+ }
54+
55+ // Should NOT show middle items
56+ if strings.Contains(tree, `"id": 3`) || strings.Contains(tree, `"id": 4`) {
57+ t.Error("Middle items should be truncated")
58+ }
59+}
60+
61+func TestRenderJSONTree_VerboseMode(t *testing.T) {
62+ items := make([]map[string]interface{}, 10)
63+ for i := 0; i < 10; i++ {
64+ items[i] = map[string]interface{}{"id": i}
65+ }
66+ jsonBytes, _ := json.Marshal(items)
67+
68+ tree, err := renderJSONTree(string(jsonBytes), true)
69+ if err != nil {
70+ t.Fatalf("Failed to render JSON tree: %v", err)
71+ }
72+
73+ // Should NOT truncate in verbose mode
74+ if strings.Contains(tree, "more") {
75+ t.Error("Should not show truncation in verbose mode")
76+ }
77+
78+ // Should show all items
79+ for i := 0; i < 10; i++ {
80+ expected := strings.Replace(`"id": X`, "X", string(rune('0'+i)), 1)
81+ if !strings.Contains(tree, expected) {
82+ t.Errorf("Expected item %d to be shown in verbose mode", i)
83+ }
84+ }
85+}
86+
87+func TestRenderJSONTree_InvalidJSON(t *testing.T) {
88+ jsonStr := `{invalid json`
89+
90+ _, err := renderJSONTree(jsonStr, false)
91+ if err == nil {
92+ t.Error("Expected error for invalid JSON")
93+ }
94+}