From 8c7c3bedb2b4c0f4b48cdaa4f3c7e478f82360b9 Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Wed, 18 Nov 2026 17:48:38 -0500 Subject: [PATCH 1/6] feat: Show a tool call's arguments as an object in the detail pane A tool call's arguments field is a JSON object sent as one string. The detail pane showed it as one long quoted line with \n and \" escapes, so a multi-line command was hard to read. The pane now decodes a string under the key "arguments" when it is exactly one JSON object, and shows that object. A multi-line command then shows as lines. A string that is not one JSON object stays a string. Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- cmd/agentop/tui/detail_tree.go | 9 +++++++++ cmd/agentop/tui/detail_tree_test.go | 15 +++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/cmd/agentop/tui/detail_tree.go b/cmd/agentop/tui/detail_tree.go index 0c0c74c8a..7ebce8b60 100644 --- a/cmd/agentop/tui/detail_tree.go +++ b/cmd/agentop/tui/detail_tree.go @@ -151,6 +151,15 @@ func buildTree(v any, path, key string, hasKey bool) *node { case int, int64, int32: scalar(strconv.FormatInt(toInt64(x), 10), styleJSONNumber.Render) case string: + // A tool call's arguments are a JSON object sent as a string: show the object. + if key == "arguments" && strings.HasPrefix(x, "{") { + dec := json.NewDecoder(strings.NewReader(x)) + dec.UseNumber() + var obj map[string]any + if dec.Decode(&obj) == nil && !dec.More() { + return buildTree(obj, path, key, hasKey) + } + } n.kind, n.plain, n.size = kindString, x, len(x)+2 n.fold = strings.Count(x, "\n") >= clipLines || len(x) > clipBytes case []any: diff --git a/cmd/agentop/tui/detail_tree_test.go b/cmd/agentop/tui/detail_tree_test.go index 051a8b783..e07c72f21 100644 --- a/cmd/agentop/tui/detail_tree_test.go +++ b/cmd/agentop/tui/detail_tree_test.go @@ -240,3 +240,18 @@ func TestParentPath(t *testing.T) { } } } + +// A tool call's arguments string shows as its object, so a command's lines are lines. +// A string that is not one JSON object stays a string. +func TestRenderTree_ArgumentsStringIsAnObject(t *testing.T) { + got := treeText(t, `{"arguments":"{\"command\":\"cd x\\ncat y\"}","other":"{\"a\":1}"}`, foldState{all: true}) + want := []string{"{", ` "arguments": {`, ` "command": │`, " cd x", " cat y", " },", ` "other": "{\"a\":1}"`, "}"} + if strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Errorf("got %q, want %q", got, want) + } + for _, bad := range []string{`{"arguments":"{bad"}`, `{"arguments":"{} {}"}`} { + if l := treeText(t, bad, foldState{all: true}); len(l) != 3 { + t.Errorf("%s: got %q, want the string kept", bad, l) + } + } +} From d4d110d16851439605d0d711d5a90f4bb0f7b701 Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Wed, 18 Nov 2026 17:58:20 -0500 Subject: [PATCH 2/6] feat: Show a tool's one-line JSON output as a value in the detail pane A tool's output is often compact JSON, for example the output of gh pr view --json. The detail pane showed it as one long quoted line. The pane now decodes a toolResults content string when it is one line and is exactly one JSON object or array. Output with line breaks already shows as lines, so it stays a string. The raw capture is not changed. Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- cmd/agentop/tui/detail_tree.go | 14 +++++++++----- cmd/agentop/tui/detail_tree_test.go | 11 +++++++++++ 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/cmd/agentop/tui/detail_tree.go b/cmd/agentop/tui/detail_tree.go index 7ebce8b60..4f3d25b4b 100644 --- a/cmd/agentop/tui/detail_tree.go +++ b/cmd/agentop/tui/detail_tree.go @@ -151,13 +151,17 @@ func buildTree(v any, path, key string, hasKey bool) *node { case int, int64, int32: scalar(strconv.FormatInt(toInt64(x), 10), styleJSONNumber.Render) case string: - // A tool call's arguments are a JSON object sent as a string: show the object. - if key == "arguments" && strings.HasPrefix(x, "{") { + // A tool call's arguments are a JSON object sent as a string, and a tool's output is + // often compact JSON: show the value. Output with line breaks already reads well. + args := key == "arguments" && strings.HasPrefix(x, "{") + output := key == "content" && strings.Contains(path, "toolResults[") && + (strings.HasPrefix(x, "{") || strings.HasPrefix(x, "[")) && !strings.Contains(x, "\n") + if args || output { dec := json.NewDecoder(strings.NewReader(x)) dec.UseNumber() - var obj map[string]any - if dec.Decode(&obj) == nil && !dec.More() { - return buildTree(obj, path, key, hasKey) + var val any + if dec.Decode(&val) == nil && !dec.More() { + return buildTree(val, path, key, hasKey) } } n.kind, n.plain, n.size = kindString, x, len(x)+2 diff --git a/cmd/agentop/tui/detail_tree_test.go b/cmd/agentop/tui/detail_tree_test.go index e07c72f21..5f3136884 100644 --- a/cmd/agentop/tui/detail_tree_test.go +++ b/cmd/agentop/tui/detail_tree_test.go @@ -255,3 +255,14 @@ func TestRenderTree_ArgumentsStringIsAnObject(t *testing.T) { } } } + +// A tool's one-line JSON output shows as its value. Output with line breaks, and a content +// key outside toolResults, stay strings. +func TestRenderTree_ToolResultJSONIsAValue(t *testing.T) { + got := treeText(t, `{"toolResults":[{"content":"[1,{\"a\":2}]"},{"content":"{\n\"a\": 1}"}],"content":"{\"b\":3}"}`, foldState{all: true}) + want := []string{"{", ` "content": "{\"b\":3}",`, ` "toolResults": [`, " {", ` "content": [`, " 1,", " {", + ` "a": 2`, " }", " ]", " },", " {", ` "content": │`, " {", ` "a": 1}`, " }", " ]", "}"} + if strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Errorf("got %q\nwant %q", got, want) + } +} From f9f44204df1e925844c91f85462eff77b6d168d8 Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Wed, 18 Nov 2026 18:06:36 -0500 Subject: [PATCH 3/6] fix: Keep JSON strings as they are in the exact capture, and decode one only when no bytes follow its value Fixes review: under raw, an arguments string or a tool output string showed as a value, so the capture did not show what the client sent. Fixes review: {}] and {"a":1}} showed as a clean value, and the bytes after it were hidden. Now they stay a string. Files: - cmd/agentop/tui/detail_tree.go - cmd/agentop/tui/detail_tree_test.go Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- cmd/agentop/tui/detail_tree.go | 17 ++++++++++++--- cmd/agentop/tui/detail_tree_test.go | 32 +++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/cmd/agentop/tui/detail_tree.go b/cmd/agentop/tui/detail_tree.go index 4f3d25b4b..d6ca9e3c8 100644 --- a/cmd/agentop/tui/detail_tree.go +++ b/cmd/agentop/tui/detail_tree.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "fmt" + "io" "sort" "strconv" "strings" @@ -134,6 +135,14 @@ func sectionOf(path string) string { return "request" } +// inCapture reports whether path is in an event's exact capture: the "raw" child of its root. +func inCapture(path string) bool { + if s := sectionOf(path); strings.HasPrefix(path, s+".") { + path = path[len(s)+1:] + } + return path == "raw" || strings.HasPrefix(path, "raw.") || strings.HasPrefix(path, "raw[") +} + func buildTree(v any, path, key string, hasKey bool) *node { n := &node{path: path, key: key, hasKey: hasKey} scalar := func(s string, style func(...string) string) { @@ -156,12 +165,14 @@ func buildTree(v any, path, key string, hasKey bool) *node { args := key == "arguments" && strings.HasPrefix(x, "{") output := key == "content" && strings.Contains(path, "toolResults[") && (strings.HasPrefix(x, "{") || strings.HasPrefix(x, "[")) && !strings.Contains(x, "\n") - if args || output { + if (args || output) && !inCapture(path) { dec := json.NewDecoder(strings.NewReader(x)) dec.UseNumber() var val any - if dec.Decode(&val) == nil && !dec.More() { - return buildTree(val, path, key, hasKey) + if dec.Decode(&val) == nil { + if _, err := dec.Token(); err == io.EOF { + return buildTree(val, path, key, hasKey) + } } } n.kind, n.plain, n.size = kindString, x, len(x)+2 diff --git a/cmd/agentop/tui/detail_tree_test.go b/cmd/agentop/tui/detail_tree_test.go index 5f3136884..1c6b1ff8f 100644 --- a/cmd/agentop/tui/detail_tree_test.go +++ b/cmd/agentop/tui/detail_tree_test.go @@ -266,3 +266,35 @@ func TestRenderTree_ToolResultJSONIsAValue(t *testing.T) { t.Errorf("got %q\nwant %q", got, want) } } + +// A string with bytes after its JSON value stays a string, in arguments and in tool output. +func TestRenderTree_JSONStringWithTrailingBytesStaysAString(t *testing.T) { + for _, s := range []string{`{}]`, `{\"a\":1}}`, `{\"a\":1}]`, `{\"a\":1}x`} { + for _, doc := range []string{`{"arguments":"` + s + `"}`, `{"toolResults":[{"content":"` + s + `"}]}`} { + if got := strings.Join(treeText(t, doc, foldState{all: true}), "\n"); !strings.Contains(got, `"`+s+`"`) { + t.Errorf("%s: got %q, want the string kept", doc, got) + } + } + } +} + +// The exact capture shows the body as the client sent it: arguments and tool output stay strings. +func TestRenderTree_JSONStringInRawStaysAString(t *testing.T) { + body := `{"raw":{"arguments":"{\"a\":1}","toolResults":[{"content":"[1]"}]},"inference":{"arguments":"{\"a\":1}"}}` + for _, path := range []string{"", "request", "response"} { + sec, err := sectionTree(path, "━━ S", nil, []byte(body), "") + if err != nil { + t.Fatal(err) + } + var args, out, inf bool + for _, l := range renderTree(sec, foldState{all: true}) { + s := strings.TrimSpace(stripANSI(l.text)) + args = args || strings.HasPrefix(s, `"arguments": "{\"a\":1}"`) + out = out || s == `"content": "[1]"` + inf = inf || s == `"arguments": {` + } + if !args || !out || !inf { + t.Errorf("path %q: raw arguments kept %v, raw output kept %v, inference object %v", path, args, out, inf) + } + } +} From 2a151f8b7c2b0fc04486e7768f568dc836e5d111 Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Wed, 18 Nov 2026 19:49:37 -0500 Subject: [PATCH 4/6] fix: Match decoded tool arguments and tool output in the details search, and refresh the demo asset Fixes review: the details search matched arguments and one-line tool output as raw text, but the detail tree shows them decoded Fixes review: Go CI (README demo) failed on a stale docs/assets/cortex-demo.svg Files: - cmd/agentop/tui/detail_tree.go - cmd/agentop/tui/search_details_parity_test.go - core/model/tooljson.go - core/sessionapi/search.go - docs/assets/cortex-demo.svg - docs/session-api.md Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- cmd/agentop/tui/detail_tree.go | 23 +++++----- cmd/agentop/tui/search_details_parity_test.go | 9 ++-- core/model/tooljson.go | 39 ++++++++++++++++ core/sessionapi/search.go | 27 ++++++++++-- docs/assets/cortex-demo.svg | 44 +++++++++---------- docs/session-api.md | 2 + 6 files changed, 104 insertions(+), 40 deletions(-) create mode 100644 core/model/tooljson.go diff --git a/cmd/agentop/tui/detail_tree.go b/cmd/agentop/tui/detail_tree.go index d6ca9e3c8..9cf3f8358 100644 --- a/cmd/agentop/tui/detail_tree.go +++ b/cmd/agentop/tui/detail_tree.go @@ -4,7 +4,6 @@ import ( "bytes" "encoding/json" "fmt" - "io" "sort" "strconv" "strings" @@ -14,6 +13,7 @@ import ( "github.com/charmbracelet/lipgloss" "github.com/rossoctl/cortex/cmd/agentop/tui/find" + coremodel "github.com/rossoctl/cortex/core/model" ) // The event detail pane renders an event as a tree, so that the parts of it a reader does not @@ -161,18 +161,17 @@ func buildTree(v any, path, key string, hasKey bool) *node { scalar(strconv.FormatInt(toInt64(x), 10), styleJSONNumber.Render) case string: // A tool call's arguments are a JSON object sent as a string, and a tool's output is - // often compact JSON: show the value. Output with line breaks already reads well. - args := key == "arguments" && strings.HasPrefix(x, "{") - output := key == "content" && strings.Contains(path, "toolResults[") && - (strings.HasPrefix(x, "{") || strings.HasPrefix(x, "[")) && !strings.Contains(x, "\n") - if (args || output) && !inCapture(path) { - dec := json.NewDecoder(strings.NewReader(x)) - dec.UseNumber() + // often compact JSON: show the value. + if !inCapture(path) { var val any - if dec.Decode(&val) == nil { - if _, err := dec.Token(); err == io.EOF { - return buildTree(val, path, key, hasKey) - } + ok := false + if key == "arguments" { + val, ok = coremodel.ToolArgumentsJSON(x) + } else if key == "content" && strings.Contains(path, "toolResults[") { + val, ok = coremodel.ToolOutputJSON(x) + } + if ok { + return buildTree(val, path, key, hasKey) } } n.kind, n.plain, n.size = kindString, x, len(x)+2 diff --git a/cmd/agentop/tui/search_details_parity_test.go b/cmd/agentop/tui/search_details_parity_test.go index 8a511e810..8f20cb3bc 100644 --- a/cmd/agentop/tui/search_details_parity_test.go +++ b/cmd/agentop/tui/search_details_parity_test.go @@ -35,8 +35,10 @@ func TestDetailSearch_ParityWithTheDetailView(t *testing.T) { }, Tools: []pipeline.InferenceTool{{Name: "bash", Description: "run gamma", Parameters: `{"type":"object","properties":{"deltafield":{"type":"string"}}}`}}, - ToolResults: []pipeline.InferenceToolResult{{ToolUseID: "t1", Content: "epsilon output"}}, - HistoryToolCalls: []pipeline.InferenceToolCall{{ID: "t1", Name: "bash", Arguments: `{"cmd":"zeta"}`}}, + ToolResults: []pipeline.InferenceToolResult{{ToolUseID: "t1", Content: "epsilon output"}, + {ToolUseID: "t3", Content: `{"name":"caf\u00e9","n":"ABC"}`}}, + HistoryToolCalls: []pipeline.InferenceToolCall{{ID: "t1", Name: "bash", Arguments: `{"cmd":"zeta"}`}, + {ID: "t3", Name: "bash", Arguments: `{"command":"echo \"omega\"\nls"}`}}, } resp := inf resp.Completion = "eta answer" @@ -70,7 +72,8 @@ func TestDetailSearch_ParityWithTheDetailView(t *testing.T) { t.Fatalf("page: %d events, err %v", len(page.Events), err) } for _, q := range []string{"alpha", "beta reply", "gamma", "deltafield", "epsilon", "zeta", "eta answer", - "theta", "iota", "lambda", "x-kappa", "mu stream", "/nu", "xi", "toolUseId", "role", "bash", "absent"} { + "theta", "iota", "lambda", "x-kappa", "mu stream", "/nu", "xi", "toolUseId", "role", "bash", "absent", + `echo "omega"`, "café", `\"`} { res, err := c.SearchSession(ctx, "s1", q) if err != nil { t.Fatal(err) diff --git a/core/model/tooljson.go b/core/model/tooljson.go new file mode 100644 index 000000000..1cbcd0c3d --- /dev/null +++ b/core/model/tooljson.go @@ -0,0 +1,39 @@ +package model + +import ( + "encoding/json" + "io" + "strings" +) + +// ToolArgumentsJSON decodes s, a tool call's Arguments, when it is exactly one JSON object. +// A detail view shows that value, not the string. Numbers decode as json.Number. +func ToolArgumentsJSON(s string) (any, bool) { + if !strings.HasPrefix(s, "{") { + return nil, false + } + return oneJSONValue(s) +} + +// ToolOutputJSON decodes s, a tool result's Content, when it is one line and exactly one JSON +// object or array. Output with line breaks already reads well as a string. +func ToolOutputJSON(s string) (any, bool) { + if !strings.HasPrefix(s, "{") && !strings.HasPrefix(s, "[") || strings.Contains(s, "\n") { + return nil, false + } + return oneJSONValue(s) +} + +// oneJSONValue decodes s when it holds one JSON value with only white space after it. +func oneJSONValue(s string) (any, bool) { + dec := json.NewDecoder(strings.NewReader(s)) + dec.UseNumber() + var v any + if dec.Decode(&v) != nil { + return nil, false + } + if _, err := dec.Token(); err != io.EOF { + return nil, false + } + return v, true +} diff --git a/core/sessionapi/search.go b/core/sessionapi/search.go index 7d2d3206c..fac0db724 100644 --- a/core/sessionapi/search.go +++ b/core/sessionapi/search.go @@ -92,6 +92,7 @@ type matcher struct { q string seen map[strKey]bool json map[strKey]bool + tool map[strKey]bool keys map[string]bool } @@ -102,7 +103,7 @@ type strKey struct { func newMatcher(q string) *matcher { return &matcher{q: strings.Map(unicode.ToLower, q), - seen: map[strKey]bool{}, json: map[strKey]bool{}, keys: map[string]bool{}} + seen: map[strKey]bool{}, json: map[strKey]bool{}, tool: map[strKey]bool{}, keys: map[string]bool{}} } // fold reports whether s holds the query, folded as agentop's find.Contains folds: rune by rune, @@ -129,6 +130,7 @@ func (m *matcher) text(s string) bool { func (m *matcher) forget() { clear(m.seen) clear(m.json) + clear(m.tool) clear(m.keys) } @@ -229,7 +231,7 @@ func (m *matcher) calls(cs []model.InferenceToolCall) bool { } for i := range cs { x := &cs[i] - if m.field("id", x.ID) || m.field("name", x.Name) || m.field("arguments", x.Arguments) { + if m.field("id", x.ID) || m.field("name", x.Name) || m.toolJSON("arguments", x.Arguments, model.ToolArgumentsJSON) { return true } } @@ -245,7 +247,7 @@ func (m *matcher) results(rs []model.InferenceToolResult) bool { } for i := range rs { x := &rs[i] - if m.field("toolUseId", x.ToolUseID) || m.field("content", x.Content) || + if m.field("toolUseId", x.ToolUseID) || m.toolJSON("content", x.Content, model.ToolOutputJSON) || (x.IsError && (m.key("isError") || m.key("true"))) { return true } @@ -253,6 +255,25 @@ func (m *matcher) results(rs []model.InferenceToolResult) bool { return false } +// toolJSON is field for a string that the detail tree shows as its decoded value when decode +// accepts it. Each distinct string is decoded one time. +func (m *matcher) toolJSON(key, v string, decode func(string) (any, bool)) bool { + if v == "" || m.key(key) { + return v != "" + } + k := strKey{unsafe.StringData(v), len(v)} + r, ok := m.tool[k] + if !ok { + if d, isJSON := decode(v); isJSON { + r = m.value(d) + } else { + r = m.text(v) + } + m.tool[k] = r + } + return r +} + // schema is a tool's parameters: JSON, which the detail tree shows as keys and values. Each // distinct schema is walked one time. func (m *matcher) schema(raw string) bool { diff --git a/docs/assets/cortex-demo.svg b/docs/assets/cortex-demo.svg index 18dfdc4d8..791cfd19c 100644 --- a/docs/assets/cortex-demo.svg +++ b/docs/assets/cortex-demo.svg @@ -5190,17 +5190,17 @@ clipPath rect{width:100000px} ▌▾ { -"arguments": "{\"command\":\"npm test -- Settings\"}", +▾ "arguments": { -"id": "toolu_web_04", +"command": "npm test -- Settings" -"name": "Bash" +}, -} +"id": "toolu_web_04", -] +"name": "Bash" -}, +} [↑↓] move [↵] fold [tab] response [y] yank request [u] usage [/] search [esc] back [?] keys [q] quit @@ -5228,37 +5228,37 @@ clipPath rect{width:100000px} ▾ { -"arguments": "{\"command\":\"npm test -- Settings\"}", +▾ "arguments": { -"id": "toolu_web_04", +"command": "npm test -- Settings" -"name": "Bash" +}, -} +"id": "toolu_web_04", -] +"name": "Bash" -}, +} -▾ { +] -"role": "user", +}, -▾ "toolResults": [ +▾ { -▾ { +"role": "user", -"content": │ +▾ "toolResults": [ -PASS src/pages/Settings.test.tsx +▾ { - ✓ toggles dark mode (31 ms) +"content": │ - ✓ keeps the choice after reload (12 ms) +PASS src/pages/Settings.test.tsx -"toolUseId": "toolu_web_04" + ✓ toggles dark mode (31 ms) -▌} +▌ ✓ keeps the choice after reload (12 ms) diff --git a/docs/session-api.md b/docs/session-api.md index e803e3f45..21929b565 100644 --- a/docs/session-api.md +++ b/docs/session-api.md @@ -333,6 +333,8 @@ curl -s 'localhost:9094/v1/sessions//search?q=retry%20budget' - request: `inference.messages`, `inference.tools` (a tool's `parameters` as JSON), `inference.toolResults`, the history tool calls, `mcp.params` - response: `inference.toolCalls`, `mcp.result`, `a2a.artifact` + - a tool call's `arguments` and a tool's one-line output as their JSON value, where the view + decodes them (`model.ToolArgumentsJSON`, `model.ToolOutputJSON`) - the key names in those parts, as the view shows them - where the archive holds a capture: its body blocks (keys and values when a block is JSON, its text when not), the keys and values between blocks, the headers, the query, and a response's From 5e2e4c84caf89f981868881104197c02dfda716f Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Wed, 18 Nov 2026 20:03:58 -0500 Subject: [PATCH 5/6] fix: Decode tool JSON in the detail tree only at the tool call and tool result fields that the details search reads Fixes review: the tree decoded arguments and tool output at any depth, in mcp.params and inside a decoded value, where the details search reads the string Files: - cmd/agentop/tui/detail_tree.go - cmd/agentop/tui/detail_tree_test.go - cmd/agentop/tui/search_details_parity_test.go Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- cmd/agentop/tui/detail_tree.go | 36 +++++------ cmd/agentop/tui/detail_tree_test.go | 63 +++++++++++-------- cmd/agentop/tui/search_details_parity_test.go | 8 +-- 3 files changed, 59 insertions(+), 48 deletions(-) diff --git a/cmd/agentop/tui/detail_tree.go b/cmd/agentop/tui/detail_tree.go index 9cf3f8358..a52546e54 100644 --- a/cmd/agentop/tui/detail_tree.go +++ b/cmd/agentop/tui/detail_tree.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "fmt" + "regexp" "sort" "strconv" "strings" @@ -135,13 +136,13 @@ func sectionOf(path string) string { return "request" } -// inCapture reports whether path is in an event's exact capture: the "raw" child of its root. -func inCapture(path string) bool { - if s := sectionOf(path); strings.HasPrefix(path, s+".") { - path = path[len(s)+1:] - } - return path == "raw" || strings.HasPrefix(path, "raw.") || strings.HasPrefix(path, "raw[") -} +// toolArgsPath and toolOutputPath are a tool call's arguments and a tool result's content in an +// event's inference, where the detail view puts them. They are the fields that sessionapi's +// details search decodes, so a string in the capture, in MCP, or in a decoded value stays a string. +var ( + toolArgsPath = regexp.MustCompile(`^((request|response)\.)?inference\.(messages\[\d+\]\.)?(toolCalls|historyToolCalls)\[\d+\]\.arguments$`) + toolOutputPath = regexp.MustCompile(`^((request|response)\.)?inference\.(messages\[\d+\]\.)?toolResults\[\d+\]\.content$`) +) func buildTree(v any, path, key string, hasKey bool) *node { n := &node{path: path, key: key, hasKey: hasKey} @@ -162,17 +163,16 @@ func buildTree(v any, path, key string, hasKey bool) *node { case string: // A tool call's arguments are a JSON object sent as a string, and a tool's output is // often compact JSON: show the value. - if !inCapture(path) { - var val any - ok := false - if key == "arguments" { - val, ok = coremodel.ToolArgumentsJSON(x) - } else if key == "content" && strings.Contains(path, "toolResults[") { - val, ok = coremodel.ToolOutputJSON(x) - } - if ok { - return buildTree(val, path, key, hasKey) - } + var val any + ok := false + switch { + case toolArgsPath.MatchString(path): + val, ok = coremodel.ToolArgumentsJSON(x) + case toolOutputPath.MatchString(path): + val, ok = coremodel.ToolOutputJSON(x) + } + if ok { + return buildTree(val, path, key, hasKey) } n.kind, n.plain, n.size = kindString, x, len(x)+2 n.fold = strings.Count(x, "\n") >= clipLines || len(x) > clipBytes diff --git a/cmd/agentop/tui/detail_tree_test.go b/cmd/agentop/tui/detail_tree_test.go index 1c6b1ff8f..e7f98482a 100644 --- a/cmd/agentop/tui/detail_tree_test.go +++ b/cmd/agentop/tui/detail_tree_test.go @@ -241,38 +241,49 @@ func TestParentPath(t *testing.T) { } } -// A tool call's arguments string shows as its object, so a command's lines are lines. -// A string that is not one JSON object stays a string. -func TestRenderTree_ArgumentsStringIsAnObject(t *testing.T) { - got := treeText(t, `{"arguments":"{\"command\":\"cd x\\ncat y\"}","other":"{\"a\":1}"}`, foldState{all: true}) - want := []string{"{", ` "arguments": {`, ` "command": │`, " cd x", " cat y", " },", ` "other": "{\"a\":1}"`, "}"} - if strings.Join(got, "\n") != strings.Join(want, "\n") { - t.Errorf("got %q, want %q", got, want) - } - for _, bad := range []string{`{"arguments":"{bad"}`, `{"arguments":"{} {}"}`} { - if l := treeText(t, bad, foldState{all: true}); len(l) != 3 { - t.Errorf("%s: got %q, want the string kept", bad, l) - } +// toolDoc is v as JSON, so a test can write a JSON string that holds JSON without escapes. +func toolDoc(t *testing.T, v any) string { + t.Helper() + b, err := json.Marshal(v) + if err != nil { + t.Fatal(err) } + return string(b) } -// A tool's one-line JSON output shows as its value. Output with line breaks, and a content -// key outside toolResults, stay strings. -func TestRenderTree_ToolResultJSONIsAValue(t *testing.T) { - got := treeText(t, `{"toolResults":[{"content":"[1,{\"a\":2}]"},{"content":"{\n\"a\": 1}"}],"content":"{\"b\":3}"}`, foldState{all: true}) - want := []string{"{", ` "content": "{\"b\":3}",`, ` "toolResults": [`, " {", ` "content": [`, " 1,", " {", - ` "a": 2`, " }", " ]", " },", " {", ` "content": │`, " {", ` "a": 1}`, " }", " ]", "}"} - if strings.Join(got, "\n") != strings.Join(want, "\n") { +// A tool call's arguments and a tool's one-line JSON output show as their value, at the paths +// where the detail view puts them, one level only. The same key elsewhere, a string inside a +// decoded value, and output with line breaks stay strings. +func TestRenderTree_ToolArgumentsAndOutputDecodeOneLevel(t *testing.T) { + doc := toolDoc(t, map[string]any{ + "inference": map[string]any{"toolCalls": []any{map[string]any{ + "arguments": `{"command":"cd x\ncat y","arguments":"{\"a\":1}"}`, "other": `{"a":1}`}}, + "toolResults": []any{map[string]any{"content": `[1,{"content":"{\"b\":2}"}]`}, map[string]any{"content": "{\n\"a\": 1}"}}, + "arguments": `{"a":1}`}, + "mcp": map[string]any{"params": map[string]any{"arguments": `{"a":1}`}}, + }) + want := []string{"{", ` "inference": {`, ` "arguments": "{\"a\":1}",`, ` "toolCalls": [`, " {", + ` "arguments": {`, ` "arguments": "{\"a\":1}",`, ` "command": │`, " cd x", " cat y", + " },", ` "other": "{\"a\":1}"`, " }", " ],", ` "toolResults": [`, " {", ` "content": [`, + " 1,", " {", ` "content": "{\"b\":2}"`, " }", " ]", " },", " {", + ` "content": │`, " {", ` "a": 1}`, " }", " ]", " },", ` "mcp": {`, ` "params": {`, + ` "arguments": "{\"a\":1}"`, " }", " }", "}"} + if got := treeText(t, doc, foldState{all: true}); strings.Join(got, "\n") != strings.Join(want, "\n") { t.Errorf("got %q\nwant %q", got, want) } } -// A string with bytes after its JSON value stays a string, in arguments and in tool output. -func TestRenderTree_JSONStringWithTrailingBytesStaysAString(t *testing.T) { - for _, s := range []string{`{}]`, `{\"a\":1}}`, `{\"a\":1}]`, `{\"a\":1}x`} { - for _, doc := range []string{`{"arguments":"` + s + `"}`, `{"toolResults":[{"content":"` + s + `"}]}`} { - if got := strings.Join(treeText(t, doc, foldState{all: true}), "\n"); !strings.Contains(got, `"`+s+`"`) { - t.Errorf("%s: got %q, want the string kept", doc, got) +// A string that is not exactly one JSON value stays a string, in arguments and in tool output. +func TestRenderTree_ToolJSONWithOtherBytesStaysAString(t *testing.T) { + for _, s := range []string{`{bad`, `{} {}`, `{}]`, `{"a":1}}`, `{"a":1}]`, `{"a":1}x`} { + for _, inf := range []map[string]any{ + {"toolCalls": []any{map[string]any{"arguments": s}}}, + {"toolResults": []any{map[string]any{"content": s}}}, + } { + doc := toolDoc(t, map[string]any{"inference": inf}) + kept := toolDoc(t, s) + if got := strings.Join(treeText(t, doc, foldState{all: true}), "\n"); !strings.Contains(got, kept) { + t.Errorf("%s: got %q, want %s kept", doc, got, kept) } } } @@ -280,7 +291,7 @@ func TestRenderTree_JSONStringWithTrailingBytesStaysAString(t *testing.T) { // The exact capture shows the body as the client sent it: arguments and tool output stay strings. func TestRenderTree_JSONStringInRawStaysAString(t *testing.T) { - body := `{"raw":{"arguments":"{\"a\":1}","toolResults":[{"content":"[1]"}]},"inference":{"arguments":"{\"a\":1}"}}` + body := `{"raw":{"arguments":"{\"a\":1}","toolResults":[{"content":"[1]"}]},"inference":{"toolCalls":[{"arguments":"{\"a\":1}"}]}}` for _, path := range []string{"", "request", "response"} { sec, err := sectionTree(path, "━━ S", nil, []byte(body), "") if err != nil { diff --git a/cmd/agentop/tui/search_details_parity_test.go b/cmd/agentop/tui/search_details_parity_test.go index 8f20cb3bc..0a1d7c4d7 100644 --- a/cmd/agentop/tui/search_details_parity_test.go +++ b/cmd/agentop/tui/search_details_parity_test.go @@ -36,9 +36,9 @@ func TestDetailSearch_ParityWithTheDetailView(t *testing.T) { Tools: []pipeline.InferenceTool{{Name: "bash", Description: "run gamma", Parameters: `{"type":"object","properties":{"deltafield":{"type":"string"}}}`}}, ToolResults: []pipeline.InferenceToolResult{{ToolUseID: "t1", Content: "epsilon output"}, - {ToolUseID: "t3", Content: `{"name":"caf\u00e9","n":"ABC"}`}}, + {ToolUseID: "t3", Content: `{"name":"caf\u00e9","n":"ABC","content":"{\"z\":\"caf\\u00e9z\"}"}`}}, HistoryToolCalls: []pipeline.InferenceToolCall{{ID: "t1", Name: "bash", Arguments: `{"cmd":"zeta"}`}, - {ID: "t3", Name: "bash", Arguments: `{"command":"echo \"omega\"\nls"}`}}, + {ID: "t3", Name: "bash", Arguments: `{"command":"echo \"omega\"\nls","arguments":"{\"n\":\"na\\u00efve\"}"}`}}, } resp := inf resp.Completion = "eta answer" @@ -54,7 +54,7 @@ func TestDetailSearch_ParityWithTheDetailView(t *testing.T) { {pipeline.SessionEvent{At: now, Phase: pipeline.SessionResponse, Inference: &resp}, &pipeline.RequestCapture{Response: &pipeline.ResponseCapture{Status: 200, Body: []byte("data: mu stream" + pad)}}}, {pipeline.SessionEvent{At: now, Phase: pipeline.SessionRequest, - MCP: &pipeline.MCPExtension{Method: "tools/call", Params: map[string]any{"path": "/nu"}}}, nil}, + MCP: &pipeline.MCPExtension{Method: "tools/call", Params: map[string]any{"path": "/nu", "arguments": `{"kk":"r\u00e9sum\u00e9"}`}}}, nil}, {pipeline.SessionEvent{At: now, Phase: pipeline.SessionResponse, MCP: &pipeline.MCPExtension{Method: "tools/call", Result: map[string]any{"text": "xi"}}}, nil}, } { @@ -73,7 +73,7 @@ func TestDetailSearch_ParityWithTheDetailView(t *testing.T) { } for _, q := range []string{"alpha", "beta reply", "gamma", "deltafield", "epsilon", "zeta", "eta answer", "theta", "iota", "lambda", "x-kappa", "mu stream", "/nu", "xi", "toolUseId", "role", "bash", "absent", - `echo "omega"`, "café", `\"`} { + `echo "omega"`, "café", "caféz", "naïve", "résumé"} { res, err := c.SearchSession(ctx, "s1", q) if err != nil { t.Fatal(err) From 70761f18343ef755d6ccf0b247159b56fd635cf5 Mon Sep 17 00:00:00 2001 From: Hai Huang Date: Wed, 18 Nov 2026 20:20:37 -0500 Subject: [PATCH 6/6] fix: Start a large decoded tool value closed, and do not keep decoded strings in the search The detail tree now starts a decoded tool value closed when its string is longer than clipBytes. Before, a large one-line JSON output opened as a full tree in the newest turn. The string that it replaced started closed. The details search now matches a decoded tool value with archive.MatchJSON and fold. Before, m.text kept each long decoded string, a new copy, in memory until the search ended. Assisted-By: Claude (Anthropic AI) Signed-off-by: Hai Huang --- cmd/agentop/tui/detail_tree.go | 5 ++++- cmd/agentop/tui/detail_tree_test.go | 19 +++++++++++++++++++ core/sessionapi/search.go | 8 +++++--- core/sessionapi/search_test.go | 14 ++++++++++++++ 4 files changed, 42 insertions(+), 4 deletions(-) diff --git a/cmd/agentop/tui/detail_tree.go b/cmd/agentop/tui/detail_tree.go index a52546e54..4d3412af2 100644 --- a/cmd/agentop/tui/detail_tree.go +++ b/cmd/agentop/tui/detail_tree.go @@ -172,7 +172,10 @@ func buildTree(v any, path, key string, hasKey bool) *node { val, ok = coremodel.ToolOutputJSON(x) } if ok { - return buildTree(val, path, key, hasKey) + // A large value starts closed, as the string did, so it does not fill the turn. + t := buildTree(val, path, key, hasKey) + t.defOpen = len(x) <= clipBytes + return t } n.kind, n.plain, n.size = kindString, x, len(x)+2 n.fold = strings.Count(x, "\n") >= clipLines || len(x) > clipBytes diff --git a/cmd/agentop/tui/detail_tree_test.go b/cmd/agentop/tui/detail_tree_test.go index e7f98482a..e7859ea87 100644 --- a/cmd/agentop/tui/detail_tree_test.go +++ b/cmd/agentop/tui/detail_tree_test.go @@ -309,3 +309,22 @@ func TestRenderTree_JSONStringInRawStaysAString(t *testing.T) { } } } + +// A decoded tool value larger than clipBytes starts closed, as the string did. A small one starts +// open. +func TestRenderTree_LargeDecodedToolValueStartsClosed(t *testing.T) { + big := toolDoc(t, []any{strings.Repeat("y", clipBytes)}) + doc := toolDoc(t, map[string]any{"inference": map[string]any{"messages": []any{map[string]any{ + "role": "user", "toolResults": []any{map[string]any{"content": big}, map[string]any{"content": `{"a":1}`}}}}}}) + root, err := treeFromJSON([]byte(doc)) + if err != nil { + t.Fatal(err) + } + res := root.child("inference").child("messages").kids[0].child("toolResults").kids + if c := res[0].child("content"); c.kind != kindArray || c.defOpen { + t.Errorf("large output: kind %v, open %v, want a closed array", c.kind, c.defOpen) + } + if c := res[1].child("content"); c.kind != kindObject || !c.defOpen { + t.Errorf("small output: kind %v, open %v, want an open object", c.kind, c.defOpen) + } +} diff --git a/core/sessionapi/search.go b/core/sessionapi/search.go index fac0db724..0ece5be40 100644 --- a/core/sessionapi/search.go +++ b/core/sessionapi/search.go @@ -256,7 +256,9 @@ func (m *matcher) results(rs []model.InferenceToolResult) bool { } // toolJSON is field for a string that the detail tree shows as its decoded value when decode -// accepts it. Each distinct string is decoded one time. +// accepts it. Each distinct string is checked one time. The strings inside the value are new +// copies that no other field shares, so they are matched with fold: m.text would keep each one +// in memory to the end of the search. func (m *matcher) toolJSON(key, v string, decode func(string) (any, bool)) bool { if v == "" || m.key(key) { return v != "" @@ -264,8 +266,8 @@ func (m *matcher) toolJSON(key, v string, decode func(string) (any, bool)) bool k := strKey{unsafe.StringData(v), len(v)} r, ok := m.tool[k] if !ok { - if d, isJSON := decode(v); isJSON { - r = m.value(d) + if _, isJSON := decode(v); isJSON { + r = archive.MatchJSON(v, m.fold) } else { r = m.text(v) } diff --git a/core/sessionapi/search_test.go b/core/sessionapi/search_test.go index 11b0ee74a..6bf1f8783 100644 --- a/core/sessionapi/search_test.go +++ b/core/sessionapi/search_test.go @@ -12,6 +12,7 @@ import ( "testing" "time" + "github.com/rossoctl/cortex/core/model" "github.com/rossoctl/cortex/core/pipeline" "github.com/rossoctl/cortex/core/session" "github.com/rossoctl/cortex/core/session/archive" @@ -259,3 +260,16 @@ func TestSearch_MatcherForgetsAtASegment(t *testing.T) { t.Errorf("after forget: %d texts, %d schemas and %d keys kept, want none", len(m.seen), len(m.json), len(m.keys)) } } + +// A tool string's decoded value is a new copy of its strings. The search matches them without +// keeping them, and still finds a long string inside the value. +func TestToolJSON_KeepsNoDecodedString(t *testing.T) { + long := strings.Repeat("x", session.InternMinLen) + ` needle\n` + m := newMatcher("needle") + if !m.toolJSON("arguments", `{"command":"`+long+`"}`, model.ToolArgumentsJSON) { + t.Fatal("the long string in the decoded arguments did not match") + } + if len(m.seen) != 0 { + t.Errorf("the matcher kept %d decoded strings", len(m.seen)) + } +}