This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new 7dad07108774 CAMEL-27135: camel-jbang - the Spans tab labels GenAI
spans and summarizes an agent run (#30523)
7dad07108774 is described below
commit 7dad071087749eb1a5df6b71e790d175771b4371
Author: Claus Ibsen <[email protected]>
AuthorDate: Fri Nov 20 22:47:53 2026 +0100
CAMEL-27135: camel-jbang - the Spans tab labels GenAI spans and summarizes
an agent run (#30523)
GenAI spans get labels in the Spans waterfall: an agent run, a model call
with its tokens and finish reason, a tool call with its arguments. The detail
panel of an agent run shows its model, model and tool calls, tokens, the split
of its time and the steps one by one. The waterfall pads and cuts its labels by
display width (CharWidth).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../images/jbang/camel-tui-spans-agent-run.png | Bin 0 -> 409035 bytes
.../ROOT/pages/camel-jbang-tui-observe.adoc | 7 +
.../dsl/jbang/core/commands/tui/GenAiSpanView.java | 296 +++++++++++++++++++++
.../dsl/jbang/core/commands/tui/SpansTab.java | 22 +-
.../src/main/resources/tui/help/spans.md | 16 ++
.../jbang/core/commands/tui/GenAiSpanViewTest.java | 176 ++++++++++++
.../core/commands/tui/SpansTabRenderTest.java | 64 +++++
7 files changed, 576 insertions(+), 5 deletions(-)
diff --git
a/docs/user-manual/modules/ROOT/images/jbang/camel-tui-spans-agent-run.png
b/docs/user-manual/modules/ROOT/images/jbang/camel-tui-spans-agent-run.png
new file mode 100644
index 000000000000..f60bec1c4b05
Binary files /dev/null and
b/docs/user-manual/modules/ROOT/images/jbang/camel-tui-spans-agent-run.png
differ
diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui-observe.adoc
b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui-observe.adoc
index 57da30036add..466557e20324 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui-observe.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui-observe.adoc
@@ -264,6 +264,11 @@ Features:
* *Sort and search* -- sort by trace ID, route, status, duration, or span
count;
filter with text search
* *Error highlighting* -- failed spans (status ERROR) are highlighted in red
+* *AI agent runs* -- GenAI spans are labelled in the waterfall: an agent run
(◆), a model call (●) with its
+ tokens and finish reason, and a tool call (⚙) with its arguments. The detail
panel of an agent run shows its
+ model and provider, the number of model and tool calls, the tokens, how its
time splits into model calls, tool
+ calls and the rest, and the steps one by one. Agent runs are recorded from
the GenAI observability level
+ `detailed` on (`camel.aiObservability.level=detailed`).
* *AI conversations* -- on a GenAI span (a model call, an agent run or a tool
call), press *t* to read its
conversation: the system instructions, the user and assistant messages, and
each tool call with its arguments
and result. An agent run shows the input and output of its last model call,
which hold the whole run. The
@@ -273,6 +278,8 @@ Features:
This is especially useful for understanding latency in multi-route
integrations and for
correlating Camel processing with external service calls (HTTP, database,
messaging).
+image::jbang/camel-tui-spans-agent-run.png[An agent run in the waterfall: two
model calls and a tool call, with the steps, tokens and time of the run in the
detail panel]
+
image::jbang/camel-tui-spans-conversation.png[The conversation of an agent
run: the question, the call of a route tool with its result, and the answer]
== Process Information
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiSpanView.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiSpanView.java
new file mode 100644
index 000000000000..385a2863a75e
--- /dev/null
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiSpanView.java
@@ -0,0 +1,296 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.dsl.jbang.core.commands.tui;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import dev.tamboui.style.Style;
+import dev.tamboui.text.CharWidth;
+import dev.tamboui.text.Line;
+import dev.tamboui.text.Span;
+import org.apache.camel.component.ai.observability.GenAiAttributes;
+import org.apache.camel.component.ai.observability.GenAiOperationName;
+import org.apache.camel.dsl.jbang.core.commands.LlmClient;
+
+/**
+ * How the Spans tab shows GenAI spans: a label per span in the waterfall (an
agent run, a model call with its tokens
+ * and finish reason, a tool call with its arguments), and in the detail panel
of an agent run its steps, tokens and
+ * time.
+ */
+final class GenAiSpanView {
+
+ static final String AGENT = "◆";
+ static final String MODEL_CALL = "●";
+ static final String TOOL = TuiIcons.GEAR;
+
+ private static final int MAX_ARGUMENTS = 40;
+ private static final int MAX_STEPS = 8;
+ private static final int MAX_PARENT_HOPS = 50;
+
+ /** A model call or tool call of an agent run. */
+ record Step(SpanEntry span, boolean tool, String name, long durationMs,
long inputTokens, long outputTokens,
+ long cachedTokens, String finishReason) {
+ }
+
+ /** An agent run with its steps in the order they started. */
+ record AgentRun(String agentName, String model, String provider, String
conversationId, long durationMs,
+ List<Step> steps) {
+
+ long modelCalls() {
+ return steps.stream().filter(s -> !s.tool()).count();
+ }
+
+ long toolCalls() {
+ return steps.stream().filter(Step::tool).count();
+ }
+
+ long inputTokens() {
+ return steps.stream().mapToLong(Step::inputTokens).sum();
+ }
+
+ long outputTokens() {
+ return steps.stream().mapToLong(Step::outputTokens).sum();
+ }
+
+ long cachedTokens() {
+ return steps.stream().mapToLong(Step::cachedTokens).sum();
+ }
+
+ long modelMs() {
+ return steps.stream().filter(s ->
!s.tool()).mapToLong(Step::durationMs).sum();
+ }
+
+ long toolMs() {
+ return
steps.stream().filter(Step::tool).mapToLong(Step::durationMs).sum();
+ }
+ }
+
+ private GenAiSpanView() {
+ }
+
+ static boolean isAgentRun(SpanEntry span) {
+ return GenAiOperationName.INVOKE_AGENT.value().equals(operation(span));
+ }
+
+ static boolean isToolCall(SpanEntry span) {
+ return GenAiOperationName.EXECUTE_TOOL.value().equals(operation(span));
+ }
+
+ /** The waterfall label of a GenAI span. */
+ static String label(SpanEntry span) {
+ Map<String, Object> attrs = span.attributes();
+ if (isAgentRun(span)) {
+ String model = model(attrs);
+ return AGENT + " agent " + orElse(text(attrs,
GenAiAttributes.AGENT_NAME), span.routeId())
+ + (model != null ? " · " + model : "");
+ }
+ if (isToolCall(span)) {
+ String arguments = text(attrs,
GenAiAttributes.TOOL_CALL_ARGUMENTS);
+ return TOOL + " tool " + orElse(text(attrs,
GenAiAttributes.TOOL_NAME), span.name())
+ + (arguments != null ? " " + oneLine(arguments,
MAX_ARGUMENTS) : "");
+ }
+ StringBuilder sb = new StringBuilder(MODEL_CALL).append('
').append(operation(span));
+ String model = model(attrs);
+ if (model != null) {
+ sb.append(' ').append(model);
+ }
+ long in = number(attrs, GenAiAttributes.INPUT_TOKENS);
+ long out = number(attrs, GenAiAttributes.OUTPUT_TOKENS);
+ if (in > 0 || out > 0) {
+ sb.append(" ·
").append(tokens(in)).append('→').append(tokens(out));
+ }
+ String finish = text(attrs, GenAiAttributes.FINISH_REASONS);
+ if (finish != null) {
+ sb.append(" · ").append(finish);
+ }
+ return sb.toString();
+ }
+
+ /** The colour of a GenAI span in the waterfall: an agent run, a model
call or a tool call. */
+ static Style style(SpanEntry span, boolean selected) {
+ Style style = isAgentRun(span) ? Theme.label() : isToolCall(span) ?
Theme.warning() : Theme.success();
+ return selected ? style.bold() : style;
+ }
+
+ /** The agent run with its model and tool calls: the GenAI spans whose
nearest agent run is this one. */
+ static AgentRun agentRun(SpanEntry agent, List<SpanEntry> traceSpans) {
+ Map<String, SpanEntry> byId = new HashMap<>();
+ for (SpanEntry s : traceSpans) {
+ if (s.spanId() != null) {
+ byId.put(s.spanId(), s);
+ }
+ }
+ List<Step> steps = new ArrayList<>();
+ traceSpans.stream()
+ .filter(s -> s != agent && GenAiTranscript.isGenAiSpan(s) &&
!isAgentRun(s))
+ .filter(s -> agent.spanId() != null &&
agent.spanId().equals(nearestAgentRun(s, byId)))
+ .sorted(Comparator.comparingLong(SpanEntry::startEpochNanos))
+ .forEach(s -> steps.add(step(s)));
+ Map<String, Object> attrs = agent.attributes();
+ return new AgentRun(
+ orElse(text(attrs, GenAiAttributes.AGENT_NAME),
agent.routeId()), model(attrs),
+ orElse(text(attrs, GenAiAttributes.PROVIDER_NAME), text(attrs,
GenAiAttributes.SYSTEM)),
+ text(attrs, GenAiAttributes.CONVERSATION_ID),
agent.durationMs(), steps);
+ }
+
+ private static Step step(SpanEntry span) {
+ Map<String, Object> attrs = span.attributes();
+ if (isToolCall(span)) {
+ return new Step(
+ span, true, orElse(text(attrs, GenAiAttributes.TOOL_NAME),
span.name()), span.durationMs(),
+ 0, 0, 0, null);
+ }
+ return new Step(
+ span, false, operation(span) + (model(attrs) != null ? " " +
model(attrs) : ""),
+ span.durationMs(), number(attrs, GenAiAttributes.INPUT_TOKENS),
+ number(attrs, GenAiAttributes.OUTPUT_TOKENS), number(attrs,
GenAiAttributes.CACHE_READ_INPUT_TOKENS),
+ text(attrs, GenAiAttributes.FINISH_REASONS));
+ }
+
+ private static String nearestAgentRun(SpanEntry span, Map<String,
SpanEntry> byId) {
+ SpanEntry current = span;
+ for (int hops = 0; hops < MAX_PARENT_HOPS && current != null &&
!current.isRoot(); hops++) {
+ current = byId.get(current.parentSpanId());
+ if (current != null && isAgentRun(current)) {
+ return current.spanId();
+ }
+ }
+ return null;
+ }
+
+ /** The lines of the detail panel for an agent run: model, steps, tokens,
time, and the steps one by one. */
+ static List<Line> agentRunLines(AgentRun run) {
+ Style muted = Theme.muted();
+ Style value = Style.EMPTY.fg(Theme.baseFg()).bold();
+ List<Line> lines = new ArrayList<>();
+ List<Span> first = new ArrayList<>(
+ List.of(
+ Span.styled(" Agent: ", muted),
Span.styled(orElse(run.agentName(), "-"), Theme.label())));
+ if (run.model() != null) {
+ first.add(Span.styled(" Model: ", muted));
+ first.add(Span.styled(run.model() + (run.provider() != null ? " ("
+ run.provider() + ")" : ""), value));
+ }
+ if (run.conversationId() != null) {
+ first.add(Span.styled(" Conversation id: ", muted));
+ first.add(Span.raw(run.conversationId()));
+ }
+ lines.add(Line.from(first));
+ lines.add(Line.from(
+ Span.styled(" Steps: ", muted),
+ Span.styled(run.modelCalls() + " model call" +
(run.modelCalls() == 1 ? "" : "s") + ", "
+ + run.toolCalls() + " tool call" +
(run.toolCalls() == 1 ? "" : "s"),
+ value),
+ Span.styled(" Tokens: ", muted),
+ Span.styled(tokens(run.inputTokens()) + " in / " +
tokens(run.outputTokens()) + " out / "
+ + tokens(run.cachedTokens()) + " cached",
+ value)));
+ long other = Math.max(0, run.durationMs() - run.modelMs() -
run.toolMs());
+ lines.add(Line.from(
+ Span.styled(" Time: ", muted),
+ Span.styled(duration(run.durationMs()), value),
+ Span.styled(" = model " + duration(run.modelMs()) +
percent(run.modelMs(), run.durationMs())
+ + " + tools " + duration(run.toolMs()) +
percent(run.toolMs(), run.durationMs())
+ + " + other " + duration(other),
+ muted)));
+ int shown = Math.min(MAX_STEPS, run.steps().size());
+ for (int i = 0; i < shown; i++) {
+ lines.add(stepLine(i + 1, run.steps().get(i)));
+ }
+ if (run.steps().size() > shown) {
+ lines.add(Line.from(Span.styled(" … " + (run.steps().size() -
shown) + " more steps", muted)));
+ }
+ return lines;
+ }
+
+ private static Line stepLine(int number, Step step) {
+ String symbol = step.tool() ? TOOL : MODEL_CALL;
+ Style style = step.tool() ? Theme.warning() : Theme.success();
+ String name = symbol + " " + step.name();
+ name += " ".repeat(Math.max(1, 28 - CharWidth.of(name)));
+ List<Span> spans = new ArrayList<>(
+ List.of(
+ Span.styled(String.format(" %2d. ", number),
Theme.muted()),
+ Span.styled(name, style),
+ Span.styled(String.format("%8s",
duration(step.durationMs())), Style.EMPTY.fg(Theme.baseFg()))));
+ if (!step.tool()) {
+ spans.add(Span.styled(" " + tokens(step.inputTokens()) + "→" +
tokens(step.outputTokens()), Theme.muted()));
+ if (step.cachedTokens() > 0) {
+ spans.add(Span.styled(" (" + tokens(step.cachedTokens()) + "
cached)", Theme.muted()));
+ }
+ if (step.finishReason() != null) {
+ spans.add(Span.styled(" " + step.finishReason(),
Theme.muted()));
+ }
+ }
+ return Line.from(spans);
+ }
+
+ static String duration(long ms) {
+ return ms < 1000 ? ms + "ms" : AiPanel.formatSeconds(ms);
+ }
+
+ private static String percent(long part, long whole) {
+ return whole > 0 ? " (" + (part * 100 / whole) + "%)" : "";
+ }
+
+ private static String tokens(long tokens) {
+ return LlmClient.formatTokens((int) Math.min(Integer.MAX_VALUE,
tokens));
+ }
+
+ /** The text on one line, cut by display width (a value may hold CJK text
or emoji). */
+ private static String oneLine(String text, int max) {
+ String line = text.replaceAll("\\s+", " ").strip();
+ return CharWidth.of(line) > max ? CharWidth.substringByWidth(line, max
- 1) + "…" : line;
+ }
+
+ private static String operation(SpanEntry span) {
+ return span != null ? text(span.attributes(),
GenAiAttributes.OPERATION_NAME) : null;
+ }
+
+ private static String model(Map<String, Object> attrs) {
+ String model = orElse(text(attrs, GenAiAttributes.RESPONSE_MODEL),
text(attrs, GenAiAttributes.REQUEST_MODEL));
+ return "unknown".equals(model) ? null : model;
+ }
+
+ private static String orElse(String value, String fallback) {
+ return value != null ? value : fallback;
+ }
+
+ private static String text(Map<String, Object> attrs, String key) {
+ Object value = attrs != null ? attrs.get(key) : null;
+ if (value == null) {
+ return null;
+ }
+ String text = value.toString();
+ return text.isBlank() ? null : text;
+ }
+
+ private static long number(Map<String, Object> attrs, String key) {
+ Object value = attrs != null ? attrs.get(key) : null;
+ if (value instanceof Number n) {
+ return n.longValue();
+ }
+ try {
+ return value != null ? Long.parseLong(value.toString()) : 0;
+ } catch (NumberFormatException e) {
+ return 0;
+ }
+ }
+}
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SpansTab.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SpansTab.java
index 8b655074e6dc..ac8254872c89 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SpansTab.java
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SpansTab.java
@@ -33,6 +33,7 @@ import dev.tamboui.layout.Layout;
import dev.tamboui.layout.Rect;
import dev.tamboui.style.Style;
import dev.tamboui.terminal.Frame;
+import dev.tamboui.text.CharWidth;
import dev.tamboui.text.Line;
import dev.tamboui.text.Span;
import dev.tamboui.text.Text;
@@ -497,7 +498,7 @@ class SpansTab extends AbstractTab {
int labelWidth = 0;
for (WaterfallNode n : nodes) {
int indent = n.depth * 2;
- labelWidth = Math.max(labelWidth, indent +
spanLabel(n.span).length());
+ labelWidth = Math.max(labelWidth, indent +
CharWidth.of(spanLabel(n.span)));
}
labelWidth = Math.min(labelWidth + 2, inner.width() / 3);
@@ -533,12 +534,13 @@ class SpansTab extends AbstractTab {
boolean selected) {
String indicator = selected ? "▸ " : " ";
String indent = " ".repeat(node.depth);
+ // by display width: a GenAI label starts with a symbol that may take
two cells
String label = indent + spanLabel(node.span);
- if (label.length() > labelWidth) {
- label = label.substring(0, labelWidth - 1) + "…";
- } else {
- label = String.format("%-" + labelWidth + "s", label);
+ int width = CharWidth.of(label);
+ if (width > labelWidth) {
+ label = CharWidth.substringByWidth(label, labelWidth - 1) + "…";
}
+ label += " ".repeat(Math.max(0, labelWidth - CharWidth.of(label)));
// Calculate bar offset and width relative to trace timeline
long spanStart = node.span.startEpochNanos() - traceStart;
@@ -568,6 +570,9 @@ class SpansTab extends AbstractTab {
} else if (!camelSpan) {
labelStyle = selected ? Theme.notice().bold() : Theme.notice();
bandStyle = Theme.notice();
+ } else if (GenAiTranscript.isGenAiSpan(node.span)) {
+ labelStyle = GenAiSpanView.style(node.span, selected);
+ bandStyle = TuiHelper.colorForDuration(node.span.durationMs(),
minDuration, maxDuration);
} else {
labelStyle = selected ? Style.EMPTY.fg(Theme.accent()).bold() :
Style.EMPTY.fg(Theme.accent());
bandStyle = TuiHelper.colorForDuration(node.span.durationMs(),
minDuration, maxDuration);
@@ -632,6 +637,10 @@ class SpansTab extends AbstractTab {
if (GenAiTranscript.isGenAiSpan(span)) {
lines.add(conversationLine(span));
}
+ if (GenAiSpanView.isAgentRun(span)) {
+ List<SpanEntry> trace = spans.get().stream().filter(s ->
selectedTraceId.equals(s.traceId())).toList();
+
lines.addAll(GenAiSpanView.agentRunLines(GenAiSpanView.agentRun(span, trace)));
+ }
// Attributes as individual key: value lines
if (span.attributes() != null && !span.attributes().isEmpty()) {
@@ -914,6 +923,9 @@ class SpansTab extends AbstractTab {
}
private static String spanLabel(SpanEntry span) {
+ if (GenAiTranscript.isGenAiSpan(span)) {
+ return GenAiSpanView.label(span);
+ }
String name = span.name();
Map<String, Object> attrs = span.attributes();
if (attrs != null) {
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/resources/tui/help/spans.md
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/resources/tui/help/spans.md
index 479f5df71404..45e55b274337 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/resources/tui/help/spans.md
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/resources/tui/help/spans.md
@@ -47,6 +47,22 @@ flow. Error spans are always shown regardless of the toggle.
Press **Esc** to return to the trace list.
+### AI Agent Runs
+
+GenAI spans get their own labels and colours in the waterfall:
+
+- **◆ agent** — an agent run (`invoke_agent`) with its name and model
+- **● chat** — a model call with its model, input→output tokens and
+ finish reason (`tool_calls` when the model asked for a tool)
+- **⚙ tool** — a tool call (`execute_tool`) with its name and, at level
+ `full`, its arguments
+
+Select an agent run to see its summary in the detail panel: the model,
+the number of model and tool calls, the tokens (input, output, cached),
+how its time splits into model calls, tool calls and the rest, and the
+steps one by one. Agent runs and tool calls are recorded from GenAI
+observability level `detailed` on (`camel.aiObservability.level`).
+
### AI Conversations
On a GenAI span (a model call such as `chat`, an agent run `invoke_agent`,
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiSpanViewTest.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiSpanViewTest.java
new file mode 100644
index 000000000000..c55dc7aa9e63
--- /dev/null
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/GenAiSpanViewTest.java
@@ -0,0 +1,176 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.dsl.jbang.core.commands.tui;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import dev.tamboui.text.CharWidth;
+import dev.tamboui.text.Line;
+import dev.tamboui.text.Span;
+import org.apache.camel.component.ai.observability.GenAiAttributes;
+import org.apache.camel.dsl.jbang.core.commands.tui.GenAiSpanView.AgentRun;
+import org.apache.camel.dsl.jbang.core.commands.tui.GenAiSpanView.Step;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+class GenAiSpanViewTest {
+
+ @BeforeEach
+ void setUp() {
+ Theme.resetForTesting();
+ }
+
+ @Test
+ void labelOfAnAgentRun() {
+ assertThat(GenAiSpanView.label(agent())).isEqualTo("◆ agent
support-agent · llama3.2");
+ }
+
+ @Test
+ void labelOfAModelCallHasItsTokensAndFinishReason() {
+ assertThat(GenAiSpanView.label(chat("chat1", "agent", 100, 236, 1660,
25, 0, "tool_calls")))
+ .isEqualTo("● chat llama3.2 · 1.7k→25 · tool_calls");
+ SpanEntry embeddings = span("e", "", 0, 10, attrs("embeddings",
GenAiAttributes.REQUEST_MODEL, "unknown"));
+ assertThat(GenAiSpanView.label(embeddings)).isEqualTo("● embeddings");
+ }
+
+ @Test
+ void labelOfAToolCallHasItsArgumentsOnOneLine() {
+ assertThat(GenAiSpanView.label(tool("tool", "agent", 340, 1, "{\n
\"orderId\": \"A-17\"\n}")))
+ .isEqualTo("⚙ tool lookupOrder { \"orderId\": \"A-17\" }");
+ String prefix = "⚙ tool lookupOrder ";
+ assertThat(GenAiSpanView.label(tool("tool", "agent", 340, 1,
"{\"note\":\"" + "x".repeat(60) + "\"}")))
+ .satisfies(label ->
assertThat(CharWidth.of(label)).isEqualTo(CharWidth.of(prefix) + 40))
+ .endsWith("…");
+ // cut by display width, never inside a wide character, a flag or a
ZWJ emoji
+ String wide =
"{\"city\":\"東京\",\"flag\":\"\uD83C\uDDEB\uD83C\uDDF7\",\"who\":\"\uD83D\uDC69\u200D\uD83D\uDCBB\","
+ + "\"note\":\"東京東京東京東京東京東京\"}";
+ String label = GenAiSpanView.label(tool("tool", "agent", 340, 1,
wide));
+
assertThat(CharWidth.of(label)).isLessThanOrEqualTo(CharWidth.of(prefix) + 40);
+ assertThat(label).startsWith(prefix +
"{\"city\":\"東京\",\"flag\":\"\uD83C\uDDEB\uD83C\uDDF7\"").endsWith("…");
+ assertThat(GenAiSpanView.label(tool("tool", "agent", 340, 1,
null))).isEqualTo("⚙ tool lookupOrder");
+ }
+
+ @Test
+ void agentRunHasItsStepsInOrder() {
+ AgentRun run = GenAiSpanView.agentRun(agent(), trace());
+
+ assertThat(run.agentName()).isEqualTo("support-agent");
+ assertThat(run.model()).isEqualTo("llama3.2");
+ assertThat(run.provider()).isEqualTo("openai");
+ assertThat(run.conversationId()).isEqualTo("conv-1");
+ assertThat(run.steps()).extracting(Step::name).containsExactly("chat
llama3.2", "lookupOrder", "chat llama3.2");
+ assertThat(run.modelCalls()).isEqualTo(2);
+ assertThat(run.toolCalls()).isEqualTo(1);
+ assertThat(run.inputTokens()).isEqualTo(1660 + 1700);
+ assertThat(run.outputTokens()).isEqualTo(25 + 12);
+ assertThat(run.cachedTokens()).isEqualTo(1600);
+ assertThat(run.modelMs()).isEqualTo(236 + 146);
+ assertThat(run.toolMs()).isEqualTo(1);
+ }
+
+ @Test
+ void agentRunLeavesOutTheStepsOfAnotherRun() {
+ SpanEntry inner = span("inner", "tool", 350, 50, attrs("invoke_agent",
GenAiAttributes.AGENT_NAME, "helper"));
+ SpanEntry innerChat = chat("innerChat", "inner", 360, 30, 10, 5, 0,
"stop");
+ List<SpanEntry> spans = new ArrayList<>(trace());
+ spans.add(inner);
+ spans.add(innerChat);
+
+ assertThat(GenAiSpanView.agentRun(agent(), spans).steps()).hasSize(3);
+ assertThat(GenAiSpanView.agentRun(inner,
spans).steps()).extracting(Step::span).containsExactly(innerChat);
+ }
+
+ @Test
+ void agentRunLinesShowStepsTokensAndTime() {
+ String text =
text(GenAiSpanView.agentRunLines(GenAiSpanView.agentRun(agent(), trace())));
+
+ assertThat(text)
+ .contains("Agent: support-agent Model: llama3.2 (openai)
Conversation id: conv-1")
+ .contains("Steps: 2 model calls, 1 tool call Tokens: 3.4k in
/ 37 out / 1.6k cached")
+ .contains("Time: 385ms = model 382ms (99%) + tools 1ms (0%)
+ other 2ms")
+ .contains(" 1. ● chat llama3.2")
+ .contains(" 2. ⚙ lookupOrder")
+ .contains("1.7k→12 (1.6k cached) stop");
+ }
+
+ /** An agent run: a model call, a tool call (whose route spans nest under
it), a model call under a Camel span. */
+ private static List<SpanEntry> trace() {
+ SpanEntry toolRoute = span("toolRoute", "tool", 341, 1,
Map.of("camel.uri", "ai-tool://lookupOrder"));
+ SpanEntry step = span("step", "agent", 380, 150, Map.of("camel.uri",
"openai:chat-completion"));
+ return List.of(agent(),
+ chat("chat1", "agent", 100, 236, 1660, 25, 0, "tool_calls"),
+ tool("tool", "agent", 340, 1, "{\"orderId\":\"A-17\"}"),
+ toolRoute,
+ step,
+ chat("chat2", "step", 382, 146, 1700, 12, 1600, "stop"));
+ }
+
+ private static SpanEntry agent() {
+ return span("agent", "route", 99, 385, attrs("invoke_agent",
+ GenAiAttributes.AGENT_NAME, "support-agent",
+ GenAiAttributes.REQUEST_MODEL, "llama3.2",
+ GenAiAttributes.PROVIDER_NAME, "openai",
+ GenAiAttributes.CONVERSATION_ID, "conv-1"));
+ }
+
+ private static SpanEntry chat(
+ String id, String parent, long start, long ms, long in, long out,
long cached, String finish) {
+ Map<String, Object> attrs = attrs("chat",
GenAiAttributes.REQUEST_MODEL, "llama3.2",
+ GenAiAttributes.FINISH_REASONS, finish);
+ attrs.put(GenAiAttributes.INPUT_TOKENS, in);
+ attrs.put(GenAiAttributes.OUTPUT_TOKENS, out);
+ if (cached > 0) {
+ attrs.put(GenAiAttributes.CACHE_READ_INPUT_TOKENS, cached);
+ }
+ return span(id, parent, start, ms, attrs);
+ }
+
+ private static SpanEntry tool(String id, String parent, long start, long
ms, String arguments) {
+ Map<String, Object> attrs = attrs("execute_tool",
GenAiAttributes.TOOL_NAME, "lookupOrder");
+ if (arguments != null) {
+ attrs.put(GenAiAttributes.TOOL_CALL_ARGUMENTS, arguments);
+ }
+ return span(id, parent, start, ms, attrs);
+ }
+
+ private static Map<String, Object> attrs(String operation, String...
keyValues) {
+ Map<String, Object> attrs = new HashMap<>();
+ attrs.put(GenAiAttributes.OPERATION_NAME, operation);
+ for (int i = 0; i < keyValues.length; i += 2) {
+ attrs.put(keyValues[i], keyValues[i + 1]);
+ }
+ return attrs;
+ }
+
+ private static SpanEntry span(String id, String parent, long startMs, long
ms, Map<String, Object> attributes) {
+ return new SpanEntry(
+ "trace-1", id, parent, id, "INTERNAL", "OK", startMs *
1_000_000L,
+ (startMs + ms) * 1_000_000L, ms, "support-agent", null,
"camel", attributes);
+ }
+
+ private static String text(List<Line> lines) {
+ return lines.stream()
+ .map(line ->
line.spans().stream().map(Span::content).collect(Collectors.joining()))
+ .collect(Collectors.joining("\n"));
+ }
+}
diff --git
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/SpansTabRenderTest.java
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/SpansTabRenderTest.java
index 1e0bd3b2ed56..ba6cb502ba21 100644
---
a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/SpansTabRenderTest.java
+++
b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/SpansTabRenderTest.java
@@ -208,6 +208,70 @@ class SpansTabRenderTest {
assertThat(tab.transcriptForTesting().markdownForTesting()).contains(TranscriptOverlay.NO_CONTENT);
}
+ @Test
+ void waterfallLabelsGenAiSpansAndSummarizesTheAgentRun() {
+ spans.get().add(new SpanEntry(
+ "trace0001", "agent", null, "invoke_agent", "INTERNAL", "OK",
0L, 400_000_000L, 400, "route1", null,
+ "camel", Map.of(GenAiAttributes.OPERATION_NAME, "invoke_agent",
+ GenAiAttributes.AGENT_NAME, "support-agent",
+ GenAiAttributes.REQUEST_MODEL, "llama3.2")));
+ spans.get().add(new SpanEntry(
+ "trace0001", "chat", "agent", "chat", "CLIENT", "OK", 0L,
300_000_000L, 300, "route1", null,
+ "camel", Map.of(GenAiAttributes.OPERATION_NAME, "chat",
+ GenAiAttributes.REQUEST_MODEL, "llama3.2",
+ GenAiAttributes.INPUT_TOKENS, 166L,
+ GenAiAttributes.OUTPUT_TOKENS, 25L,
+ GenAiAttributes.FINISH_REASONS, "stop")));
+ spans.get().add(new SpanEntry(
+ "trace0001", "tool", "agent", "execute_tool", "INTERNAL",
"OK", 300_000_000L, 310_000_000L, 10,
+ "route1", null, "camel",
Map.of(GenAiAttributes.OPERATION_NAME, "execute_tool",
+ GenAiAttributes.TOOL_NAME, "lookupOrder")));
+ SpansTab tab = new SpansTab(ctx, spans);
+ TuiTestHelper.renderToString(tab, 160, 34);
+ tab.handleKeyEvent(KeyEvent.ofKey(KeyCode.ENTER));
+
+ assertThat(TuiTestHelper.renderToString(tab, 160, 34))
+ .contains("◆ agent support-agent · llama3.2")
+ .contains("● chat llama3.2 · 166→25 · stop")
+ .contains("⚙ tool lookupOrder")
+ .contains("Steps: 1 model call, 1 tool call")
+ .contains("1. ● chat llama3.2");
+ }
+
+ @Test
+ void waterfallBarsLineUpWhateverTheWidthOfTheLabels() {
+ // GenAI symbols, a CJK route, a flag and a ZWJ emoji: all spans start
at 0, so all bars start in one column
+ spans.get().add(new SpanEntry(
+ "trace0001", "root", null, "root", "INTERNAL", "OK", 0L,
400_000_000L, 400,
+ "注文ルート", null, "camel", Map.of("camel.uri",
"timer://\uD83C\uDDEB\uD83C\uDDF7")));
+ spans.get().add(new SpanEntry(
+ "trace0001", "agent", "root", "agent", "INTERNAL", "OK", 0L,
300_000_000L, 300,
+ "route1", null, "camel",
Map.of(GenAiAttributes.OPERATION_NAME, "invoke_agent",
+ GenAiAttributes.AGENT_NAME,
"\uD83D\uDC69\u200D\uD83D\uDCBB")));
+ spans.get().add(new SpanEntry(
+ "trace0001", "tool", "agent", "tool", "INTERNAL", "OK", 0L,
200_000_000L, 200,
+ "route1", null, "camel",
Map.of(GenAiAttributes.OPERATION_NAME, "execute_tool",
+ GenAiAttributes.TOOL_NAME, "lookupOrder")));
+ SpansTab tab = new SpansTab(ctx, spans);
+ TuiTestHelper.renderToString(tab, 140, 30);
+ tab.handleKeyEvent(KeyEvent.ofKey(KeyCode.ENTER));
+
+ Rect area = new Rect(0, 0, 140, 30);
+ Buffer buffer = Buffer.empty(area);
+ tab.render(Frame.forTesting(buffer), area);
+
+ List<Integer> barColumns = new ArrayList<>();
+ for (int y = 0; y < buffer.height(); y++) {
+ for (int x = 0; x < buffer.width(); x++) {
+ if ("█".equals(buffer.get(x, y).symbol())) {
+ barColumns.add(x);
+ break;
+ }
+ }
+ }
+ assertThat(barColumns).hasSize(3).containsOnly(barColumns.get(0));
+ }
+
private static String footer(SpansTab tab) {
List<Span> footerSpans = new ArrayList<>();
tab.renderFooter(footerSpans);