You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by da...@apache.org on 2026/09/09 06:02:12 UTC
(camel) branch main updated: camel-jbang-plugin-tui: extract shared diagram detail panels out of RoutesTab and DiagramTab
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 0f83e1be0d72 camel-jbang-plugin-tui: extract shared diagram detail panels out of RoutesTab and DiagramTab
0f83e1be0d72 is described below
commit 0f83e1be0d7263f075a82b0fb224360658aade25
Author: Claus Ibsen <cl...@gmail.com>
AuthorDate: Wed Sep 9 08:01:15 2026 +0200
camel-jbang-plugin-tui: extract shared diagram detail panels out of RoutesTab and DiagramTab
RoutesTab and DiagramTab carried ~1100 near-identical lines: the route
and EIP info panels, the catalog-backed EIP detail panel with its
processor-detail cache, the inline quick-doc builders and the catalog
cache. Move them into three focused classes so both tabs share one
implementation:
- DiagramDetailSupport owns the processor-detail cache, detail scroll
state and renders the route info, EIP info and EIP detail panels.
- EipDocSupport holds the stateless catalog-to-markdown and inline
quick-doc helpers (also used by SourceTab and SpringBootMetadataHelper).
- CatalogCache replaces four copies of the per-version catalog cache
(RoutesTab, DiagramTab, EndpointsTab, SourceTab).
findClosestEipNode moves to DiagramSupport and numWidth to TuiHelper.
RoutesTab shrinks from 2658 to 1657 lines, DiagramTab from 1690 to 1022.
camel-jbang-plugin-tui: move tab help pages from Java text blocks to markdown resources
The 41 getHelpText() implementations held about 2900 lines of markdown
as Java text blocks, burying the tab logic under prose. Each page now
lives in src/main/resources/tui/help/<tab>.md and is loaded (and cached)
through DocHelper.loadHelpText(). MemoryLeakTab keeps its icon
placeholders via formatted(). HelpTextResourcesTest checks that every
referenced page resolves.
camel-jbang-plugin-tui: split CamelMonitor.doCall into named wiring steps
doCall was a 472-line method that created the data service, every popup,
the tab registry, the MCP facade and the servers inline. It is now a
30-line sequence of private methods (createDataService, createActionsPopup,
createTabRegistry, createPopupManager, createMcpFacade, startMcpServer,
startWebServer, runTui, ...) with the statements kept in their original
order. The MCP json path becomes a field so startup and shutdown share it.
camel-jbang-plugin-tui: split StatusParser.parseIntegration into per-section parsers
parseIntegration walked every section of the status JSON in one 682-line
method. Each section (runtime, statistics, memory, routes, consumers,
producers, endpoints, circuit breakers, inflight, REST, properties,
datasources, SQL trace, vaults, ...) now has its own private static
parseXxx(info, root) method, mirroring the existing parseKafkaSection
style, and parseIntegration reads as a list of the sections it fills.
No section shared local state, so the code moved verbatim.
camel-jbang-plugin-tui: move MCP tool definitions out of TuiToolRegistry
The 496-line buildToolDefinitions method that declared all 48 MCP tools
moves to a new data-only TuiToolDefinitions class, grouped into
interaction, structured data, catalog, log and example tools following
the section comments it already had. TuiToolRegistry keeps the dispatch
and the call* implementations.
camel-jbang-plugin-tui: split YAML analysis, refactoring and validation helpers out of SourceViewer
SourceViewer (4161 lines) mixed the viewer/editor with three independent
concerns that only needed the edit buffer or plain strings:
- YamlSourceContext: structural analysis of the Camel YAML being edited
(enclosing component/EIP/URI, sibling keys and parameters, insertion
and paste indentation, scope rows, breadcrumb). Instance methods read
the shared TextAreaState; the string helpers are static.
- SourceRefactorings: the pure text transformations behind extract
route to file, replace URI and extract value to property.
- SourceValidationSupport: turning validation messages into the inline
error map.
SourceViewer exposes yamlContext() for tests and shrinks to 3045 lines.
Tests are updated to call the helpers on their new classes.
camel-jbang-plugin-tui: move Source tab completion and validation providers to SourceEditAssist
SourceTab carried ~1850 lines of autocomplete, quick-doc, validation and
deprecation providers for Camel YAML and properties files, plus the
catalog, completion-tree, Spring Boot metadata and placeholder caches
they use. They move verbatim into SourceEditAssist, which SourceTab
wires into the SourceViewer through a single configureEditAssist(path)
method (the two copies of that wiring are folded into one). SourceTab
shrinks from 3313 to 1333 lines and keeps the file browser, route index
and jump-link logic.
camel-jbang-plugin-tui: break up HistoryTab.handleKeyEvent and OverviewTab.render
HistoryTab.handleKeyEvent (310 lines) now delegates to
handleHistoryDiagramKeys, handleTraceDetailKeys, handleTraceListKeys and
handleHistoryListKeys, one per view mode. OverviewTab.render (506 lines)
builds the integrations table through buildTopModeTable /
buildOverviewTable returning a TableSpec record, and draws the throughput
chart in renderThroughputChart. Code moved verbatim; only local
declarations were hoisted into the new methods.
camel-jbang-plugin-tui: break up the remaining 200-500 line key and render methods
- RoutesTab.handleKeyEvent -> handleDiagramKeys / handleTableKeys;
RoutesTab.render -> renderDiagramView, buildRouteTopTable, buildRouteTable
- DiagramTab.handleKeyEvent -> handleNodeNavigationKeys / handleDiagramActionKeys
- ActionsPopup.handleKeyEvent -> handleChildPopupKeys / handleMenuKeys
- CamelMonitor.handleGlobalKeys -> isTextInputActive, handleTabDigitKeys,
handleFunctionKeys
Each key handler was a sequence of independently guarded if-blocks, so
the groups were cut at their existing section comments and the blocks
moved verbatim. The only semantic nuance: a digit key whose tab switch
is refused now falls through to the (non-matching) function-key checks
instead of returning immediately; the result is the same.
Regen
camel-console: hide routes created by Kamelets from the route-topology console
The Diagram tab in the TUI showed three routes while the Route tab showed
one: the topology dumper walks all route definitions, whereas the route
console only sees routes registered in JMX, which excludes Kamelet
routes by default. The route-topology console now drops nodes, edges and
external endpoints belonging to Kamelet-created routes unless the new
kamelets=true option asks for them. The CLI connector forwards the
option and camel cmd route-topology gains --kamelets.
camel-jbang-plugin-tui: show AI response times with sub-second precision
The AI panel truncated response times to whole seconds when recording a
reply, so the conversation footer, title bar, activity log and the usage
view's average and total latency all showed e.g. "2s". The conversation
entry now keeps milliseconds and every display goes through the existing
formatSeconds helper, giving "2.3s". Usage entries already stored
millisecond latency, so the average is now computed from that directly.
camel-jbang-plugin-tui: record tool call durations and split AI vs tool time in the AI panel
Each tool result line in the AI log now carries how long the tool took
("tui_get_table (42ms)"). The agent loop accumulates model latency and
tool execution time per turn, so an assistant reply with tool calls shows
"5.2s, ai 4.1s, tools 1.1s/3" in the log and below the answer, and the
usage view breaks the session down into AI time and tool time with the
number of calls.
camel-jbang-plugin-tui: show the AI versus tool time breakdown in the AI usage view
The usage view (Ctrl+U) gets a "Time per question" chart beside the
token chart with one AI bar and one tool bar per answered question, an
AVG latency column in the per-model table, and the /usage summary prints
the session's AI time and tool time. The F1 help and the TUI manual
describe the breakdown and the per-tool durations in the AI log.
camel-jbang-plugin-tui: format the /usage summary as markdown in the AI chat
The chat renders system messages through MarkdownView, but /usage
printed a plain text blob. It now prints a bold headline, a bullet list
for tokens, average latency, AI vs tool time and the last request, a
table with one row per model (requests, in, out, total, avg latency),
and an italic tip about Ctrl+U. Latencies use the same one-decimal
seconds as the rest of the panel.
camel-jbang-plugin-tui: capitalize Tool time in the /usage summary
Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
Signed-off-by: Claus Ibsen <cl...@gmail.com>
---
.../apache/camel/dev-console/route-topology.json | 19 +-
.../impl/console/RouteTopologyDevConsole.java | 40 +-
.../RouteTopologyDevConsoleKameletTest.java | 86 +
.../ROOT/pages/camel-4x-upgrade-guide-4_23.adoc | 4 +
.../modules/ROOT/pages/camel-jbang-managing.adoc | 1 +
.../modules/ROOT/pages/camel-jbang-tui.adoc | 11 +-
.../camel-jbang-cmd-route-topology.adoc | 1 +
.../camel/cli/connector/LocalCliConnector.java | 3 +-
.../LangChain4jAgentEndpointBuilderFactory.java | 14 -
.../META-INF/camel-jbang-commands-metadata.json | 2 +-
.../commands/action/CamelRouteTopologyAction.java | 5 +
.../dsl/jbang/core/commands/tui/ActionsPopup.java | 286 +--
.../dsl/jbang/core/commands/tui/ActivityTab.java | 54 +-
.../camel/dsl/jbang/core/commands/tui/AiPanel.java | 202 +-
.../dsl/jbang/core/commands/tui/BeansTab.java | 49 +-
.../dsl/jbang/core/commands/tui/BrowseTab.java | 51 +-
.../dsl/jbang/core/commands/tui/CamelMonitor.java | 266 ++-
.../dsl/jbang/core/commands/tui/CatalogCache.java | 70 +
.../dsl/jbang/core/commands/tui/CatalogTab.java | 82 +-
.../jbang/core/commands/tui/CircuitBreakerTab.java | 95 +-
.../dsl/jbang/core/commands/tui/ClasspathTab.java | 61 +-
.../jbang/core/commands/tui/ConfigurationTab.java | 46 +-
.../dsl/jbang/core/commands/tui/ConsumersTab.java | 64 +-
.../dsl/jbang/core/commands/tui/CveAuditTab.java | 42 +-
.../dsl/jbang/core/commands/tui/DataSourceTab.java | 42 +-
.../core/commands/tui/DiagramDetailSupport.java | 557 +++++
.../jbang/core/commands/tui/DiagramSupport.java | 44 +
.../dsl/jbang/core/commands/tui/DiagramTab.java | 871 +-------
.../dsl/jbang/core/commands/tui/DocHelper.java | 19 +
.../dsl/jbang/core/commands/tui/EipDocSupport.java | 507 +++++
.../dsl/jbang/core/commands/tui/EndpointsTab.java | 133 +-
.../dsl/jbang/core/commands/tui/ErrorsTab.java | 125 +-
.../dsl/jbang/core/commands/tui/EventTab.java | 29 +-
.../core/commands/tui/GotoSourceNodePopup.java | 2 +-
.../dsl/jbang/core/commands/tui/HealthTab.java | 79 +-
.../jbang/core/commands/tui/HeapHistogramTab.java | 54 +-
.../dsl/jbang/core/commands/tui/HistoryTab.java | 529 ++---
.../camel/dsl/jbang/core/commands/tui/HttpTab.java | 61 +-
.../dsl/jbang/core/commands/tui/InflightTab.java | 52 +-
.../jbang/core/commands/tui/InternalTasksTab.java | 40 +-
.../camel/dsl/jbang/core/commands/tui/JfrTab.java | 29 +-
.../dsl/jbang/core/commands/tui/KafkaTab.java | 40 +-
.../camel/dsl/jbang/core/commands/tui/LogTab.java | 100 +-
.../core/commands/tui/MavenDependenciesTab.java | 84 +-
.../dsl/jbang/core/commands/tui/MemoryLeakTab.java | 132 +-
.../dsl/jbang/core/commands/tui/MemoryTab.java | 87 +-
.../dsl/jbang/core/commands/tui/MetricsTab.java | 97 +-
.../dsl/jbang/core/commands/tui/NetworkTab.java | 34 +-
.../dsl/jbang/core/commands/tui/OverviewTab.java | 987 ++++-----
.../dsl/jbang/core/commands/tui/ProducersTab.java | 24 +-
.../core/commands/tui/RouteControllerTab.java | 35 +-
.../dsl/jbang/core/commands/tui/RoutesTab.java | 1757 +++-------------
.../dsl/jbang/core/commands/tui/SecretsTab.java | 40 +-
.../tui/{SourceTab.java => SourceEditAssist.java} | 1601 ++-------------
.../core/commands/tui/SourceRefactorings.java | 221 ++
.../dsl/jbang/core/commands/tui/SourceTab.java | 2123 +-------------------
.../core/commands/tui/SourceValidationSupport.java | 96 +
.../dsl/jbang/core/commands/tui/SourceViewer.java | 1176 +----------
.../dsl/jbang/core/commands/tui/SpansTab.java | 92 +-
.../commands/tui/SpringBootMetadataHelper.java | 2 +-
.../dsl/jbang/core/commands/tui/SqlQueryTab.java | 35 +-
.../dsl/jbang/core/commands/tui/SqlTraceTab.java | 41 +-
.../dsl/jbang/core/commands/tui/StartupTab.java | 68 +-
.../dsl/jbang/core/commands/tui/StatusParser.java | 243 ++-
.../dsl/jbang/core/commands/tui/ThreadsTab.java | 74 +-
.../jbang/core/commands/tui/TransformersTab.java | 26 +-
.../dsl/jbang/core/commands/tui/TuiHelper.java | 12 +
.../core/commands/tui/TuiToolDefinitions.java | 600 ++++++
.../jbang/core/commands/tui/TuiToolRegistry.java | 539 +----
.../jbang/core/commands/tui/TypeConvertersTab.java | 38 +-
.../jbang/core/commands/tui/YamlSourceContext.java | 924 +++++++++
.../src/main/resources/tui/help/activity.md | 51 +
.../src/main/resources/tui/help/beans.md | 46 +
.../src/main/resources/tui/help/browse.md | 48 +
.../src/main/resources/tui/help/catalog.md | 79 +
.../src/main/resources/tui/help/circuit-breaker.md | 92 +
.../src/main/resources/tui/help/classpath.md | 58 +
.../src/main/resources/tui/help/configuration.md | 43 +
.../src/main/resources/tui/help/consumers.md | 61 +
.../src/main/resources/tui/help/cve-audit.md | 39 +
.../src/main/resources/tui/help/data-source.md | 39 +
.../src/main/resources/tui/help/diagram.md | 125 ++
.../src/main/resources/tui/help/endpoints.md | 99 +
.../src/main/resources/tui/help/errors.md | 122 ++
.../src/main/resources/tui/help/event.md | 26 +
.../src/main/resources/tui/help/health.md | 76 +
.../src/main/resources/tui/help/heap-histogram.md | 51 +
.../src/main/resources/tui/help/history.md | 157 ++
.../src/main/resources/tui/help/http.md | 58 +
.../src/main/resources/tui/help/inflight.md | 49 +
.../src/main/resources/tui/help/internal-tasks.md | 37 +
.../src/main/resources/tui/help/jfr.md | 26 +
.../src/main/resources/tui/help/kafka.md | 37 +
.../src/main/resources/tui/help/log.md | 97 +
.../main/resources/tui/help/maven-dependencies.md | 81 +
.../src/main/resources/tui/help/memory-leak.md | 129 ++
.../src/main/resources/tui/help/memory.md | 84 +
.../src/main/resources/tui/help/metrics.md | 94 +
.../src/main/resources/tui/help/network.md | 31 +
.../src/main/resources/tui/help/overview.md | 143 ++
.../src/main/resources/tui/help/producers.md | 21 +
.../main/resources/tui/help/route-controller.md | 32 +
.../src/main/resources/tui/help/routes.md | 154 ++
.../src/main/resources/tui/help/secrets.md | 37 +
.../src/main/resources/tui/help/source.md | 94 +
.../src/main/resources/tui/help/spans.md | 89 +
.../src/main/resources/tui/help/sql-query.md | 32 +
.../src/main/resources/tui/help/sql-trace.md | 38 +
.../src/main/resources/tui/help/startup.md | 65 +
.../src/main/resources/tui/help/threads.md | 71 +
.../src/main/resources/tui/help/transformers.md | 23 +
.../src/main/resources/tui/help/type-converters.md | 35 +
.../dsl/jbang/core/commands/tui/AiPanelTest.java | 10 +-
.../core/commands/tui/HelpTextResourcesTest.java | 86 +
.../commands/tui/SourceViewerPasteIndentTest.java | 24 +-
.../commands/tui/SourceViewerRefactorTest.java | 92 +-
.../core/commands/tui/YamlCompletionTest.java | 116 +-
.../commands/tui/YamlEndpointValidationTest.java | 34 +-
.../commands/tui/YamlSimpleValidationTest.java | 22 +-
119 files changed, 8140 insertions(+), 11068 deletions(-)
diff --git a/core/camel-console/src/generated/resources/META-INF/org/apache/camel/dev-console/route-topology.json b/core/camel-console/src/generated/resources/META-INF/org/apache/camel/dev-console/route-topology.json
index 7c4fe2e36fb6..26284535e933 100644
--- a/core/camel-console/src/generated/resources/META-INF/org/apache/camel/dev-console/route-topology.json
+++ b/core/camel-console/src/generated/resources/META-INF/org/apache/camel/dev-console/route-topology.json
@@ -28,9 +28,24 @@
"defaultValue": false,
"description": "Whether to include external systems (databases, messaging brokers, etc.) as nodes"
},
- "metric": {
+ "kamelets": {
"index": 1,
"kind": "option",
+ "displayName": "Kamelets",
+ "group": "query",
+ "label": "query",
+ "required": false,
+ "type": "boolean",
+ "javaType": "java.lang.Boolean",
+ "deprecated": false,
+ "autowired": false,
+ "secret": false,
+ "defaultValue": false,
+ "description": "Whether to include routes created by Kamelets. These are hidden by default, as they are an implementation detail of the Kamelet"
+ },
+ "metric": {
+ "index": 2,
+ "kind": "option",
"displayName": "Metric",
"group": "query",
"label": "query",
@@ -44,7 +59,7 @@
"description": "Whether to include live metrics (message counts) on nodes and edges"
},
"routes": {
- "index": 2,
+ "index": 3,
"kind": "option",
"displayName": "Routes",
"group": "query",
diff --git a/core/camel-console/src/main/java/org/apache/camel/impl/console/RouteTopologyDevConsole.java b/core/camel-console/src/main/java/org/apache/camel/impl/console/RouteTopologyDevConsole.java
index e48f43118e3a..8af931d7d7d8 100644
--- a/core/camel-console/src/main/java/org/apache/camel/impl/console/RouteTopologyDevConsole.java
+++ b/core/camel-console/src/main/java/org/apache/camel/impl/console/RouteTopologyDevConsole.java
@@ -19,9 +19,12 @@ package org.apache.camel.impl.console;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Set;
+import org.apache.camel.Route;
import org.apache.camel.api.management.ManagedCamelContext;
import org.apache.camel.api.management.mbean.ManagedRouteMBean;
import org.apache.camel.api.management.mbean.ManagedSendProcessorMBean;
@@ -90,6 +93,11 @@ public class RouteTopologyDevConsole extends AbstractDevConsole {
defaultValue = "false", javaType = "java.lang.Boolean")
public static final String ROUTES = "routes";
+ @Metadata(label = "query",
+ description = "Whether to include routes created by Kamelets. These are hidden by default, as they are an implementation detail of the Kamelet",
+ defaultValue = "false", javaType = "java.lang.Boolean")
+ public static final String KAMELETS = "kamelets";
+
public RouteTopologyDevConsole() {
super("camel", "route-topology", "Route Topology", "Route topology showing inter-route connections");
}
@@ -100,7 +108,7 @@ public class RouteTopologyDevConsole extends AbstractDevConsole {
if (dumper == null) {
return "";
}
- TopologyResult result = dumper.dumpTopology(getCamelContext());
+ TopologyResult result = filterKamelets(dumper.dumpTopology(getCamelContext()), options);
boolean external = optionBoolean(options, EXTERNAL, false);
StringBuilder sb = new StringBuilder();
@@ -135,7 +143,7 @@ public class RouteTopologyDevConsole extends AbstractDevConsole {
if (dumper == null) {
return JsonRecordSupport.toJsonObject(new Response(null, null, null, null));
}
- TopologyResult result = dumper.dumpTopology(getCamelContext());
+ TopologyResult result = filterKamelets(dumper.dumpTopology(getCamelContext()), options);
boolean metric = optionBoolean(options, METRIC, false);
boolean external = optionBoolean(options, EXTERNAL, false);
@@ -227,6 +235,34 @@ public class RouteTopologyDevConsole extends AbstractDevConsole {
return JsonRecordSupport.toJsonObject(response);
}
+ /**
+ * Removes the routes created by Kamelets, together with the edges and external endpoints that belong to them,
+ * unless the {@link #KAMELETS} option asks for them. Kamelet routes are an implementation detail of the Kamelet and
+ * are hidden the same way as in the route console (they are not registered in JMX by default).
+ */
+ private TopologyResult filterKamelets(TopologyResult result, Map<String, Object> options) {
+ if (optionBoolean(options, KAMELETS, false)) {
+ return result;
+ }
+ Set<String> hidden = new HashSet<>();
+ for (TopologyNode node : result.nodes()) {
+ Route route = getCamelContext().getRoute(node.routeId());
+ if (route != null && route.isCreatedByKamelet()) {
+ hidden.add(node.routeId());
+ }
+ }
+ if (hidden.isEmpty()) {
+ return result;
+ }
+ List<TopologyNode> nodes = result.nodes().stream()
+ .filter(n -> !hidden.contains(n.routeId())).toList();
+ List<TopologyEdge> edges = result.edges().stream()
+ .filter(e -> !hidden.contains(e.fromRouteId()) && !hidden.contains(e.toRouteId())).toList();
+ List<TopologyExternalEndpoint> externalEndpoints = result.externalEndpoints().stream()
+ .filter(e -> !hidden.contains(e.routeId())).toList();
+ return new TopologyResult(nodes, edges, externalEndpoints);
+ }
+
/**
* Collects per-endpoint metrics for producer endpoints by iterating managed send processors. Returns a map keyed by
* "routeId|normalizedUri" with value [exchangesTotal, exchangesFailed].
diff --git a/core/camel-console/src/test/java/org/apache/camel/impl/console/RouteTopologyDevConsoleKameletTest.java b/core/camel-console/src/test/java/org/apache/camel/impl/console/RouteTopologyDevConsoleKameletTest.java
new file mode 100644
index 000000000000..dc9c5d648d59
--- /dev/null
+++ b/core/camel-console/src/test/java/org/apache/camel/impl/console/RouteTopologyDevConsoleKameletTest.java
@@ -0,0 +1,86 @@
+/*
+ * 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.impl.console;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.console.DevConsole;
+import org.apache.camel.model.RouteDefinition;
+import org.apache.camel.support.PluginHelper;
+import org.apache.camel.util.json.JsonArray;
+import org.apache.camel.util.json.JsonObject;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Routes created by Kamelets are hidden from the topology unless asked for with {@code kamelets=true}.
+ */
+class RouteTopologyDevConsoleKameletTest extends ContextTestSupport {
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ // simulates the route a Kamelet creates internally, feeding the user route
+ RouteDefinition kamelet = from("timer:tick").routeId("mysource-1")
+ .to("direct:mysource");
+ kamelet.setKamelet(true);
+
+ from("direct:mysource").routeId("route1")
+ .to("mock:result");
+ }
+ };
+ }
+
+ @Test
+ void testKameletRoutesHiddenByDefault() {
+ DevConsole console = PluginHelper.getDevConsoleResolver(context).resolveDevConsole("route-topology");
+ JsonObject json = (JsonObject) console.call(DevConsole.MediaType.JSON);
+
+ assertEquals(List.of("route1"), routeIds((JsonArray) json.get("nodes")));
+ JsonArray edges = (JsonArray) json.get("edges");
+ assertTrue(edges == null || edges.isEmpty(), "edges to hidden kamelet routes must be removed");
+
+ String text = (String) console.call(DevConsole.MediaType.TEXT);
+ assertTrue(text.contains("Route Topology (1 routes"), text);
+ assertFalse(text.contains("mysource-1"), text);
+ }
+
+ @Test
+ void testKameletRoutesIncludedOnRequest() {
+ DevConsole console = PluginHelper.getDevConsoleResolver(context).resolveDevConsole("route-topology");
+ JsonObject json = (JsonObject) console.call(DevConsole.MediaType.JSON, Map.of("kamelets", "true"));
+
+ assertEquals(List.of("mysource-1", "route1"), routeIds((JsonArray) json.get("nodes")));
+ JsonArray edges = (JsonArray) json.get("edges");
+ assertEquals(1, edges.size());
+ JsonObject edge = (JsonObject) edges.get(0);
+ assertEquals("mysource-1", edge.getString("fromRouteId"));
+ assertEquals("route1", edge.getString("toRouteId"));
+ }
+
+ private static List<String> routeIds(JsonArray nodes) {
+ return nodes.stream().map(o -> ((JsonObject) o).getString("routeId")).sorted().toList();
+ }
+}
diff --git a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_23.adoc b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_23.adoc
index 117c059d53c8..54e703207e52 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_23.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_23.adoc
@@ -101,6 +101,10 @@ agree with that list. This affects consumers of the context status, such as the
(`registerRoutesCreateByKamelet=true`), they are counted as before. The JMX `ManagedCamelContext` MBean attributes
`TotalRoutes` and `StartedRoutes` are unchanged and still count every route.
+The `route-topology` developer console (used by `camel cmd route-topology` and the Camel TUI diagram) no longer
+includes routes created by Kamelets, as these are an implementation detail of the Kamelet and were already hidden
+from the route console. Set the `kamelets=true` option (or `--kamelets` on the CLI) to include them.
+
=== camel-dynamic-router
The `dynamic-router-control` endpoint no longer takes the subscription `predicate`, or the
diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-managing.adoc b/docs/user-manual/modules/ROOT/pages/camel-jbang-managing.adoc
index 107421fb034d..6e55603866cf 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-managing.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-managing.adoc
@@ -185,6 +185,7 @@ camel cmd route-topology myApp --external
----
The `--external` flag includes external systems (Kafka, databases, etc.) as nodes in the graph.
+Routes created by Kamelets are hidden, as they are an implementation detail of the Kamelet; use `--kamelets` to include them.
Both commands include live metrics by default — use `--metric=false` to disable.
TIP: The xref:camel-jbang-tui.adoc[Camel TUI] shows route diagrams and topology interactively.
diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
index b83fc7152c34..2463934bf9b9 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
@@ -989,13 +989,18 @@ Press *Ctrl+U* while the AI panel is open to toggle the AI Usage view. It shows
the embedded AI prompt (*TUI ask*) and from LLM calls made by the monitored integration (*integration*),
the latter taken from OpenTelemetry GenAI spans when observability is enabled on the integration. The
*Tokens per question* chart has one bar per question you asked, so a question that needed several tool
-calls shows as a single bar.
+calls shows as a single bar. The summary line splits the session time into *AI time* (waiting for the
+model) and *Tool time* (running the TUI tools the model called, with the number of calls), the model
+table has an *AVG* latency column, and the *Time per question* chart next to the token chart shows the
+two side by side for each question, so you can see whether a slow answer was the model or the tools.
=== AI log
Every request the panel makes is recorded in the AI log (*F2* -> _AI & MCP_ -> _AI Log_, or the
-`tui_get_ai_log` tool): the question, each tool the model called with its arguments and the size of
-the result, and a `Response` line with the elapsed time and the token counts. The `Response` line
+`tui_get_ai_log` tool): the question, each tool the model called with its arguments, the result with
+how long the tool took, and a `Response` line with the elapsed time and the token counts. When the
+model called tools, the elapsed time is broken down into the time spent waiting for the model and the
+time spent in tool calls (for example `5.2s, ai 4.1s, tools 1.1s/3`). The `Response` line
also shows whether the provider reused its cached prompt. For Ollama it prints the prompt-processing
(`prefill`) and generation (`gen`) time reported by the server -- a prefill of a fraction of a second
on a 10k-token prompt means the cache was hit, while a prefill of several seconds means the whole
diff --git a/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-cmd-route-topology.adoc b/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-cmd-route-topology.adoc
index 2eca996bd50d..be5d95e0a598 100644
--- a/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-cmd-route-topology.adoc
+++ b/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-cmd-route-topology.adoc
@@ -25,6 +25,7 @@ camel cmd route-topology [options]
| `--font-size` | Font size in logical pixels for node text | 12 | int
| `--ignore-loading-error` | Whether to ignore route loading and compilation errors (use this with care!) | false | boolean
| `--json` | Output in JSON Format | | boolean
+| `--kamelets` | Include routes created by Kamelets (hidden by default, only for a running Camel application) | | boolean
| `--metric` | Whether to include live metrics (only possible for a running Camel application) | true | boolean
| `--output` | Save diagram to a file (PNG for image themes, text for ascii theme) | | String
| `--theme` | Color theme preset (dark, light, transparent, ascii, unicode) or custom colors (e.g. bg=#1e1e1e:from=#2e7d32:to=#1565c0). Use ascii/unicode for plain text output. | | String
diff --git a/dsl/camel-cli-connector/src/main/java/org/apache/camel/cli/connector/LocalCliConnector.java b/dsl/camel-cli-connector/src/main/java/org/apache/camel/cli/connector/LocalCliConnector.java
index c5859350123f..d059599f1b6b 100644
--- a/dsl/camel-cli-connector/src/main/java/org/apache/camel/cli/connector/LocalCliConnector.java
+++ b/dsl/camel-cli-connector/src/main/java/org/apache/camel/cli/connector/LocalCliConnector.java
@@ -797,9 +797,10 @@ public class LocalCliConnector extends ServiceSupport implements CliConnector, C
String metric = root.getStringOrDefault("metric", "false");
String external = root.getStringOrDefault("external", "false");
String routes = root.getStringOrDefault("routes", "false");
+ String kamelets = root.getStringOrDefault("kamelets", "false");
JsonObject json
= (JsonObject) dc.call(DevConsole.MediaType.JSON,
- Map.of("metric", metric, "external", external, "routes", routes));
+ Map.of("metric", metric, "external", external, "routes", routes, "kamelets", kamelets));
LOG.trace("Updating output file: {}", outputFile);
IOHelper.writeText(json.toJson(), outputFile);
} else {
diff --git a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/LangChain4jAgentEndpointBuilderFactory.java b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/LangChain4jAgentEndpointBuilderFactory.java
index 64d267adea90..9acf041cfb2f 100644
--- a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/LangChain4jAgentEndpointBuilderFactory.java
+++ b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/LangChain4jAgentEndpointBuilderFactory.java
@@ -724,20 +724,6 @@ public interface LangChain4jAgentEndpointBuilderFactory {
public String langChain4jAgentToolExecutions() {
return "CamelLangChain4jAgentToolExecutions";
}
- /**
- * Set to true when user input is rejected by the configured moderation
- * model; not set on success.
- *
- * The option is a: {@code Boolean} type.
- *
- * Group: producer
- *
- * @return the name of the header {@code
- * LangChain4jAgentModerationFlagged}.
- */
- public String langChain4jAgentModerationFlagged() {
- return "CamelLangChain4jAgentModerationFlagged";
- }
}
static LangChain4jAgentEndpointBuilder endpointBuilder(String componentName, String path) {
class LangChain4jAgentEndpointBuilderImpl extends AbstractEndpointBuilder implements LangChain4jAgentEndpointBuilder, AdvancedLangChain4jAgentEndpointBuilder {
diff --git a/dsl/camel-jbang/camel-jbang-core/src/generated/resources/META-INF/camel-jbang-commands-metadata.json b/dsl/camel-jbang/camel-jbang-core/src/generated/resources/META-INF/camel-jbang-commands-metadata.json
index 30ea3af76e38..df1d6b8d1d32 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/generated/resources/META-INF/camel-jbang-commands-metadata.json
+++ b/dsl/camel-jbang/camel-jbang-core/src/generated/resources/META-INF/camel-jbang-commands-metadata.json
@@ -3,7 +3,7 @@
{ "name": "ask", "fullName": "ask", "description": "Ask a question about a running Camel application using AI", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.Ask", "options": [ { "names": "--api-key", "description": "API key. Also reads ANTHROPIC_API_KEY, OPENAI_API_KEY, WATSONX_APIKEY, or LLM_API_KEY env vars", "javaType": "java.lang.String", "type": "string" }, { "names": "--api-type", "description": "API type: 'ollama', 'openai', 'anthropic', or 'watsonx'", "javaType": [...]
{ "name": "bind", "fullName": "bind", "description": "DEPRECATED: Bind source and sink Kamelets as a new Camel integration", "deprecated": true, "sourceClass": "org.apache.camel.dsl.jbang.core.commands.bind.Bind", "options": [ { "names": "--error-handler", "description": "Add error handler (none|log|sink:<endpoint>). Sink endpoints are expected in the format [[apigroup\/]version:]kind:[namespace\/]name, plain Camel URIs or Kamelet name.", "javaType": "java.lang.String", "type": "stri [...]
{ "name": "catalog", "fullName": "catalog", "description": "List artifacts from Camel Catalog", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.catalog.CatalogCommand", "options": [ { "names": "-h,--help", "description": "Display the help and sub-commands", "javaType": "boolean", "type": "boolean" } ], "subcommands": [ { "name": "component", "fullName": "catalog component", "description": "List components from the Camel Catalog", "sourceClass": "org.apache.camel.dsl.jbang.co [...]
- { "name": "cmd", "fullName": "cmd", "description": "Performs commands in the running Camel integrations, such as start\/stop route, or change logging levels.", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.action.CamelAction", "options": [ { "names": "-h,--help", "description": "Display the help and sub-commands", "javaType": "boolean", "type": "boolean" } ], "subcommands": [ { "name": "browse", "fullName": "cmd browse", "description": "Browse pending messages on endpoints [...]
+ { "name": "cmd", "fullName": "cmd", "description": "Performs commands in the running Camel integrations, such as start\/stop route, or change logging levels.", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.action.CamelAction", "options": [ { "names": "-h,--help", "description": "Display the help and sub-commands", "javaType": "boolean", "type": "boolean" } ], "subcommands": [ { "name": "browse", "fullName": "cmd browse", "description": "Browse pending messages on endpoints [...]
{ "name": "completion", "fullName": "completion", "description": "Generate completion script for bash\/zsh", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.Complete", "options": [ { "names": "-h,--help", "description": "Display the help and sub-commands", "javaType": "boolean", "type": "boolean" } ] },
{ "name": "config", "fullName": "config", "description": "Get and set user configuration values", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.config.ConfigCommand", "options": [ { "names": "-h,--help", "description": "Display the help and sub-commands", "javaType": "boolean", "type": "boolean" } ], "subcommands": [ { "name": "get", "fullName": "config get", "description": "Display user configuration value", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.config. [...]
{ "name": "debug", "fullName": "debug", "description": "Debug local Camel integration", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.Debug", "options": [ { "names": "--ago", "description": "Use ago instead of yyyy-MM-dd HH:mm:ss in timestamp.", "javaType": "boolean", "type": "boolean" }, { "names": "--background", "description": "Run in the background", "defaultValue": "false", "javaType": "boolean", "type": "boolean" }, { "names": "--background-wait", "description": "To [...]
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelRouteTopologyAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelRouteTopologyAction.java
index 57062f95b7a9..e5ed1e3fa5da 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelRouteTopologyAction.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelRouteTopologyAction.java
@@ -101,6 +101,10 @@ public class CamelRouteTopologyAction extends ActionBaseCommand {
description = "Include external systems (consumers at top, producers at bottom)")
boolean external;
+ @CommandLine.Option(names = { "--kamelets" },
+ description = "Include routes created by Kamelets (hidden by default, only for a running Camel application)")
+ boolean kamelets;
+
@CommandLine.Option(names = { "--ignore-loading-error" }, defaultValue = "false",
description = "Whether to ignore route loading and compilation errors (use this with care!)")
boolean ignoreLoadingError;
@@ -135,6 +139,7 @@ public class CamelRouteTopologyAction extends ActionBaseCommand {
Path outputFile = prepareAction(Long.toString(pid), "route-topology", root -> {
root.put("metric", String.valueOf(metric));
root.put("external", String.valueOf(external));
+ root.put("kamelets", String.valueOf(kamelets));
});
JsonObject jo = getJsonObject(outputFile);
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ActionsPopup.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ActionsPopup.java
index 07abfb14df70..b882e4b67a0d 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ActionsPopup.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ActionsPopup.java
@@ -484,6 +484,20 @@ class ActionsPopup {
}
boolean handleKeyEvent(KeyEvent ke) {
+ if (handleChildPopupKeys(ke)) {
+ return true;
+ }
+ if (showActionsMenu) {
+ return handleMenuKeys(ke);
+ }
+ return false;
+ }
+
+ /**
+ * Routes the key to whichever child popup or overlay is currently open (send message, logs, doc viewer, options,
+ * infra browser, run options, folder input, examples, caption, stop-all, doctor, theme, go-to tab, settings).
+ */
+ private boolean handleChildPopupKeys(KeyEvent ke) {
if (sendMessagePopup.isVisible()) {
if (ke.isKey(KeyCode.F5) && !sendFileBrowser.isVisible()) {
sendMessagePopup.doSend(ctx, ctx.backgroundExecutor);
@@ -591,152 +605,156 @@ class ActionsPopup {
}
return true;
}
- if (showActionsMenu) {
- if (ke.isCancel()) {
- if (currentSubmenu != null) {
+ return false;
+ }
+
+ /**
+ * Keys while the actions menu itself is open: cancel/back, navigation, submenu entry and action execution.
+ */
+ private boolean handleMenuKeys(KeyEvent ke) {
+ if (ke.isCancel()) {
+ if (currentSubmenu != null) {
+ currentSubmenu = null;
+ actionsMenuState.select(savedMainSelection);
+ } else {
+ showActionsMenu = false;
+ }
+ } else if (ke.isUp()) {
+ navigateActionsMenu(-1);
+ } else if (ke.isDown()) {
+ navigateActionsMenu(1);
+ } else if (ke.isPageUp() || ke.isKey(KeyCode.PAGE_UP)) {
+ navigateActionsMenuToSection(-1);
+ } else if (ke.isPageDown() || ke.isKey(KeyCode.PAGE_DOWN)) {
+ navigateActionsMenuToSection(1);
+ } else if (ke.isHome() || ke.isKey(KeyCode.HOME)) {
+ actionsMenuState.select(0);
+ if (isDividerIndex(0)) {
+ navigateActionsMenu(1);
+ }
+ } else if (ke.isEnd() || ke.isKey(KeyCode.END)) {
+ int last = visualActionCount() - 1;
+ actionsMenuState.select(last);
+ if (isDividerIndex(last)) {
+ navigateActionsMenu(-1);
+ }
+ } else if (ke.isConfirm()) {
+ Integer sel = actionsMenuState.selected();
+ if (sel != null) {
+ Action action = resolveAction(sel);
+ if (action == null) {
+ // divider selected, ignore
+ } else if (action == Action.BACK) {
currentSubmenu = null;
actionsMenuState.select(savedMainSelection);
- } else {
+ } else if (action == Action.THEMES_SUBMENU) {
showActionsMenu = false;
- }
- } else if (ke.isUp()) {
- navigateActionsMenu(-1);
- } else if (ke.isDown()) {
- navigateActionsMenu(1);
- } else if (ke.isPageUp() || ke.isKey(KeyCode.PAGE_UP)) {
- navigateActionsMenuToSection(-1);
- } else if (ke.isPageDown() || ke.isKey(KeyCode.PAGE_DOWN)) {
- navigateActionsMenuToSection(1);
- } else if (ke.isHome() || ke.isKey(KeyCode.HOME)) {
- actionsMenuState.select(0);
- if (isDividerIndex(0)) {
- navigateActionsMenu(1);
- }
- } else if (ke.isEnd() || ke.isKey(KeyCode.END)) {
- int last = visualActionCount() - 1;
- actionsMenuState.select(last);
- if (isDividerIndex(last)) {
- navigateActionsMenu(-1);
- }
- } else if (ke.isConfirm()) {
- Integer sel = actionsMenuState.selected();
- if (sel != null) {
- Action action = resolveAction(sel);
- if (action == null) {
- // divider selected, ignore
- } else if (action == Action.BACK) {
- currentSubmenu = null;
- actionsMenuState.select(savedMainSelection);
- } else if (action == Action.THEMES_SUBMENU) {
- showActionsMenu = false;
- themePopup.open();
- } else if (action == Action.SCREEN_SUBMENU) {
- savedMainSelection = sel;
- currentSubmenu = "screen";
- actionsMenuState.select(0);
- } else if (action == Action.MCP_SUBMENU) {
- savedMainSelection = sel;
- currentSubmenu = "mcp";
- actionsMenuState.select(0);
- } else if (action == Action.GOTO_TAB) {
- showActionsMenu = false;
- gotoTabPopup.open();
- } else if (action == Action.SETTINGS) {
- showActionsMenu = false;
- settingsPopup.open();
- } else if (action == Action.SWITCH_INTEGRATION) {
- if (hasMultipleIntegrations()) {
- showActionsMenu = false;
- if (switchIntegrationAction != null) {
- switchIntegrationAction.run();
- }
- }
- } else if (action == Action.SHELL) {
- showActionsMenu = false;
- if (openShellAction != null) {
- openShellAction.run();
- }
- } else if (action == Action.RUN_EXAMPLE) {
- showActionsMenu = false;
- exampleBrowserPopup.open();
- } else if (action == Action.OPEN_PROJECT) {
- showActionsMenu = false;
- folderInputPopup.open();
- } else if (action == Action.SCREENSHOT) {
- showActionsMenu = false;
- screenshotAction.run();
- } else if (action == Action.SHOW_KEYSTROKES) {
- showActionsMenu = false;
- toggleKeystrokes.run();
- } else if (action == Action.TAPE_RECORDING) {
- showActionsMenu = false;
- toggleTapeRecording.run();
- } else if (action == Action.TAPE_INSTRUCTIONS) {
- showActionsMenu = false;
- openTapeInstructions();
- } else if (action == Action.BROWSE_FILES) {
- if (ctx != null && ctx.selectedPid != null && !ctx.isInfraSelected()) {
- showActionsMenu = false;
- if (browseFilesAction != null) {
- browseFilesAction.run();
- }
- }
- } else if (action == Action.DOCTOR) {
- showActionsMenu = false;
- doctorPopup.open();
- } else if (action == Action.RUN_INFRA) {
- showActionsMenu = false;
- infraBrowserPopup.open();
- } else if (action == Action.AI_PROMPT) {
- showActionsMenu = false;
- if (openAiPromptAction != null) {
- openAiPromptAction.run();
- }
- } else if (action == Action.SETUP_AI) {
- showActionsMenu = false;
- openSetupAI();
- } else if (action == Action.MCP_INFO) {
- showActionsMenu = false;
- openMcpInfo();
- } else if (action == Action.MCP_LOG) {
- showActionsMenu = false;
- openMcpLog();
- } else if (action == Action.AI_LOG) {
- showActionsMenu = false;
- openAiLog();
- } else if (action == Action.SEND_MESSAGE) {
- if (ctx != null && ctx.selectedPid != null && !ctx.isInfraSelected()) {
- showActionsMenu = false;
- openSendMessage();
- }
- } else if (action == Action.RESET_STATS) {
+ themePopup.open();
+ } else if (action == Action.SCREEN_SUBMENU) {
+ savedMainSelection = sel;
+ currentSubmenu = "screen";
+ actionsMenuState.select(0);
+ } else if (action == Action.MCP_SUBMENU) {
+ savedMainSelection = sel;
+ currentSubmenu = "mcp";
+ actionsMenuState.select(0);
+ } else if (action == Action.GOTO_TAB) {
+ showActionsMenu = false;
+ gotoTabPopup.open();
+ } else if (action == Action.SETTINGS) {
+ showActionsMenu = false;
+ settingsPopup.open();
+ } else if (action == Action.SWITCH_INTEGRATION) {
+ if (hasMultipleIntegrations()) {
showActionsMenu = false;
- if (resetStatsAction != null) {
- resetStatsAction.run();
+ if (switchIntegrationAction != null) {
+ switchIntegrationAction.run();
}
- } else if (action == Action.RESET_SCREEN) {
+ }
+ } else if (action == Action.SHELL) {
+ showActionsMenu = false;
+ if (openShellAction != null) {
+ openShellAction.run();
+ }
+ } else if (action == Action.RUN_EXAMPLE) {
+ showActionsMenu = false;
+ exampleBrowserPopup.open();
+ } else if (action == Action.OPEN_PROJECT) {
+ showActionsMenu = false;
+ folderInputPopup.open();
+ } else if (action == Action.SCREENSHOT) {
+ showActionsMenu = false;
+ screenshotAction.run();
+ } else if (action == Action.SHOW_KEYSTROKES) {
+ showActionsMenu = false;
+ toggleKeystrokes.run();
+ } else if (action == Action.TAPE_RECORDING) {
+ showActionsMenu = false;
+ toggleTapeRecording.run();
+ } else if (action == Action.TAPE_INSTRUCTIONS) {
+ showActionsMenu = false;
+ openTapeInstructions();
+ } else if (action == Action.BROWSE_FILES) {
+ if (ctx != null && ctx.selectedPid != null && !ctx.isInfraSelected()) {
showActionsMenu = false;
- if (resetScreenAction != null) {
- resetScreenAction.run();
+ if (browseFilesAction != null) {
+ browseFilesAction.run();
}
- } else if (action == Action.TOGGLE_THEME) {
- Theme.toggle();
- refreshTheme();
- showActionsMenu = false;
- } else if (action == Action.CAPTION) {
- showActionsMenu = false;
- captionOverlay.openInline();
- } else if (action == Action.CAMEL_ANIMATION) {
+ }
+ } else if (action == Action.DOCTOR) {
+ showActionsMenu = false;
+ doctorPopup.open();
+ } else if (action == Action.RUN_INFRA) {
+ showActionsMenu = false;
+ infraBrowserPopup.open();
+ } else if (action == Action.AI_PROMPT) {
+ showActionsMenu = false;
+ if (openAiPromptAction != null) {
+ openAiPromptAction.run();
+ }
+ } else if (action == Action.SETUP_AI) {
+ showActionsMenu = false;
+ openSetupAI();
+ } else if (action == Action.MCP_INFO) {
+ showActionsMenu = false;
+ openMcpInfo();
+ } else if (action == Action.MCP_LOG) {
+ showActionsMenu = false;
+ openMcpLog();
+ } else if (action == Action.AI_LOG) {
+ showActionsMenu = false;
+ openAiLog();
+ } else if (action == Action.SEND_MESSAGE) {
+ if (ctx != null && ctx.selectedPid != null && !ctx.isInfraSelected()) {
showActionsMenu = false;
- if (camelAnimationAction != null) {
- camelAnimationAction.run();
- }
+ openSendMessage();
+ }
+ } else if (action == Action.RESET_STATS) {
+ showActionsMenu = false;
+ if (resetStatsAction != null) {
+ resetStatsAction.run();
+ }
+ } else if (action == Action.RESET_SCREEN) {
+ showActionsMenu = false;
+ if (resetScreenAction != null) {
+ resetScreenAction.run();
+ }
+ } else if (action == Action.TOGGLE_THEME) {
+ Theme.toggle();
+ refreshTheme();
+ showActionsMenu = false;
+ } else if (action == Action.CAPTION) {
+ showActionsMenu = false;
+ captionOverlay.openInline();
+ } else if (action == Action.CAMEL_ANIMATION) {
+ showActionsMenu = false;
+ if (camelAnimationAction != null) {
+ camelAnimationAction.run();
}
}
}
- return true;
}
- return false;
+ return true;
}
// ---- Mouse handling ----
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ActivityTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ActivityTab.java
index d691fa9413f3..c239cbc80378 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ActivityTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ActivityTab.java
@@ -411,59 +411,7 @@ class ActivityTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Activity
-
- The Activity tab shows a live feed of recently completed exchanges.
- It captures the last N exchanges (default 100) with their message
- content, giving you a rolling window of what your integration has
- been processing.
-
- Unlike the Inspect tab which traces individual processing steps
- within a route, Activity shows one entry per completed exchange
- with a summary of the final state.
-
- ## Summary Panel
-
- The top panel shows aggregated stats from the visible activity:
-
- - **Total** / **OK** / **Failed** — exchange counts
- - **Sends** — total remote endpoint calls across all exchanges
- - **p50** / **p95** / **Max** — elapsed time statistics
- - **Window** — how far back the oldest and newest entries are
-
- ## Activity List
-
- - **EXCHANGE** — Exchange identifier
- - **ROUTE** — Route that processed the exchange
- - **STATUS** — `OK` (green) or `FAILED` (red)
- - **ELAPSED** — Total processing time in milliseconds
- - **SENDS** — Number of outbound endpoint calls made during the exchange
- - **SINCE** — How long ago the exchange completed (e.g., `5s`, `2m`)
- - **ENDPOINT** — The consumer endpoint that received the exchange
-
- ## Detail View
-
- Select an exchange to see its details in the panel below:
-
- - **Exchange info**: Exchange ID, route, elapsed time, and failure status
- - **Endpoint Sends**: Remote endpoints called during the exchange,
- with individual elapsed times
- - **Exception**: If the exchange failed, shows the exception type,
- message, and stack trace
-
- ## Keys
-
- - `Up/Down` — select exchange
- - `Home/End` — jump to first/last exchange
- - `PgUp/PgDn` — scroll the detail panel
- - `Left/Right` — horizontal scroll (when wrap is off)
- - `Space` — pause/resume data feed (freezes the view for inspection)
- - `t` — cycle time filter (all, 1m, 5m, 15m, 30m, 1h)
- - `w` — toggle word wrap
- - `s` — cycle sort column
- - `S` — reverse sort order
- """;
+ return DocHelper.loadHelpText("activity");
}
}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
index fc3561aba9f4..6a4f92f62cbf 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
@@ -174,6 +174,10 @@ class AiPanel {
private long thinkingStartTime;
private volatile String thinkingVerb;
private volatile int sessionTotalTokens;
+ private volatile long sessionToolTimeMs;
+ private volatile int sessionToolCalls;
+ /** Per answered question: [aiMs, toolMs, toolCalls], in order, for the time chart in the usage view. */
+ private final List<long[]> turnTimings = new CopyOnWriteArrayList<>();
// Slash commands
private final AiSlashCommandRegistry slashCommands = AiSlashCommandRegistry.defaults();
@@ -256,9 +260,24 @@ class AiPanel {
ROUTE
}
- record ConversationEntry(AiRole role, String text, long elapsedSeconds, int totalTokens) {
+ /**
+ * One conversation line. For assistant replies {@code elapsedMs} is the wall-clock time of the whole turn,
+ * {@code aiMs} the part spent waiting for the model and {@code toolMs} the part spent executing the
+ * {@code toolCalls} TUI tool calls the model made.
+ */
+ record ConversationEntry(AiRole role, String text, long elapsedMs, long aiMs, long toolMs, int toolCalls,
+ int totalTokens) {
ConversationEntry(AiRole role, String text) {
- this(role, text, -1, 0);
+ this(role, text, -1, 0, 0, 0, 0);
+ }
+
+ /** "5.2s" or, when tools were called, "5.2s, ai 4.1s, tools 1.1s/3". */
+ String timing() {
+ String t = formatSeconds(elapsedMs);
+ if (toolCalls > 0) {
+ t += ", ai " + formatSeconds(aiMs) + ", tools " + formatSeconds(toolMs) + "/" + toolCalls;
+ }
+ return t;
}
}
@@ -351,7 +370,7 @@ class AiPanel {
return -1;
}
ConversationEntry last = conversation.get(conversation.size() - 1);
- return last.role() == AiRole.ASSISTANT ? last.elapsedSeconds() : -1;
+ return last.role() == AiRole.ASSISTANT ? last.elapsedMs() : -1;
}
private int lastResponseTokens() {
@@ -1080,6 +1099,9 @@ class AiPanel {
LlmClient.TokenUsage totalUsage = LlmClient.TokenUsage.EMPTY;
Map<String, Integer> callCounts = new HashMap<>();
List<String> recentCalls = new ArrayList<>();
+ long turnAiMs = 0;
+ long turnToolMs = 0;
+ int turnToolCalls = 0;
for (int i = 0; i < MAX_ITERATIONS; i++) {
if (Thread.interrupted()) {
throw new InterruptedException();
@@ -1089,6 +1111,7 @@ class AiPanel {
drainClientOutput();
LlmClient.ChatResponse response = client.chatWithTools(systemPrompt, messages, tools);
long callLatency = System.currentTimeMillis() - callStart;
+ turnAiMs += callLatency;
if (response == null) {
String err = "No response from LLM";
conversation.add(new ConversationEntry(AiRole.ERROR, err));
@@ -1125,6 +1148,7 @@ class AiPanel {
String key = toolCall.name() + " " + arguments;
int repeats = callCounts.merge(key, 1, Integer::sum);
String result;
+ long toolStart = System.currentTimeMillis();
if (repeats > MAX_IDENTICAL_TOOL_CALLS) {
result = "You have already called " + toolCall.name() + " with these exact arguments "
+ (repeats - 1) + " times in this turn and the result will not change. Stop calling "
@@ -1132,7 +1156,12 @@ class AiPanel {
} else {
result = executeTuiTool(toolCall.name(), toolCall.arguments());
}
- log(LogLevel.RESULT, toolCall.name(), result);
+ long toolElapsed = System.currentTimeMillis() - toolStart;
+ turnToolMs += toolElapsed;
+ turnToolCalls++;
+ sessionToolTimeMs += toolElapsed;
+ sessionToolCalls++;
+ log(LogLevel.RESULT, toolCall.name() + " (" + formatToolTime(toolElapsed) + ")", result);
recentCalls.add(toolCall.name() + " " + summarize(arguments, 80) + " -> " + summarize(result, 120));
results.add(new LlmClient.ToolResult(toolCall.id(), truncateToolResult(result)));
}
@@ -1141,12 +1170,17 @@ class AiPanel {
String text = response.text();
sessionTotalTokens += totalUsage.totalTokens();
if (text != null && !text.isBlank()) {
- long elapsed = (System.currentTimeMillis() - thinkingStartTime) / 1000;
- conversation.add(new ConversationEntry(AiRole.ASSISTANT, text, elapsed, totalUsage.totalTokens()));
+ long elapsed = System.currentTimeMillis() - thinkingStartTime;
+ ConversationEntry entry = new ConversationEntry(
+ AiRole.ASSISTANT, text, elapsed, turnAiMs, turnToolMs, turnToolCalls,
+ totalUsage.totalTokens());
+ conversation.add(entry);
+ turnTimings.add(new long[] { turnAiMs, turnToolMs, turnToolCalls });
String tokenInfo = totalUsage.totalTokens() > 0
? ", " + LlmClient.formatTokens(totalUsage.totalTokens()) + " tokens"
: "";
- log(LogLevel.RESPONSE, "Response (" + elapsed + "s" + tokenInfo + describeCacheSignal(totalUsage) + ")",
+ log(LogLevel.RESPONSE,
+ "Response (" + entry.timing() + tokenInfo + describeCacheSignal(totalUsage) + ")",
text);
} else {
String err = "Empty response from LLM.";
@@ -1218,6 +1252,13 @@ class AiPanel {
return String.format(Locale.ROOT, "%.1fs", millis / 1000.0);
}
+ /**
+ * Tool calls are usually fast, so show milliseconds below one second and one decimal second above.
+ */
+ private static String formatToolTime(long millis) {
+ return millis < 1000 ? millis + "ms" : formatSeconds(millis);
+ }
+
private static String summarize(String text, int max) {
if (text == null) {
return "";
@@ -1252,7 +1293,7 @@ class AiPanel {
String tokenSuffix = titleTokens > 0 ? ", " + LlmClient.formatTokens(titleTokens) + " tokens" : "";
titleLine = Line.from(
Span.styled(" AI ", Style.EMPTY.bold()),
- Span.styled("(" + titleElapsed + "s" + tokenSuffix + ") ", Style.EMPTY.dim()));
+ Span.styled("(" + formatSeconds(titleElapsed) + tokenSuffix + ") ", Style.EMPTY.dim()));
} else if (sessionTotalTokens > 0) {
titleLine = Line.from(
Span.styled(" AI ", Style.EMPTY.bold()),
@@ -1374,11 +1415,13 @@ class AiPanel {
// Show elapsed time and token count as a dimmed line below the markdown when at the bottom
long lastElapsed = -1;
+ String lastTiming = "";
int lastTokens = 0;
if (!thinking.get() && !conversation.isEmpty()) {
ConversationEntry last = conversation.get(conversation.size() - 1);
- if (last.role() == AiRole.ASSISTANT && last.elapsedSeconds() >= 0) {
- lastElapsed = last.elapsedSeconds();
+ if (last.role() == AiRole.ASSISTANT && last.elapsedMs() >= 0) {
+ lastElapsed = last.elapsedMs();
+ lastTiming = last.timing();
lastTokens = last.totalTokens();
}
}
@@ -1443,7 +1486,8 @@ class AiPanel {
if (elapsedArea != null && lastElapsed >= 0) {
String tokenSuffix = lastTokens > 0 ? ", " + LlmClient.formatTokens(lastTokens) + " tokens" : "";
frame.renderWidget(
- Paragraph.from(Line.from(Span.styled("(" + lastElapsed + "s" + tokenSuffix + ")", Style.EMPTY.dim()))),
+ Paragraph.from(
+ Line.from(Span.styled("(" + lastTiming + tokenSuffix + ")", Style.EMPTY.dim()))),
elapsedArea);
}
if (statusArea != null) {
@@ -1664,14 +1708,15 @@ class AiPanel {
int requestCount = entries.size();
// Per-model aggregation
- Map<String, int[]> perModel = new LinkedHashMap<>();
+ Map<String, long[]> perModel = new LinkedHashMap<>();
for (AiUsageEntry e : entries) {
String key = modelTableKey(e);
- int[] stats = perModel.computeIfAbsent(key, k -> new int[4]);
+ long[] stats = perModel.computeIfAbsent(key, k -> new long[5]);
stats[0]++; // requests
stats[1] += e.inputTokens();
stats[2] += e.outputTokens();
stats[3] += e.totalTokens();
+ stats[4] += e.latencyMs();
}
// Tokens per question (panel requests only): the round trips made for one question share its sequence
@@ -1725,9 +1770,12 @@ class AiPanel {
Span.styled(")", dimStyle)));
summaryLines.add(Line.from(
Span.styled("Avg latency: ", dimStyle),
- Span.styled((totalLatency / requestCount / 1000) + "s", cyanStyle),
- Span.styled(" Total time: ", dimStyle),
- Span.styled((totalLatency / 1000) + "s", cyanStyle)));
+ Span.styled(formatSeconds(totalLatency / requestCount), cyanStyle),
+ Span.styled(" AI time: ", dimStyle),
+ Span.styled(formatSeconds(totalLatency), cyanStyle),
+ Span.styled(" Tool time: ", dimStyle),
+ Span.styled(formatSeconds(sessionToolTimeMs), cyanStyle),
+ Span.styled(" (" + sessionToolCalls + " calls)", dimStyle)));
frame.renderWidget(
Paragraph.from(new dev.tamboui.text.Text(summaryLines, dev.tamboui.layout.Alignment.LEFT)),
summaryArea);
@@ -1735,14 +1783,15 @@ class AiPanel {
// --- Per-model table ---
Rect tableArea = sections.get(1);
List<Row> rows = new ArrayList<>();
- for (Map.Entry<String, int[]> entry : perModel.entrySet()) {
- int[] s = entry.getValue();
+ for (Map.Entry<String, long[]> entry : perModel.entrySet()) {
+ long[] s = entry.getValue();
rows.add(Row.from(
Cell.from(Span.styled(entry.getKey(), cyanStyle)),
Cell.from(String.valueOf(s[0])),
- Cell.from(LlmClient.formatTokens(s[1])),
- Cell.from(LlmClient.formatTokens(s[2])),
- Cell.from(LlmClient.formatTokens(s[3]))));
+ Cell.from(LlmClient.formatTokens((int) s[1])),
+ Cell.from(LlmClient.formatTokens((int) s[2])),
+ Cell.from(LlmClient.formatTokens((int) s[3])),
+ Cell.from(formatSeconds(s[4] / s[0]))));
}
Table table = Table.builder()
.rows(rows)
@@ -1751,19 +1800,38 @@ class AiPanel {
Cell.from(Span.styled("REQS", Style.EMPTY.bold())),
Cell.from(Span.styled("INPUT", Style.EMPTY.bold())),
Cell.from(Span.styled("OUTPUT", Style.EMPTY.bold())),
- Cell.from(Span.styled("TOTAL", Style.EMPTY.bold()))))
+ Cell.from(Span.styled("TOTAL", Style.EMPTY.bold())),
+ Cell.from(Span.styled("AVG", Style.EMPTY.bold()))))
.widths(
Constraint.fill(),
Constraint.length(6),
Constraint.length(8),
Constraint.length(8),
- Constraint.length(8))
+ Constraint.length(8),
+ Constraint.length(7))
.build();
frame.renderStatefulWidget(table, tableArea, statsTableState);
- // --- Token bar chart per turn ---
- if (hasChart && turnTokens.size() > 1) {
- Rect chartArea = sections.get(2);
+ // --- Charts per question: tokens on the left, AI vs tool time on the right ---
+ if (hasChart && (turnTokens.size() > 1 || turnTimings.size() > 1)) {
+ Rect chartsArea = sections.get(2);
+ List<long[]> timings = new ArrayList<>(turnTimings);
+ boolean showTime = timings.size() > 1 && chartsArea.width() >= 40;
+ List<Rect> halves = showTime
+ ? Layout.horizontal().constraints(Constraint.fill(), Constraint.length(1), Constraint.fill())
+ .split(chartsArea)
+ : List.of(chartsArea);
+ if (turnTokens.size() > 1) {
+ renderTokensPerQuestion(frame, halves.get(0), turnTokens);
+ }
+ if (showTime) {
+ renderTimePerQuestion(frame, halves.get(2), timings);
+ }
+ }
+ }
+
+ private void renderTokensPerQuestion(Frame frame, Rect chartArea, List<Integer> turnTokens) {
+ {
// Title row + chart
List<Rect> chartParts = Layout.vertical()
@@ -1800,6 +1868,47 @@ class AiPanel {
}
}
+ /**
+ * One group of two bars per answered question: time waiting for the model next to time spent in tool calls.
+ */
+ private void renderTimePerQuestion(Frame frame, Rect chartArea, List<long[]> timings) {
+ List<Rect> chartParts = Layout.vertical()
+ .constraints(Constraint.length(1), Constraint.fill())
+ .split(chartArea);
+ Style aiStyle = Style.EMPTY.fg(Theme.accent());
+ Style toolStyle = Theme.warning();
+ frame.renderWidget(
+ Paragraph.from(Line.from(
+ Span.styled("Time per question: ", Style.EMPTY.bold()),
+ Span.styled("\u25a0 ai ", aiStyle),
+ Span.styled("\u25a0 tools", toolStyle))),
+ chartParts.get(0));
+
+ Rect barArea = chartParts.get(1);
+ long maxMs = 1;
+ for (long[] t : timings) {
+ maxMs = Math.max(maxMs, Math.max(t[0], t[1]));
+ }
+ // each question takes two 1-wide bars plus a gap
+ int maxGroups = Math.max(1, barArea.width() / 3);
+ int startIdx = Math.max(0, timings.size() - maxGroups);
+ List<BarGroup> groups = new ArrayList<>();
+ for (int i = startIdx; i < timings.size(); i++) {
+ long[] t = timings.get(i);
+ groups.add(BarGroup.of(
+ Bar.builder().value(t[0]).textValue("").style(aiStyle).build(),
+ Bar.builder().value(t[1]).textValue("").style(toolStyle).build()));
+ }
+ BarChart barChart = BarChart.builder()
+ .data(groups)
+ .max(maxMs + maxMs / 20)
+ .barWidth(1)
+ .barGap(0)
+ .groupGap(1)
+ .build();
+ frame.renderWidget(barChart, barArea);
+ }
+
private List<AiUsageEntry> combinedUsageEntries() {
List<AiUsageEntry> combined = new ArrayList<>(usageHistory.size() + 8);
combined.addAll(usageHistory);
@@ -1821,6 +1930,7 @@ class AiPanel {
*/
void resetUsage() {
usageHistory.clear();
+ turnTimings.clear();
usageResetAt = Instant.now();
statsScrollOffset = 0;
}
@@ -2297,29 +2407,38 @@ class AiPanel {
stats[4] += e.latencyMs();
}
StringBuilder sb = new StringBuilder();
- sb.append("Requests: ").append(entries.size());
+ sb.append("**AI usage:** ").append(entries.size()).append(" request(s)");
if (routeRequests > 0) {
sb.append(" (").append(tuiRequests).append(" from this panel, ").append(routeRequests)
.append(" from the integration)");
}
- sb.append(", tokens: ").append(LlmClient.formatTokens(totalTokens))
+ sb.append("\n\n");
+ sb.append("- **Tokens:** ").append(LlmClient.formatTokens(totalTokens))
.append(" (in ").append(LlmClient.formatTokens(totalInput))
- .append(", out ").append(LlmClient.formatTokens(totalOutput))
- .append("), avg latency: ").append(totalLatency / entries.size()).append(" ms\n");
- for (Map.Entry<String, long[]> entry : perModel.entrySet()) {
- long[] stats = entry.getValue();
- sb.append("- ").append(entry.getKey()).append(": ").append(stats[0]).append(" request(s), ")
- .append(LlmClient.formatTokens((int) stats[3])).append(" tokens (in ")
- .append(LlmClient.formatTokens((int) stats[1])).append(", out ")
- .append(LlmClient.formatTokens((int) stats[2])).append("), avg ")
- .append(stats[4] / stats[0]).append(" ms\n");
+ .append(", out ").append(LlmClient.formatTokens(totalOutput)).append(")\n");
+ sb.append("- **Avg latency:** ").append(formatSeconds(totalLatency / entries.size())).append("\n");
+ if (sessionToolCalls > 0) {
+ sb.append("- **AI time:** ").append(formatSeconds(totalLatency))
+ .append(", **Tool time:** ").append(formatSeconds(sessionToolTimeMs))
+ .append(" in ").append(sessionToolCalls).append(" tool call(s)\n");
}
AiUsageEntry last = usageHistory.isEmpty() ? null : usageHistory.get(usageHistory.size() - 1);
if (last != null) {
- sb.append("Last request: ").append(LlmClient.formatTokens(last.totalTokens())).append(" tokens in ")
- .append(last.latencyMs()).append(" ms\n");
+ sb.append("- **Last request:** ").append(LlmClient.formatTokens(last.totalTokens()))
+ .append(" tokens in ").append(formatSeconds(last.latencyMs())).append("\n");
}
- sb.append("Ctrl+U opens the full usage view with the per-turn chart.");
+ sb.append("\n| Model | Reqs | In | Out | Total | Avg |\n|---|---|---|---|---|---|\n");
+ for (Map.Entry<String, long[]> entry : perModel.entrySet()) {
+ long[] stats = entry.getValue();
+ sb.append("| ").append(entry.getKey())
+ .append(" | ").append(stats[0])
+ .append(" | ").append(LlmClient.formatTokens((int) stats[1]))
+ .append(" | ").append(LlmClient.formatTokens((int) stats[2]))
+ .append(" | ").append(LlmClient.formatTokens((int) stats[3]))
+ .append(" | ").append(formatSeconds(stats[4] / stats[0]))
+ .append(" |\n");
+ }
+ sb.append("\n_Ctrl+U opens the full usage view with the per-question charts._");
return sb.toString().strip();
}
@@ -2374,8 +2493,11 @@ class AiPanel {
cursorPos = 0;
scrollOffset = 0;
usageHistory.clear();
+ turnTimings.clear();
statsScrollOffset = 0;
sessionTotalTokens = 0;
+ sessionToolTimeMs = 0;
+ sessionToolCalls = 0;
if (messages != null) {
messages.clear();
}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/BeansTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/BeansTab.java
index 9a5b599e8287..8cc616a9b008 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/BeansTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/BeansTab.java
@@ -548,54 +548,7 @@ class BeansTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Beans
-
- The Beans tab shows all beans registered in the Camel registry. Beans
- are reusable Java objects that routes can reference by name — for
- example, a database connection pool, a custom processor, a REST
- configuration, or a type converter.
-
- In Camel, beans can be registered in several ways:
-
- - **YAML DSL** — defined in a `beans:` section of your YAML route file
- - **Java** — bound to the registry via `bindToRegistry()` or annotations
- - **Spring/Quarkus** — injected as managed beans (`@Component`, `@Named`)
- - **Camel auto-discovery** — components and languages auto-register their beans
-
- ## Table Columns
-
- - **NAME** — Bean name used to look it up from routes. In a route you reference this with `.bean("myService")` or `${bean:myService}`
- - **TYPE** — Short Java class name of the bean (e.g., `Greeter`, `HikariDataSource`)
-
- ## Detail View
-
- The detail panel at the bottom shows the full type (including package)
- and the bean's properties with their current values. This is useful for
- verifying configuration — for example, checking that a database connection
- pool has the correct URL, or that a data format is configured with the
- right options.
-
- ## Filter Modes
-
- Press `f` to cycle through filter modes:
-
- - **all** — show all beans (including framework internals)
- - **user** — only your application beans (excludes Camel, Spring, Quarkus, and JDK beans)
- - **camel** — only Camel internal beans
- - **spring** — only Spring Framework beans (Spring Boot apps only)
- - **quarkus** — only Quarkus beans (Quarkus apps only)
-
- ## Keys
-
- - `Tab` — switch focus between table and detail panel
- - `Up/Down` — navigate in focused panel
- - `PgUp/PgDn` — page in focused panel
- - `s` — cycle sort column
- - `S` — reverse sort order
- - `f` — cycle filter
- - `Esc` — back
- """;
+ return DocHelper.loadHelpText("beans");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/BrowseTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/BrowseTab.java
index 51ef08fbb6a0..5f2bea9282df 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/BrowseTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/BrowseTab.java
@@ -741,56 +741,7 @@ class BrowseTab extends AbstractTab {
@Override
public String getHelpText() {
- return """
- # Browse
-
- The Browse tab lets you inspect messages currently queued in browsable
- endpoints. Browsable endpoints include `seda`, `browse`, and `stub` —
- these are in-memory queues where messages wait to be consumed.
-
- This is useful for debugging message flow: you can see what messages
- are waiting in a queue without consuming them (unlike a consumer
- which removes messages from the queue).
-
- ## Endpoint List
-
- The left panel shows all browsable endpoints with their current
- queue sizes. Select an endpoint to see its queued messages.
-
- ## Example Screen
-
- ```
- Endpoint Queue Size
- seda://queue 5
- seda://orders 12
- browse://audit 3
- ```
-
- ## Message View
-
- When you select an endpoint, the right panel shows each queued message:
-
- - **Exchange ID** — Unique identifier for this exchange
- - **Exchange Pattern** — `InOnly` (fire-and-forget) or `InOut` (request-reply)
- - **Headers** — Message headers as key-value pairs (e.g., `Content-Type: application/json`, `CamelFileName: order.xml`)
- - **Body** — The message body content. This is the actual data being processed — could be JSON, XML, plain text, or binary
-
- ## When To Use
-
- - **Debugging routing**: If messages are not reaching their destination, check if they are accumulating in a SEDA queue
- - **Inspecting content**: Verify that message transformations (marshal, unmarshal, setBody) are producing the expected output
- - **Testing**: When using `stub` endpoints for testing, browse to verify messages were sent correctly
- - **Monitoring backlog**: A growing queue size may indicate that consumers cannot keep up with producers
-
- ## Keys
-
- - `Up/Down` — navigate endpoints and messages
- - `PgUp/PgDn` — page through list or detail
- - `Tab` — switch focus between messages and detail (in detail view)
- - `Enter` — browse selected endpoint / view message detail
- - `p` — toggle pretty-print for message body
- - `Esc` — back to previous view
- """;
+ return DocHelper.loadHelpText("browse");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CamelMonitor.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CamelMonitor.java
index 4de42a3ca044..8dc0e2368f4e 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CamelMonitor.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CamelMonitor.java
@@ -170,6 +170,7 @@ public class CamelMonitor extends CamelCommand {
private String lastWaveNotification;
private boolean mcpInjectedKey;
private TuiMcpServer mcpServer;
+ private Path mcpJsonFile;
private TuiWebServer webServer;
private McpFacade mcpFacade;
private final Queue<McpFacade.PendingKey> pendingKeys = new ConcurrentLinkedQueue<>();
@@ -282,6 +283,43 @@ public class CamelMonitor extends CamelCommand {
public Integer doCall() throws Exception {
System.setProperty("java.awt.headless", "true");
+ String openDir = resolveOpenDirectory();
+ applyThemeOption();
+ configureRecording();
+ recordingManager.init(record != null);
+
+ // to make ServiceLoader work with tamboui for downloaded JARs
+ Thread.currentThread().setContextClassLoader(classLoader);
+
+ // data service first: tabs and popups reference its state
+ createDataService();
+ ctx = new MonitorContext(dataService.data(), dataService.infraData());
+ dataService.setContext(ctx);
+
+ // popups, tabs and their cross-wiring
+ createActionsPopup();
+ createProcessControlPopup();
+ wireContextCallbacks();
+ createTabRegistry();
+ setupGotoTabSupport();
+ createPopupManager();
+ wireOverviewActions();
+
+ loadInitialData(openDir);
+
+ // optional integrations: AI/MCP facade, MCP server, web server
+ createMcpFacade();
+ startMcpServer();
+ startWebServer();
+
+ runTui();
+ return 0;
+ }
+
+ /**
+ * If the name argument is a directory, returns it (and resets the name filter) so it can be opened as a project.
+ */
+ private String resolveOpenDirectory() {
// Detect if name arg is a directory path — open it as a project instead of using it as a name/PID filter
String openDir = null;
if (!"*".equals(name)) {
@@ -291,7 +329,13 @@ public class CamelMonitor extends CamelCommand {
name = "*";
}
}
+ return openDir;
+ }
+ /**
+ * Validates and applies the --theme option.
+ */
+ private void applyThemeOption() {
if (theme != null) {
if (!Theme.isValidMode(theme)) {
String expected = String.join("' or '", ThemeMode.ids());
@@ -301,15 +345,12 @@ public class CamelMonitor extends CamelCommand {
}
Theme.applyStartupMode(theme);
}
+ }
- // Configure TamboUI recording if --record is specified
- configureRecording();
-
- recordingManager.init(record != null);
-
- // to make ServiceLoader work with tamboui for downloaded JARs
- Thread.currentThread().setContextClassLoader(classLoader);
-
+ /**
+ * Creates the data refresh service; tabs and popups reference its state so it is created first.
+ */
+ private void createDataService() {
// Create data refresh service first — tabs and popups reference its state
dataService = new DataRefreshService(
name,
@@ -351,11 +392,12 @@ public class CamelMonitor extends CamelCommand {
},
this::getStatusFile,
this::getErrorFile);
+ }
- // Create shared context and tab instances
- ctx = new MonitorContext(dataService.data(), dataService.infraData());
- dataService.setContext(ctx);
-
+ /**
+ * Creates the actions popup (F2) wired to the data service and recording manager.
+ */
+ private void createActionsPopup() {
actionsPopup = new ActionsPopup(
() -> dataService.data().get().stream()
.filter(i -> !i.vanishing && i.name != null)
@@ -378,7 +420,12 @@ public class CamelMonitor extends CamelCommand {
actionsPopup.setContext(ctx);
actionsPopup.setMonitorContext(ctx);
actionsPopup.setNotificationCallback((msg, error) -> setNotification(msg, error));
+ }
+ /**
+ * Creates the process control popup and its bridge back to this monitor.
+ */
+ private void createProcessControlPopup() {
processControlPopup = new ProcessControlPopup(ctx);
processControlPopup.setActions(new ProcessControlPopup.ControlActions() {
@Override
@@ -421,6 +468,12 @@ public class CamelMonitor extends CamelCommand {
return actionsPopup.hasRunningProcesses();
}
});
+ }
+
+ /**
+ * Wires the shared MonitorContext callbacks and connects the shell and AI panels.
+ */
+ private void wireContextCallbacks() {
ctx.notificationCallback = (msg, error) -> setNotification(msg, error);
ctx.openMarkdownCallback = actionsPopup::openMarkdown;
ctx.openOptionsCallback = actionsPopup::openOptions;
@@ -434,7 +487,12 @@ public class CamelMonitor extends CamelCommand {
actionsPopup.setBrowseFilesAction(this::openFilesPopup);
actionsPopup.setSwitchIntegrationAction(
() -> popupManager.openSwitchPopup(ctx.selectedPid, getNonVanishingIntegrations()));
+ }
+ /**
+ * Creates the tab registry, initialises all tabs and wires their data refresh callbacks.
+ */
+ private void createTabRegistry() {
tabRegistry = new TabRegistry(tabsState);
tabRegistry.initTabs(ctx, dataService, this::resetIntegrationTabState);
tabRegistry.setCallbacks(new TabRegistry.TabCallbacks() {
@@ -478,7 +536,12 @@ public class CamelMonitor extends CamelCommand {
popupManager.selectMorePopupEntry(index);
}
});
+ }
+ /**
+ * Registers the go-to-tab entries (including the pseudo entries for switch, shell and AI) in the actions popup.
+ */
+ private void setupGotoTabSupport() {
List<TabRegistry.TabEntry> gotoEntries = tabRegistry.allTabEntries();
gotoEntries.add(
new TabRegistry.TabEntry(TuiIcons.SWITCH, "Switch Integration", "Switch between integrations", "F3", -10, -1));
@@ -501,7 +564,12 @@ public class CamelMonitor extends CamelCommand {
}
});
actionsPopup.setActiveTabFilter(ctx::findSelectedIntegration, tabRegistry::moreTabs);
+ }
+ /**
+ * Creates the popup manager that owns the switch, more, confirm and files popups.
+ */
+ private void createPopupManager() {
popupManager = new PopupManager(
ctx, this::getNonVanishingIntegrations, tabRegistry::moreTabs, filesBrowser,
new PopupManager.PopupCallbacks() {
@@ -541,7 +609,12 @@ public class CamelMonitor extends CamelCommand {
}
}
});
+ }
+ /**
+ * Wires the Overview tab actions back to this monitor and the popups.
+ */
+ private void wireOverviewActions() {
tabRegistry.overviewTab().setActions(new OverviewTab.OverviewActions() {
@Override
public void sendRouteCommand(String pid, String routeId, String command) {
@@ -578,7 +651,13 @@ public class CamelMonitor extends CamelCommand {
popupManager.showConfirm(title, message, onConfirm);
}
});
+ }
+ /**
+ * Performs the synchronous initial data load and either opens the given directory as a project or auto-selects the
+ * single running integration.
+ */
+ private void loadInitialData(String openDir) throws Exception {
// Initial data load (synchronous before TUI starts)
dataService.refreshSync(this::refreshLogData, this::refreshConditionalData);
@@ -592,7 +671,12 @@ public class CamelMonitor extends CamelCommand {
// Auto-select if there's exactly one integration running
tabRegistry.overviewTab().selectCurrentIntegration();
}
+ }
+ /**
+ * Creates the MCP facade that exposes the TUI to AI agents, and connects it to the AI panel and overlays.
+ */
+ private void createMcpFacade() {
canvasOverlay.setOnOpen(() -> {
popupManager.dismissAll();
actionsPopup.close();
@@ -672,8 +756,13 @@ public class CamelMonitor extends CamelCommand {
aiPanel.setMcpFacade(mcpFacade);
aiPanel.setOtelSpans(dataService.otelSpans());
mcpFacade.setAiActivityLog(aiPanel::getActivityLog);
- Path mcpJsonFile = null;
actionsPopup.setAiActivityLog(aiPanel::getActivityLog);
+ }
+
+ /**
+ * Starts the embedded MCP server when --mcp is enabled.
+ */
+ private void startMcpServer() throws Exception {
if (mcp) {
mcpServer = new TuiMcpServer(mcpPort, mcpFacade);
try {
@@ -690,7 +779,12 @@ public class CamelMonitor extends CamelCommand {
}
}
aiPanel.setMcpInfo(mcp, mcpPort);
+ }
+ /**
+ * Starts the embedded web server when --web is enabled.
+ */
+ private void startWebServer() throws Exception {
if (web) {
webServer = new TuiWebServer(webPort, getMain(), classLoader, name, refreshInterval, theme);
try {
@@ -702,7 +796,13 @@ public class CamelMonitor extends CamelCommand {
web = false;
}
}
+ }
+ /**
+ * Creates the TamboUI runner, completes the runtime wiring, runs the event loop and shuts everything down
+ * afterwards.
+ */
+ private void runTui() throws Exception {
try (var tui = webBackend != null
? TuiBackendHelper.createTuiRunner(webBackend)
: TuiBackendHelper.createTuiRunner()) {
@@ -749,7 +849,6 @@ public class CamelMonitor extends CamelCommand {
clearRecordingProperties();
}
}
- return 0;
}
/**
@@ -984,6 +1083,46 @@ public class CamelMonitor extends CamelCommand {
}
return true;
}
+ boolean textEditing = isTextInputActive();
+ // Each session (the local terminal, or a browser tab connected via --web) owns an
+ // independent CamelMonitor/TuiRunner, so quitting here only ends this session.
+ if (!textEditing && (ke.isCharIgnoreCase('q') || ke.isCtrlC())) {
+ if (!ke.isCtrlC() && ctx.confirmActions) {
+ popupManager.showConfirm("Confirm Quit", " Quit the TUI? ", () -> runner.quit());
+ } else {
+ runner.quit();
+ }
+ return true;
+ }
+ if (ke.isCtrlC()) {
+ runner.quit();
+ return true;
+ }
+ if (!textEditing && handleTabDigitKeys(ke)) {
+ return true;
+ }
+ MonitorTab activeMonitorTab = tabRegistry.activeTab();
+ boolean overlayActive = activeMonitorTab != null && activeMonitorTab.isOverlayActive();
+ if (opensHelp(ke, textEditing)) {
+ // Only opens the overlay: while it is visible, dispatch delegates to
+ // helpOverlay.handleKeyEvent (which handles F1/?/q/Esc to close) before reaching here.
+ MonitorTab tab = tabRegistry.activeTab();
+ if (tab != null) {
+ String help = tab.getHelpText();
+ if (help != null) {
+ helpOverlay.open(help);
+ }
+ }
+ return true;
+ }
+ return handleFunctionKeys(ke);
+ }
+
+ /**
+ * Whether a text input (probe editor, search or filter field, SQL input, source editor) currently has focus, in
+ * which case single-letter global shortcuts must not fire.
+ */
+ private boolean isTextInputActive() {
boolean probeEditing = tabRegistry.selectedTabIndex() == TAB_MORE
&& tabRegistry.getActiveMoreTab() == tabRegistry.httpTab()
&& tabRegistry.httpTab().isProbeMode();
@@ -1010,73 +1149,58 @@ public class CamelMonitor extends CamelCommand {
&& tabRegistry.getActiveMoreTab() == tabRegistry.catalogTab()
&& tabRegistry.catalogTab().isFilterInputActive();
boolean filesBrowserTextActive = filesBrowser.isVisible() && filesBrowser.isSourceViewerTextInputActive();
- boolean textEditing = probeEditing || sourceSearchActive || logSearchActive || spanFilterActive
+ return probeEditing || sourceSearchActive || logSearchActive || spanFilterActive
|| beanFilterActive || classpathFilterActive || mavenDepsFilterActive || sqlInputActive
|| catalogFilterActive || filesBrowserTextActive;
- // Each session (the local terminal, or a browser tab connected via --web) owns an
- // independent CamelMonitor/TuiRunner, so quitting here only ends this session.
- if (!textEditing && (ke.isCharIgnoreCase('q') || ke.isCtrlC())) {
- if (!ke.isCtrlC() && ctx.confirmActions) {
- popupManager.showConfirm("Confirm Quit", " Quit the TUI? ", () -> runner.quit());
- } else {
- runner.quit();
- }
- return true;
+ }
+
+ /**
+ * Digit keys 1-0 switch tabs directly. Source needs an integration (not infra); the data tabs additionally need a
+ * running (non-phantom) integration.
+ */
+ private boolean handleTabDigitKeys(KeyEvent ke) {
+ if (ke.isChar('1')) {
+ return tabRegistry.handleTabKey(TAB_OVERVIEW, ctx, dataService);
}
- if (ke.isCtrlC()) {
- runner.quit();
- return true;
+ if (ke.isChar('3')) {
+ return tabRegistry.handleTabKey(TAB_LOG, ctx, dataService);
}
- if (!textEditing) {
- if (ke.isChar('1')) {
- return tabRegistry.handleTabKey(TAB_OVERVIEW, ctx, dataService);
+ if (!isInfraSelected()) {
+ if (ke.isChar('2')) {
+ return tabRegistry.handleTabKey(TAB_SOURCE, ctx, dataService);
}
- if (ke.isChar('3')) {
- return tabRegistry.handleTabKey(TAB_LOG, ctx, dataService);
- }
- if (!isInfraSelected()) {
- if (ke.isChar('2')) {
- return tabRegistry.handleTabKey(TAB_SOURCE, ctx, dataService);
+ if (!isPhantomSelected()) {
+ if (ke.isChar('4')) {
+ return tabRegistry.handleTabKey(TAB_ACTIVITY, ctx, dataService);
}
- if (!isPhantomSelected()) {
- if (ke.isChar('4')) {
- return tabRegistry.handleTabKey(TAB_ACTIVITY, ctx, dataService);
- }
- if (ke.isChar('5')) {
- return tabRegistry.handleTabKey(TAB_DIAGRAM, ctx, dataService);
- }
- if (ke.isChar('6')) {
- return tabRegistry.handleTabKey(TAB_ROUTES, ctx, dataService);
- }
- if (ke.isChar('7')) {
- return tabRegistry.handleTabKey(TAB_ENDPOINTS, ctx, dataService);
- }
- if (ke.isChar('8')) {
- return tabRegistry.handleTabKey(TAB_HISTORY, ctx, dataService);
- }
- if (ke.isChar('9')) {
- return tabRegistry.handleTabKey(TAB_ERRORS, ctx, dataService);
- }
- if (ke.isChar('0')) {
- return tabRegistry.handleTabKey(TAB_MORE, ctx, dataService);
- }
+ if (ke.isChar('5')) {
+ return tabRegistry.handleTabKey(TAB_DIAGRAM, ctx, dataService);
}
- }
- }
- MonitorTab activeMonitorTab = tabRegistry.activeTab();
- boolean overlayActive = activeMonitorTab != null && activeMonitorTab.isOverlayActive();
- if (opensHelp(ke, textEditing)) {
- // Only opens the overlay: while it is visible, dispatch delegates to
- // helpOverlay.handleKeyEvent (which handles F1/?/q/Esc to close) before reaching here.
- MonitorTab tab = tabRegistry.activeTab();
- if (tab != null) {
- String help = tab.getHelpText();
- if (help != null) {
- helpOverlay.open(help);
+ if (ke.isChar('6')) {
+ return tabRegistry.handleTabKey(TAB_ROUTES, ctx, dataService);
+ }
+ if (ke.isChar('7')) {
+ return tabRegistry.handleTabKey(TAB_ENDPOINTS, ctx, dataService);
+ }
+ if (ke.isChar('8')) {
+ return tabRegistry.handleTabKey(TAB_HISTORY, ctx, dataService);
+ }
+ if (ke.isChar('9')) {
+ return tabRegistry.handleTabKey(TAB_ERRORS, ctx, dataService);
+ }
+ if (ke.isChar('0')) {
+ return tabRegistry.handleTabKey(TAB_MORE, ctx, dataService);
}
}
- return true;
}
+ return false;
+ }
+
+ /**
+ * F6 shell, F8 AI panel, Ctrl+L log pin, Shift+F2 go-to tab, F2 actions, F3 switch integration, F10 process
+ * control.
+ */
+ private boolean handleFunctionKeys(KeyEvent ke) {
if (ke.isKey(KeyCode.F6)) {
if (shellPanel.isOpen()) {
shellPanel.close();
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CatalogCache.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CatalogCache.java
new file mode 100644
index 000000000000..24eed4e7d114
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CatalogCache.java
@@ -0,0 +1,70 @@
+/*
+ * 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.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.camel.catalog.CamelCatalog;
+import org.apache.camel.dsl.jbang.core.common.CatalogLoader;
+
+/**
+ * Lazily loads and caches a {@link CamelCatalog} per Camel version. A version whose catalog fails to load is remembered
+ * so the (slow) download is not retried on every render.
+ */
+final class CatalogCache {
+
+ private final Map<String, CamelCatalog> cache = new ConcurrentHashMap<>();
+ private final Set<String> failed = ConcurrentHashMap.newKeySet();
+
+ /**
+ * Returns the catalog matching the Camel version of the given integration, or null if unknown or unavailable.
+ */
+ CamelCatalog get(IntegrationInfo info) {
+ return info != null ? get(info.camelVersion) : null;
+ }
+
+ /**
+ * Returns the catalog for the given Camel version, or null if the version is unknown or the catalog cannot be
+ * loaded.
+ */
+ CamelCatalog get(String version) {
+ if (version == null) {
+ return null;
+ }
+ CamelCatalog cached = cache.get(version);
+ if (cached != null) {
+ return cached;
+ }
+ if (failed.contains(version)) {
+ return null;
+ }
+ try {
+ cached = CatalogLoader.loadCatalog(null, version, true);
+ if (cached != null) {
+ cache.put(version, cached);
+ } else {
+ failed.add(version);
+ }
+ return cached;
+ } catch (Exception e) {
+ failed.add(version);
+ return null;
+ }
+ }
+}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CatalogTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CatalogTab.java
index e63d3b766e95..ac9a44d9f4af 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CatalogTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CatalogTab.java
@@ -701,87 +701,7 @@ class CatalogTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Catalog
-
- The Catalog tab shows Camel catalog artifacts (components, data formats,
- languages, and others). By default it shows only artifacts used by the
- running integration (matched via Maven dependencies). Press `a` to toggle
- to the full catalog showing all available artifacts.
-
- For each Camel dependency in the integration, the tab cross-references
- the Camel catalog to identify all artifacts provided by that dependency.
- For example, `camel-core` provides the `direct`, `seda`, `timer`, `bean`,
- `log`, and `mock` components, while `camel-kafka` provides the `kafka`
- component.
-
- ## Table Columns
-
- - **NAME** — The catalog artifact name (e.g., `kafka`, `timer`, `json-jackson`)
- - **KIND** — The artifact type: `component`, `dataformat`, `language`, or `other`
- - **DESCRIPTION** — Short description of the artifact
- - **LABEL** — Category labels (e.g., "messaging", "scheduling", "transformation")
-
- Deprecated artifacts are shown dimmed with a "(deprecated)" suffix.
-
- ## Mode
-
- Press `a` to toggle between:
-
- - **app only** — show only artifacts from the integration's dependencies (default)
- - **all** — show the full Camel catalog
-
- ## Scope
-
- Press `f` to cycle the scope filter:
-
- - **all** — show all catalog artifacts (default)
- - **component** — show only components
- - **dataformat** — show only data formats
- - **language** — show only expression languages
- - **other** — show only miscellaneous artifacts
- - **eip** — show EIPs detected from the running app's routes
-
- ## Filter
-
- Press `/` to open the filter input. Type a search term and press
- `Enter` to filter by substring match on name, title, or label.
-
- ## Documentation
-
- Press `d` to open the full documentation for the selected artifact in
- a scrollable viewer. The documentation is loaded from the Camel catalog
- and converted from AsciiDoc to Markdown. Use `↑`/`↓`/`PgUp`/`PgDn` or
- mouse scroll to navigate, and `Esc` to close.
-
- ## Options
-
- Press `o` to open the options viewer for the selected artifact. This
- shows all configuration options in a structured format with types,
- defaults, enum values, groups, and descriptions.
-
- For **components**, the viewer has three tabs:
- - **Component** — component-level options
- - **Endpoint** — endpoint-level options
- - **Headers** — message headers with constant names
-
- For **data formats**, **languages**, and **others**, a single Options tab
- is shown. For **EIPs**, Options and exchange Properties tabs are shown.
-
- Press `←`/`→` or `Tab` to switch tabs. Use `↑`/`↓`/`PgUp`/`PgDn` or
- mouse scroll to navigate, and `Esc` to close.
-
- ## Keys
-
- - `s` — cycle sort column (name, kind, description)
- - `S` — reverse sort order
- - `a` — toggle app only / full catalog
- - `f` — cycle scope
- - `d` — open documentation viewer
- - `o` — open options viewer
- - `/` — open filter
- - `Esc` — clear filter or back
- """;
+ return DocHelper.loadHelpText("catalog");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CircuitBreakerTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CircuitBreakerTab.java
index 32bedc3a0a27..a13ad4f917fc 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CircuitBreakerTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CircuitBreakerTab.java
@@ -382,100 +382,7 @@ class CircuitBreakerTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Circuit Breakers
-
- Circuit breakers protect your integration from cascading failures. When a
- downstream service starts failing, the circuit breaker stops sending
- requests to it, giving it time to recover instead of overwhelming it
- with doomed requests.
-
- ## How It Works
-
- Imagine calling a REST API that is down. Without a circuit breaker,
- every message would wait for a connection timeout, creating a backlog.
- With a circuit breaker, after detecting enough failures, requests are
- immediately rejected — fast-failing instead of slow-failing.
-
- ## State Machine
-
- ```
- CLOSED ──(failures exceed threshold)──> OPEN
- ^ |
- | (wait timeout)
- | v
- +────(success in trial)──── HALF_OPEN
- ```
-
- - **CLOSED** (normal operation): All requests flow through. Failures
- are counted in a sliding window. When the failure rate exceeds the
- configured threshold (e.g., 50%), the circuit trips to OPEN.
-
- - **OPEN** (circuit tripped): All requests are immediately rejected
- with a fallback response — no call is made to the failing service.
- After a wait duration (e.g., 20 seconds), the circuit moves to
- HALF_OPEN to test if the service has recovered.
-
- - **HALF_OPEN** (testing recovery): A limited number of trial requests
- are allowed through. If they succeed, the circuit closes and normal
- operation resumes. If they fail, the circuit opens again for another
- wait period.
-
- ## Table Columns
-
- - **ROUTE** — Route containing this circuit breaker
- - **ID** — Processor ID of the circuit breaker node in the route
- - **COMPONENT** — Implementation library: `resilience4j` (most common) or `fault-tolerance` (MicroProfile)
- - **STATE** — Current breaker state: `CLOSED` (green, normal), `OPEN` (red, rejecting), or `HALF_OPEN` (yellow, testing)
- - **WINDOW** — Number of calls in the current sliding window used to calculate the failure rate
- - **INFLIGHT** — Calls currently in progress inside the circuit breaker
- - **SUCCESS** — Total number of successful calls
- - **FAIL** — Total number of failed calls (exceptions thrown by the protected code)
- - **RATE%** — Current failure rate percentage in the sliding window. When this exceeds the configured threshold, the circuit trips to OPEN
- - **REJECT** — Calls rejected because the circuit is OPEN. These calls never reach the downstream service — they fail fast with a fallback
- - **SINCE-LAST** — Time since the last circuit breaker activity, shown as up to two values separated by `/`: success/failed (e.g., `3s/1m14s`). Values are omitted when there is no activity of that type
-
- ## Example Screen
-
- ```
- ROUTE ID COMPONENT STATE WINDOW INFLIGHT SUCCESS FAIL RATE% REJECT
- route1 circuitBrk1 resilience4j CLOSED 10 0 450 5 1.0% 0
- route2 circuitBrk2 resilience4j OPEN 10 0 100 8 80.0% 25
- ```
-
- In this example, `route1` is healthy with a 1% failure rate. `route2`
- has tripped open with an 80% failure rate — 25 calls have been rejected
- since it opened. The circuit will stay open until the wait timeout
- expires, then try a few test calls in HALF_OPEN state.
-
- ## Detail View
-
- The bottom panel shows when a circuit breaker is selected:
-
- - **Failure rate gauge**: Visual bar from 0% to 100%, colored green
- (low risk), yellow (approaching threshold), or red (above threshold)
- - **Sparkline chart**: Mirrored view showing successful calls (green,
- upward) vs failed calls (red, downward) over time
- - **Metrics**: Detailed counts for total, fail, inflight, reject,
- and timing statistics (mean/min/max processing time)
-
- ## Configuration Tips
-
- Common Resilience4j settings you can tune in your route:
-
- - `minimumNumberOfCalls` — Minimum calls before failure rate is
- calculated (default: 100). Lower this for faster detection
- - `waitDurationInOpenState` — How long to wait before testing
- recovery (default: 60s)
- - `failureRateThreshold` — Percentage that triggers the circuit
- to open (default: 50%)
-
- ## Keys
-
- - `Up/Down` — select circuit breaker
- - `s` — cycle sort column
- - `S` — reverse sort order
- """;
+ return DocHelper.loadHelpText("circuit-breaker");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ClasspathTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ClasspathTab.java
index e85a27be369f..d517531efae8 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ClasspathTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ClasspathTab.java
@@ -468,66 +468,7 @@ class ClasspathTab extends AbstractTab {
@Override
public String getHelpText() {
- return """
- # Classpath
-
- The Classpath tab shows all JAR files on the integration's classpath,
- parsed into Maven coordinates (groupId, artifactId, version). This is
- useful for verifying which dependency versions are in use, finding
- unexpected or duplicate JARs, and understanding the integration's
- dependency footprint.
-
- ## Table Columns
-
- - **GROUP:ARTIFACT** — Maven coordinate of the JAR (e.g., `org.apache.camel:camel-core-model`)
- - **VERSION** — The version of the dependency (e.g., `4.12.0`)
-
- Camel JARs (those with `org.apache.camel` group) are displayed in
- bold. Other dependencies are dimmed for visual distinction.
-
- ## Example Screen
-
- ```
- org.apache.camel:camel-api 4.12.0
- org.apache.camel:camel-core-model 4.12.0
- org.apache.camel:camel-support 4.12.0
- org.apache.camel:camel-yaml-dsl 4.12.0
- com.fasterxml.jackson.core:jackson-core 2.18.3
- org.slf4j:slf4j-api 2.0.16
- ```
-
- ## Scope
-
- Press `f` to cycle the scope filter:
-
- - **all** — show all classpath entries (default)
- - **camel** — show only Apache Camel JARs
- - **other** — show only non-Camel (third-party) JARs
-
- The active scope is shown in the footer and title bar.
-
- ## Filter
-
- Press `/` to open the filter input. Type a search term and press
- `Enter` to filter the classpath by substring match. For example,
- type `kafka` to find all Kafka-related JARs, or `jackson` to find
- Jackson dependencies. The scope and text filter work together.
-
- ## When To Use
-
- - **Version conflicts**: Check if the expected version of a library is present. Multiple versions of the same library can cause class loading issues
- - **Missing dependencies**: Verify that a component's dependency JAR is on the classpath
- - **Dependency audit**: Review all transitive dependencies pulled in by the integration
- - **Size analysis**: Get a sense of how many JARs are loaded — large classpaths can slow startup
-
- ## Keys
-
- - `Up/Down` — navigate entries
- - `PgUp/PgDn` — scroll by page
- - `f` — cycle scope (all, camel, other)
- - `/` — open filter
- - `Esc` — clear filter or back
- """;
+ return DocHelper.loadHelpText("classpath");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ConfigurationTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ConfigurationTab.java
index 8bf37a59c810..daa2ce39ff52 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ConfigurationTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ConfigurationTab.java
@@ -496,51 +496,7 @@ class ConfigurationTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Configuration
-
- The Configuration tab shows all configuration properties of the running
- integration. This provides a complete view of how the integration is
- configured at runtime — including Camel settings, component options,
- and application properties.
-
- Properties can come from multiple sources and Camel merges them with
- a defined priority order.
-
- ## Table Columns
-
- - **KEY** — Property name following Camel's naming convention (e.g., `camel.main.name`, `camel.component.kafka.brokers`, `greeting.message`)
- - **VALUE** — Current resolved property value. Sensitive values (passwords, tokens) are masked as `xxxxxx` for security
- - **SOURCE** — Where the property was set:
- - `application.properties` — from the main properties file
- - `ENV` — from an environment variable
- - `JVM` — from a Java system property (`-D`)
- - `Spring Boot` — from Spring Boot configuration
- - `camel-component` — default from a Camel component
- - `override` — set programmatically in code
- - `initial` — set during context initialization
-
- ## Detail View
-
- Press `Enter` on a property to see its documentation from the Camel
- catalog. For `camel.main.*` and `camel.component.*` properties, the
- detail panel shows:
-
- - **Description** — what the property does
- - **Type** — expected value type (string, boolean, integer, etc.)
- - **Default** — default value if not explicitly set
- - **Enum values** — allowed values for enumerated properties
- - **Required** / **Deprecated** / **Secret** flags
- - **Group** — the configuration group this property belongs to
-
- ## Keys
-
- - `Up/Down` — select property
- - `Enter` — view property detail / documentation
- - `s` — cycle sort column
- - `S` — reverse sort order
- - `Esc` — close detail / back
- """;
+ return DocHelper.loadHelpText("configuration");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ConsumersTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ConsumersTab.java
index ee8997034b60..4f50f9acd942 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ConsumersTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ConsumersTab.java
@@ -301,69 +301,7 @@ class ConsumersTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Consumers
-
- Consumers are the **input** side of a Camel route. They listen for or poll
- data from external systems (message brokers, file directories, databases,
- timers, etc.) and create exchanges that flow through the route.
-
- There are two types of consumers:
-
- - **Event-driven** (e.g., `seda`, `direct`, `platform-http`): React instantly
- when a message arrives. No polling — messages are pushed to the consumer.
- - **Polling** (e.g., `file`, `ftp`, `sql`, `timer`): Run on a scheduler that
- periodically checks for new data. The POLLS column tracks these cycles.
-
- ## Table Columns
-
- - **ROUTE** — The route this consumer belongs to. Each route has exactly one consumer (its `from` endpoint)
- - **STATUS** — Consumer state: `Started` (running normally), `Polling` (currently in a poll cycle). Shows a health warning icon if the consumer health check is `DOWN`
- - **TYPE** — The Camel component type (e.g., `kafka`, `file`, `timer`, `cron`, `seda`)
- - **POLLS** — Total number of poll cycles the scheduler has executed. This counts poll **attempts**, not messages received — a poll may check for new files and find none. For event-driven consumers (like `seda`), this column is empty
- - **SCHEDULE** — How often the consumer polls: a fixed interval like `1s` or `5000ms`, or a cron expression like `0 0/5 * * *`. Only shown for polling consumers
- - **SINCE-LAST** — Three timestamps showing **started** / **completed** / **failed**: when the last exchange was created, when the last exchange completed successfully, and when the last exchange failed. Helps identify stale consumers or recurring failures
- - **URI** — The full endpoint URI (e.g., `timer://hello?period=2000`). If the consumer health check is DOWN, the failure message is shown here instead
-
- ## Example Screen
-
- ```
- ROUTE STATUS TYPE POLLS SCHEDULE SINCE-LAST URI
- timer-to-log Started timer 17 2s 1s/1s/- timer://hello?period=2000
- timer-to-seda Started timer 12 3s 0s/0s/- timer://pump?period=3000
- seda-consumer Started seda 0s/0s/- seda://queue
- ```
-
- Notice that `seda-consumer` has no POLLS or SCHEDULE because it is
- event-driven — it reacts immediately when a message is put into the
- SEDA queue by another route.
-
- ## Understanding POLLS vs TOTAL
-
- A common confusion: POLLS counts how many times the scheduler fired,
- not how many messages were received. Consider a file consumer polling
- every 5 seconds:
-
- - After 1 minute: POLLS = 12 (polled 12 times)
- - But TOTAL might be 3 (only 3 files were found and processed)
- - The other 9 polls found no new files
-
- A high POLLS count with zero TOTAL exchanges means the consumer is
- actively checking but finding no new data — which is normal for many
- use cases (e.g., watching a directory for new files).
-
- ## Backoff
-
- Some consumers support backoff — reducing poll frequency when polls
- return no data. This saves resources when the source is idle. The
- consumer automatically returns to normal frequency when data appears.
-
- ## Keys
-
- - `Up/Down` — select consumer
- - `s` — cycle sort column
- - `S` — reverse sort order
- """;
+ return DocHelper.loadHelpText("consumers");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CveAuditTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CveAuditTab.java
index ed99acccf437..a7fd1c8ee5f6 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CveAuditTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CveAuditTab.java
@@ -732,47 +732,7 @@ class CveAuditTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # CVE Audit
-
- The CVE Audit tab scans the integration's classpath dependencies
- against the **OSV.dev** vulnerability database (https://osv.dev).
- OSV.dev aggregates vulnerabilities from multiple sources including
- the GitHub Advisory Database (GHSA), the National Vulnerability
- Database (NVD/CVE), and other ecosystem-specific databases.
-
- It queries all Maven JARs using the OSV batch API and displays
- known CVEs grouped by severity.
-
- ## Table Columns
-
- - **SEVERITY** — CRITICAL (red), HIGH (red), MEDIUM (yellow), LOW (dim)
- - **CVE ID** — the canonical vulnerability identifier (prefers CVE- over GHSA-)
- - **ARTIFACT** — the affected Maven artifact (groupId:artifactId:version)
- - **VIA** — the direct dependency that pulls in the affected artifact (transitive dependency chain)
- - **SUMMARY** — brief description of the vulnerability
-
- ## Detail View
-
- The detail panel at the bottom shows the full summary, affected
- artifacts, aliases (e.g., both CVE and GHSA IDs for the same issue),
- published date, and a link to the OSV.dev page.
-
- ## Caching
-
- Results are cached globally so re-visiting the tab is instant.
- Switching to another integration that shares the same JARs will
- also benefit from the cache. Press `r` to force a rescan.
-
- ## Keys
-
- - `Up/Down` — navigate vulnerabilities
- - `PgUp/PgDn` — scroll detail panel
- - `s` — cycle sort column
- - `S` — reverse sort order
- - `r` — rescan (clear cache and re-query)
- - `Esc` — back
- """;
+ return DocHelper.loadHelpText("cve-audit");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DataSourceTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DataSourceTab.java
index fc5df616c742..5cb3b625cf13 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DataSourceTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DataSourceTab.java
@@ -185,47 +185,7 @@ class DataSourceTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # DataSource
-
- Displays connection pool metrics for all `javax.sql.DataSource` beans
- registered in the Camel registry. Supports **HikariCP** (Spring Boot default)
- and **Agroal** (Quarkus default) connection pools.
-
- ## Table Columns
-
- - **NAME** — The bean name of the DataSource in the registry
- - **POOL** — The pool name (HikariCP pool name) or pool type (HikariCP / Agroal / Unknown)
- - **ACTIVE** — Number of connections currently in use. Shown in red when equal to MAX (pool exhausted)
- - **IDLE** — Number of idle connections available in the pool
- - **TOTAL** — Total connections (active + idle) currently managed by the pool
- - **MAX** — Maximum pool size configured. When ACTIVE reaches MAX, new connection requests will wait
- - **WAITING** — Number of threads waiting for a connection. Shown in yellow when > 0
- - **TYPE** — The Java class of the DataSource implementation
-
- ## Pool Exhaustion
-
- When **ACTIVE = MAX**, the pool is exhausted — no idle connections remain.
- New requests must wait for a connection to be released. The ACTIVE column
- turns red to signal this condition. If WAITING also increases, the application
- may experience timeouts.
-
- ## Connection Pools
-
- ### HikariCP
- The default connection pool for Spring Boot. Known for its speed and small
- footprint. Default max pool size is 10.
-
- ### Agroal
- The default connection pool for Quarkus. Provides leak detection and
- connection validation. Shows additional metrics like max-used and leak count.
-
- ## Keys
-
- - `Up/Down` — select datasource
- - `s` — cycle sort column
- - `S` — reverse sort order
- """;
+ return DocHelper.loadHelpText("data-source");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DiagramDetailSupport.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DiagramDetailSupport.java
new file mode 100644
index 000000000000..3565dd3771f3
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DiagramDetailSupport.java
@@ -0,0 +1,557 @@
+/*
+ * 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.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import dev.tamboui.layout.Rect;
+import dev.tamboui.markdown.MarkdownView;
+import dev.tamboui.style.Color;
+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;
+import dev.tamboui.widgets.block.Block;
+import dev.tamboui.widgets.block.BorderType;
+import dev.tamboui.widgets.block.Borders;
+import dev.tamboui.widgets.paragraph.Paragraph;
+import org.apache.camel.catalog.CamelCatalog;
+import org.apache.camel.dsl.jbang.core.commands.tui.diagram.DiagramColors;
+import org.apache.camel.util.TimeUtils;
+import org.apache.camel.util.json.JsonObject;
+
+import static org.apache.camel.dsl.jbang.core.commands.tui.EipDocSupport.*;
+import static org.apache.camel.dsl.jbang.core.commands.tui.TuiHelper.*;
+
+/**
+ * The side panels that accompany a route diagram: the route / topology-node info panel, the selected EIP node info
+ * panel, and the scrollable EIP detail panel backed by the catalog.
+ * <p>
+ * Owns the per-route processor-detail cache (fetched over IPC), the catalog cache and the detail panel scroll state so
+ * that {@link RoutesTab} and {@link DiagramTab} share one implementation.
+ */
+final class DiagramDetailSupport {
+
+ private final MonitorContext ctx;
+ private final DiagramSupport diagram;
+ private final CatalogCache catalogCache = new CatalogCache();
+
+ private int detailScroll;
+ private Rect lastDetailArea;
+ private String lastDetailNodeId;
+ private volatile JsonObject cachedRouteDetail;
+ private volatile String cachedRouteDetailId;
+ private volatile boolean detailLoading;
+ private volatile String detailLoadingRouteId;
+
+ DiagramDetailSupport(MonitorContext ctx, DiagramSupport diagram) {
+ this.ctx = ctx;
+ this.diagram = diagram;
+ }
+
+ /**
+ * Clears the cached processor detail and scroll position, e.g. when the detail panel is toggled or the selected
+ * integration or route changes.
+ */
+ void reset() {
+ detailScroll = 0;
+ lastDetailNodeId = null;
+ cachedRouteDetail = null;
+ cachedRouteDetailId = null;
+ detailLoadingRouteId = null;
+ detailLoading = false;
+ }
+
+ /**
+ * Scrolls the detail panel by the given number of lines (negative scrolls up).
+ */
+ void scrollBy(int delta) {
+ detailScroll = Math.max(0, detailScroll + delta);
+ }
+
+ /**
+ * Whether the given screen coordinate is inside the most recently rendered detail panel.
+ */
+ boolean containsMouse(int x, int y) {
+ return lastDetailArea != null && lastDetailArea.contains(x, y);
+ }
+
+ /**
+ * Returns the catalog for the Camel version of the given integration, or null when unavailable.
+ */
+ CamelCatalog getCatalog(IntegrationInfo info) {
+ return catalogCache.get(info);
+ }
+
+ void ensureProcessorDetailLoaded(String routeId) {
+ if (routeId != null && cachedRouteDetail == null
+ && !"*".equals(detailLoadingRouteId)) {
+ detailLoadingRouteId = "*";
+ detailLoading = true;
+ if (ctx.runner != null) {
+ ctx.backgroundExecutor.execute(() -> {
+ JsonObject result = requestRouteProcessorDetail("*");
+ cachedRouteDetail = result;
+ cachedRouteDetailId = "*";
+ detailLoading = false;
+ });
+ }
+ }
+ }
+
+ private JsonObject requestRouteProcessorDetail(String routeId) {
+ if (ctx.selectedPid == null) {
+ return null;
+ }
+ try {
+ JsonObject root = new JsonObject();
+ root.put("action", "processor-detail");
+ root.put("routeId", "*");
+ return ctx.executeAction(ctx.selectedPid, root, 5000);
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ JsonObject findProcessorEntry(String nodeId) {
+ if (cachedRouteDetail == null || nodeId == null) {
+ return null;
+ }
+ for (JsonObject p : getAllProcessors(cachedRouteDetail)) {
+ if (nodeId.equals(p.getString("id"))) {
+ return p;
+ }
+ }
+ return null;
+ }
+
+ Map<Integer, List<SourceViewer.DocEntry>> provideAllQuickDocs(List<JsonObject> cd) {
+ if (cachedRouteDetail == null || cd.isEmpty()) {
+ return Map.of();
+ }
+
+ List<JsonObject> processors = getAllProcessors(cachedRouteDetail);
+ if (processors.isEmpty()) {
+ return Map.of();
+ }
+
+ IntegrationInfo info = ctx.findSelectedIntegration();
+ CamelCatalog catalog = info != null ? getCatalog(info) : null;
+
+ Map<Integer, List<SourceViewer.DocEntry>> result = new LinkedHashMap<>();
+ for (JsonObject proc : processors) {
+ Integer line = proc.getInteger("line");
+ if (line == null || line <= 0) {
+ continue;
+ }
+
+ int eipIdx = findCodeDataIndex(cd, line, -1);
+ if (eipIdx < 0 || result.containsKey(eipIdx)) {
+ continue;
+ }
+ String endpointUri = proc.getString("endpointUri");
+ String type = proc.getString("type");
+
+ if (endpointUri != null && catalog != null) {
+ buildEndpointInlineDoc(result, cd, catalog, endpointUri, eipIdx);
+ } else if (type != null) {
+ buildEipInlineDoc(result, cd, catalog, type, proc.getMap("options"), eipIdx);
+ }
+ }
+ return result;
+ }
+
+ static Line buildBreadcrumbTitle(Deque<String> routeNavigationStack, String drillDownRouteId) {
+ Style nameStyle = Theme.label().bold();
+ List<Span> spans = new ArrayList<>();
+ spans.add(Span.raw(" Route ["));
+ if (routeNavigationStack.isEmpty()) {
+ spans.add(Span.styled(drillDownRouteId, nameStyle));
+ } else {
+ for (var it = routeNavigationStack.descendingIterator(); it.hasNext();) {
+ spans.add(Span.styled(it.next(), nameStyle));
+ spans.add(Span.raw(" → "));
+ }
+ spans.add(Span.styled(drillDownRouteId, nameStyle));
+ }
+ spans.add(Span.raw("] "));
+ return Line.from(spans);
+ }
+
+ void renderRouteInfoPanel(Frame frame, Rect area, IntegrationInfo info, String routeId) {
+ RouteInfo route = null;
+ for (RouteInfo r : info.routes) {
+ if (routeId.equals(r.routeId)) {
+ route = r;
+ break;
+ }
+ }
+
+ List<Line> lines = new ArrayList<>();
+ if (route != null) {
+ lines.add(Line.from(
+ Span.styled(" Route: ", Theme.muted()),
+ Span.styled(route.routeId, Style.EMPTY.fg(Theme.baseFg()).bold())));
+ lines.add(Line.from(
+ Span.styled(" From: ", Theme.muted()),
+ Span.raw(route.from != null ? route.from : "")));
+ String stateLabel = route.state != null ? route.state : "";
+ Style stateStyle = "Started".equals(route.state) ? Theme.success() : Theme.error();
+ lines.add(Line.from(
+ Span.styled(" State: ", Theme.muted()),
+ Span.styled(stateLabel, stateStyle)));
+
+ lines.add(Line.from(Span.raw("")));
+ lines.add(Line.from(
+ Span.styled(" Uptime: ", Theme.muted()),
+ Span.raw(route.uptime != null ? route.uptime : "")));
+ String tpUnit = ctx.ratePerMinute ? " msg/m" : " msg/s";
+ String tpValue = route.throughput != null
+ ? (ctx.ratePerMinute ? TuiHelper.throughputPerMinute(route.throughput) : route.throughput)
+ : "";
+ lines.add(Line.from(
+ Span.styled(" Rate: ", Theme.muted()),
+ Span.raw(tpValue),
+ Span.styled(tpUnit, Theme.muted())));
+ if (route.coverage != null) {
+ lines.add(Line.from(
+ Span.styled(" Coverage: ", Theme.muted()),
+ Span.raw(route.coverage)));
+ }
+
+ lines.add(Line.from(Span.raw("")));
+ int w = numWidth(route.total, route.failed, route.inflight);
+ lines.add(Line.from(
+ Span.styled(" Total: ", Theme.muted()),
+ Span.raw(String.format("%" + w + "d", route.total))));
+ Style failStyle = route.failed > 0 ? Theme.error().bold() : Style.EMPTY;
+ lines.add(Line.from(
+ Span.styled(" Failed: ", Theme.muted()),
+ Span.styled(String.format("%" + w + "d", route.failed), failStyle)));
+ lines.add(Line.from(
+ Span.styled(" Inflight: ", Theme.muted()),
+ Span.raw(String.format("%" + w + "d", route.inflight))));
+
+ lines.add(Line.from(Span.raw("")));
+ if (route.total > 0) {
+ lines.add(Line.from(
+ Span.styled(" Mean: ", Theme.muted()),
+ Span.raw(formatDurationMs(route.meanTime))));
+ lines.add(Line.from(
+ Span.styled(" Max: ", Theme.muted()),
+ Span.raw(formatDurationMs(route.maxTime))));
+ lines.add(Line.from(
+ Span.styled(" Min: ", Theme.muted()),
+ Span.raw(formatDurationMs(route.minTime))));
+ if (route.p50Time >= 0) {
+ lines.add(Line.from(Span.raw("")));
+ lines.add(Line.from(
+ Span.styled(" p50: ", Theme.muted()),
+ Span.raw(formatDurationMs(route.p50Time))));
+ lines.add(Line.from(
+ Span.styled(" p95: ", Theme.muted()),
+ Span.raw(formatDurationMs(route.p95Time))));
+ lines.add(Line.from(
+ Span.styled(" p99: ", Theme.muted()),
+ Span.raw(formatDurationMs(route.p99Time))));
+ lines.add(buildPercentileBarLine(
+ route.p50Time, route.p95Time, route.p99Time, area.width() - 3));
+ }
+ }
+
+ if (route.sinceLastCompleted != null || route.sinceLastFailed != null) {
+ lines.add(Line.from(Span.raw("")));
+ lines.add(Line.from(
+ Span.styled(" Since last:", Theme.muted())));
+ if (route.sinceLastCompleted != null) {
+ lines.add(Line.from(
+ Span.styled(" ok: ", Theme.muted()),
+ Span.raw(route.sinceLastCompleted)));
+ }
+ if (route.sinceLastFailed != null) {
+ lines.add(Line.from(
+ Span.styled(" fail: ", Theme.muted()),
+ Span.styled(route.sinceLastFailed,
+ Theme.error())));
+ }
+ }
+
+ } else {
+ // External endpoint — show topology node data
+ var topoNode = diagram.getSelectedTopologyNode();
+ if (topoNode != null) {
+ boolean isInbound = "external-in".equals(topoNode.nodeType);
+ boolean isBridge = "external".equals(topoNode.nodeType);
+ String label = isBridge ? " External" : isInbound ? " Inbound" : " Outbound";
+ lines.add(Line.from(
+ Span.styled(label, Style.EMPTY.fg(Theme.accent()).bold())));
+ lines.add(Line.from(Span.raw("")));
+ lines.add(Line.from(
+ Span.styled(" URI: ", Theme.muted()),
+ Span.raw(topoNode.from != null ? topoNode.from : "")));
+ if (topoNode.description != null && !topoNode.description.isBlank()) {
+ lines.add(Line.from(
+ Span.styled(" Path: ", Theme.muted()),
+ Span.raw(topoNode.description)));
+ }
+ if (!isBridge) {
+ String connectedRoute = diagram.getConnectedRouteId(routeId);
+ if (connectedRoute != null) {
+ lines.add(Line.from(Span.raw("")));
+ lines.add(Line.from(
+ Span.styled(isInbound ? " To route: " : " From route: ", Theme.muted()),
+ Span.styled(connectedRoute, Style.EMPTY.fg(Theme.baseFg()))));
+ }
+ }
+ if (topoNode.exchangesTotal > 0 || topoNode.exchangesFailed > 0) {
+ lines.add(Line.from(Span.raw("")));
+ lines.add(Line.from(
+ Span.styled(" Total: ", Theme.muted()),
+ Span.raw(String.valueOf(topoNode.exchangesTotal))));
+ if (topoNode.exchangesFailed > 0) {
+ lines.add(Line.from(
+ Span.styled(" Failed: ", Theme.muted()),
+ Span.styled(String.valueOf(topoNode.exchangesFailed),
+ Theme.error().bold())));
+ }
+ }
+ } else {
+ lines.add(Line.from(
+ Span.styled(" " + routeId, Style.EMPTY.fg(Theme.accent()).bold())));
+ lines.add(Line.from(
+ Span.styled(" (external endpoint)", Style.EMPTY.dim())));
+ }
+ }
+
+ Paragraph paragraph = Paragraph.builder()
+ .text(Text.from(lines))
+ .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
+ .title(" Info ").build())
+ .build();
+ frame.renderWidget(paragraph, area);
+ }
+
+ void renderEipInfoPanel(Frame frame, Rect area, String drillDownRouteId) {
+ List<Line> lines = new ArrayList<>();
+ var selected = diagram.getSelectedEipNodeBox();
+ if (selected != null && selected.layoutNode() != null) {
+ var ln = selected.layoutNode();
+
+ String typeLabel = ln.type != null ? ln.type : "unknown";
+ Color eipColor = DiagramColors.getEipColor(typeLabel);
+ lines.add(Line.from(
+ Span.styled(" [" + typeLabel + "]", Style.EMPTY.fg(eipColor).bold())));
+
+ String label = String.join("", ln.wrappedLines);
+ if (!label.isBlank()) {
+ lines.add(Line.from(
+ Span.styled(" ", Style.EMPTY.dim()),
+ Span.raw(label)));
+ }
+
+ if (ln.id != null) {
+ lines.add(Line.from(
+ Span.styled(" ID: ", Theme.muted()),
+ Span.raw(ln.id)));
+ }
+
+ String linkedRoute = diagram.findLinkedRouteId(drillDownRouteId);
+ if (linkedRoute != null && diagram.getRouteLayout(linkedRoute) != null) {
+ lines.add(Line.from(Span.raw("")));
+ lines.add(Line.from(
+ Span.styled(" ↵ ", Theme.label().bold()),
+ Span.styled(linkedRoute, Style.EMPTY.fg(Theme.baseFg()))));
+ } else if (ln.treeNode != null && ln.treeNode.info.remote) {
+ lines.add(Line.from(Span.raw("")));
+ String arrow = "from".equals(ln.type) ? " external → " : " → external";
+ lines.add(Line.from(
+ Span.styled(arrow, Theme.muted())));
+ }
+
+ if (ln.treeNode != null && ln.treeNode.info.stat != null) {
+ var stat = ln.treeNode.info.stat;
+ lines.add(Line.from(Span.raw("")));
+ int w = numWidth(stat.exchangesTotal, stat.exchangesFailed, stat.exchangesInflight);
+ lines.add(Line.from(
+ Span.styled(" Total: ", Theme.muted()),
+ Span.raw(String.format("%" + w + "d", stat.exchangesTotal))));
+ Style failStyle = stat.exchangesFailed > 0
+ ? Theme.error().bold() : Style.EMPTY;
+ lines.add(Line.from(
+ Span.styled(" Failed: ", Theme.muted()),
+ Span.styled(String.format("%" + w + "d", stat.exchangesFailed), failStyle)));
+ lines.add(Line.from(
+ Span.styled(" Inflight: ", Theme.muted()),
+ Span.raw(String.format("%" + w + "d", stat.exchangesInflight))));
+ if (stat.exchangesThroughput != null && !stat.exchangesThroughput.isEmpty()) {
+ String tpUnit = ctx.ratePerMinute ? " msg/m" : " msg/s";
+ String tpValue = ctx.ratePerMinute
+ ? TuiHelper.throughputPerMinute(stat.exchangesThroughput)
+ : stat.exchangesThroughput;
+ lines.add(Line.from(
+ Span.styled(" Rate: ", Theme.muted()),
+ Span.raw(tpValue),
+ Span.styled(tpUnit, Theme.muted())));
+ }
+
+ if (stat.exchangesTotal > 0) {
+ lines.add(Line.from(Span.raw("")));
+ lines.add(Line.from(
+ Span.styled(" Mean: ", Theme.muted()),
+ Span.raw(formatDurationMs(stat.meanProcessingTime))));
+ lines.add(Line.from(
+ Span.styled(" Max: ", Theme.muted()),
+ Span.raw(formatDurationMs(stat.maxProcessingTime))));
+ lines.add(Line.from(
+ Span.styled(" Min: ", Theme.muted()),
+ Span.raw(formatDurationMs(stat.minProcessingTime))));
+ lines.add(Line.from(
+ Span.styled(" Last: ", Theme.muted()),
+ Span.raw(formatDurationMs(stat.lastProcessingTime))));
+ if (stat.p50ProcessingTime >= 0) {
+ lines.add(Line.from(Span.raw("")));
+ lines.add(Line.from(
+ Span.styled(" p50: ", Theme.muted()),
+ Span.raw(formatDurationMs(stat.p50ProcessingTime))));
+ lines.add(Line.from(
+ Span.styled(" p95: ", Theme.muted()),
+ Span.raw(formatDurationMs(stat.p95ProcessingTime))));
+ lines.add(Line.from(
+ Span.styled(" p99: ", Theme.muted()),
+ Span.raw(formatDurationMs(stat.p99ProcessingTime))));
+ lines.add(buildPercentileBarLine(
+ stat.p50ProcessingTime, stat.p95ProcessingTime,
+ stat.p99ProcessingTime, area.width() - 3));
+ }
+
+ if (stat.lastCompletedExchangeTimestamp > 0 || stat.lastFailedExchangeTimestamp > 0) {
+ long now = System.currentTimeMillis();
+ lines.add(Line.from(Span.raw("")));
+ lines.add(Line.from(
+ Span.styled(" Since last:", Theme.muted())));
+ if (stat.lastCompletedExchangeTimestamp > 0) {
+ long ago = now - stat.lastCompletedExchangeTimestamp;
+ lines.add(Line.from(
+ Span.styled(" ok: ", Theme.muted()),
+ Span.raw(TimeUtils.printDuration(ago, false))));
+ }
+ if (stat.lastFailedExchangeTimestamp > 0) {
+ long ago = now - stat.lastFailedExchangeTimestamp;
+ lines.add(Line.from(
+ Span.styled(" fail: ", Theme.muted()),
+ Span.styled(TimeUtils.printDuration(ago, false),
+ Theme.error())));
+ }
+ }
+ }
+ }
+ } else {
+ lines.add(Line.from(Span.styled(" (no node selected)", Style.EMPTY.dim())));
+ }
+
+ Paragraph paragraph = Paragraph.builder()
+ .text(Text.from(lines))
+ .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
+ .title(" Info ").build())
+ .build();
+ frame.renderWidget(paragraph, area);
+ }
+
+ void renderDetail(Frame frame, Rect area, IntegrationInfo info, String drillDownRouteId) {
+ lastDetailArea = area;
+ var selected = diagram.getSelectedEipNodeBox();
+ if (selected == null || selected.layoutNode() == null) {
+ frame.renderWidget(
+ MarkdownView.builder()
+ .source("*Select an EIP node*")
+ .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
+ .title(" EIP Detail ").build())
+ .styles(Theme.markdownStyles())
+ .build(),
+ area);
+ return;
+ }
+
+ String nodeId = selected.layoutNode().id;
+ String eipType = selected.layoutNode().type;
+ if (nodeId == null || eipType == null) {
+ frame.renderWidget(
+ MarkdownView.builder()
+ .source("*No detail available*")
+ .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
+ .title(" EIP Detail ").build())
+ .styles(Theme.markdownStyles())
+ .build(),
+ area);
+ return;
+ }
+
+ // reset scroll when navigating to a different node
+ if (!nodeId.equals(lastDetailNodeId)) {
+ lastDetailNodeId = nodeId;
+ detailScroll = 0;
+ }
+
+ // load route detail once (covers all routes and processors)
+ ensureProcessorDetailLoaded(drillDownRouteId);
+
+ // find the selected processor in the cached route data
+ JsonObject processorEntry = findProcessorEntry(nodeId);
+
+ StringBuilder md = new StringBuilder();
+ CamelCatalog catalog = getCatalog(info);
+
+ if (processorEntry != null) {
+ String type = processorEntry.getString("type");
+ String endpointUri = processorEntry.getString("endpointUri");
+
+ if ("from".equals(type) && endpointUri != null && catalog != null) {
+ renderEndpointDetail(md, catalog, endpointUri);
+ } else if (type != null) {
+ renderEipDetail(md, catalog, type, processorEntry.getMap("options"));
+ } else {
+ md.append("*No detail available*\n");
+ }
+ } else if (detailLoading) {
+ md.append("*Loading...*\n");
+ } else {
+ md.append("*No detail available*\n");
+ }
+
+ String title = " " + eipType + " [" + nodeId + "] ";
+ if (CharWidth.of(title) > area.width() - 4) {
+ title = " " + CharWidth.truncateWithEllipsis(
+ eipType + " [" + nodeId + "]", area.width() - 6, CharWidth.TruncatePosition.MIDDLE) + " ";
+ }
+
+ frame.renderWidget(
+ MarkdownView.builder()
+ .source(md.toString())
+ .scroll(detailScroll)
+ .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
+ .title(title).build())
+ .styles(Theme.markdownStyles())
+ .build(),
+ area);
+ }
+}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DiagramSupport.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DiagramSupport.java
index 1bfb200729fc..50fa2da922d2 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DiagramSupport.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DiagramSupport.java
@@ -2106,4 +2106,48 @@ class DiagramSupport {
lr.labelY -= shift;
lr.maxY -= shift;
}
+
+ /**
+ * Finds the index of the EIP node box whose source line is closest to the given line, preferring the closest node
+ * at or before the line. Returns -1 when there are no boxes with line information.
+ */
+ int findClosestEipNode(int sourceLine) {
+ var boxes = getEipNodeBoxes();
+ if (boxes.isEmpty()) {
+ return -1;
+ }
+ // Prefer the closest node at or before the cursor line
+ int bestBeforeIdx = -1;
+ int bestBeforeDist = Integer.MAX_VALUE;
+ int bestAfterIdx = -1;
+ int bestAfterDist = Integer.MAX_VALUE;
+ for (int i = 0; i < boxes.size(); i++) {
+ var box = boxes.get(i);
+ if (box.layoutNode() == null || box.layoutNode().treeNode == null) {
+ continue;
+ }
+ int nodeLine = box.layoutNode().treeNode.info.line;
+ if (nodeLine <= 0) {
+ continue;
+ }
+ if (nodeLine == sourceLine) {
+ return i;
+ }
+ if (nodeLine < sourceLine) {
+ int dist = sourceLine - nodeLine;
+ if (dist < bestBeforeDist) {
+ bestBeforeDist = dist;
+ bestBeforeIdx = i;
+ }
+ } else {
+ int dist = nodeLine - sourceLine;
+ if (dist < bestAfterDist) {
+ bestAfterDist = dist;
+ bestAfterIdx = i;
+ }
+ }
+ }
+ return bestBeforeIdx >= 0 ? bestBeforeIdx : bestAfterIdx;
+ }
+
}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DiagramTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DiagramTab.java
index 6160d6260185..2f352524f5f6 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DiagramTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DiagramTab.java
@@ -16,25 +16,16 @@
*/
package org.apache.camel.dsl.jbang.core.commands.tui;
-import java.net.URISyntaxException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedHashMap;
import java.util.List;
-import java.util.Map;
-import java.util.Set;
import dev.tamboui.layout.Constraint;
import dev.tamboui.layout.Layout;
import dev.tamboui.layout.Rect;
-import dev.tamboui.markdown.MarkdownView;
-import dev.tamboui.style.Color;
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;
@@ -46,12 +37,6 @@ import dev.tamboui.widgets.block.Block;
import dev.tamboui.widgets.block.BorderType;
import dev.tamboui.widgets.block.Borders;
import dev.tamboui.widgets.paragraph.Paragraph;
-import org.apache.camel.catalog.CamelCatalog;
-import org.apache.camel.dsl.jbang.core.common.CatalogLoader;
-import org.apache.camel.tooling.model.BaseOptionModel;
-import org.apache.camel.tooling.model.ComponentModel;
-import org.apache.camel.tooling.model.EipModel;
-import org.apache.camel.util.TimeUtils;
import org.apache.camel.util.json.JsonArray;
import org.apache.camel.util.json.JsonObject;
@@ -72,16 +57,8 @@ class DiagramTab extends AbstractTab {
private final DragSplit hSplit = new DragSplit();
private boolean detailMode;
- private int detailScroll;
- private Rect lastDetailArea;
+ private final DiagramDetailSupport detail = new DiagramDetailSupport(ctx, diagram);
private final DragSplit vSplit = new DragSplit();
- private final Map<String, CamelCatalog> catalogCache = new HashMap<>();
- private final Set<String> catalogLoadFailed = new HashSet<>();
- private volatile JsonObject cachedRouteDetail;
- private volatile String cachedRouteDetailId;
- private volatile boolean detailLoading;
- private volatile String detailLoadingRouteId;
- private String lastDetailNodeId;
DiagramTab(MonitorContext ctx) {
super(ctx);
@@ -126,6 +103,16 @@ class DiagramTab extends AbstractTab {
return true;
}
+ if (handleNodeNavigationKeys(ke)) {
+ return true;
+ }
+ return handleDiagramActionKeys(ke);
+ }
+
+ /**
+ * Arrow/Home/End navigation between topology nodes or EIP nodes of the drilled-down route.
+ */
+ private boolean handleNodeNavigationKeys(KeyEvent ke) {
// Node selection navigation in topology mode
if (topologyMode && diagram.isShowDiagram() && diagram.hasDiagramData()
&& !diagram.getNodeBoxes().isEmpty()) {
@@ -194,16 +181,19 @@ class DiagramTab extends AbstractTab {
return true;
}
}
+ return false;
+ }
+ /**
+ * Detail panel, go-to node, jump back to topology, scrolling, metrics/external/description toggles, and Enter to
+ * jump into a linked route or drill down.
+ */
+ private boolean handleDiagramActionKeys(KeyEvent ke) {
// Toggle detail panel in drill-down mode
if (!topologyMode && diagram.isShowDiagram() && !diagram.getEipNodeBoxes().isEmpty()
&& ke.isCharIgnoreCase('d')) {
detailMode = !detailMode;
- detailScroll = 0;
- cachedRouteDetail = null;
- cachedRouteDetailId = null;
- detailLoadingRouteId = null;
- detailLoading = false;
+ detail.reset();
return true;
}
@@ -217,11 +207,11 @@ class DiagramTab extends AbstractTab {
// Detail panel scroll
if (!topologyMode && detailMode && diagram.isShowDiagram()) {
if (ke.isPageUp() || ke.isKey(KeyCode.PAGE_UP)) {
- detailScroll = Math.max(0, detailScroll - 10);
+ detail.scrollBy(-10);
return true;
}
if (ke.isPageDown() || ke.isKey(KeyCode.PAGE_DOWN)) {
- detailScroll += 10;
+ detail.scrollBy(10);
return true;
}
}
@@ -233,10 +223,7 @@ class DiagramTab extends AbstractTab {
drillDownRouteId = null;
topologyMode = true;
detailMode = false;
- cachedRouteDetail = null;
- cachedRouteDetailId = null;
- detailLoadingRouteId = null;
- detailLoading = false;
+ detail.reset();
diagram.setTopologyMode(true);
diagram.setSelectedEipNodeIndex(-1);
diagram.resetScroll();
@@ -322,7 +309,6 @@ class DiagramTab extends AbstractTab {
}
return true;
}
-
return false;
}
@@ -331,13 +317,13 @@ class DiagramTab extends AbstractTab {
if (gotoNodePopup.isVisible()) {
return true;
}
- if (detailMode && lastDetailArea != null && lastDetailArea.contains(me.x(), me.y())) {
+ if (detailMode && detail.containsMouse(me.x(), me.y())) {
if (me.kind() == MouseEventKind.SCROLL_UP) {
- detailScroll = Math.max(0, detailScroll - 3);
+ detail.scrollBy(-3);
return true;
}
if (me.kind() == MouseEventKind.SCROLL_DOWN) {
- detailScroll += 3;
+ detail.scrollBy(3);
return true;
}
}
@@ -391,10 +377,7 @@ class DiagramTab extends AbstractTab {
diagram.setPendingSelectionRouteId(drillDownRouteId);
topologyMode = true;
detailMode = false;
- cachedRouteDetail = null;
- cachedRouteDetailId = null;
- detailLoadingRouteId = null;
- detailLoading = false;
+ detail.reset();
diagram.setTopologyMode(true);
diagram.setSelectedEipNodeIndex(-1);
diagram.resetScroll();
@@ -440,11 +423,7 @@ class DiagramTab extends AbstractTab {
drillDownRouteId = null;
routeNavigationStack.clear();
detailMode = false;
- cachedRouteDetail = null;
- cachedRouteDetailId = null;
- detailLoadingRouteId = null;
- detailLoading = false;
- lastDetailNodeId = null;
+ detail.reset();
diagram.reset();
diagram.setTopologyMode(true);
}
@@ -487,7 +466,7 @@ class DiagramTab extends AbstractTab {
.constraints(Constraint.length(infoPanelWidth), Constraint.fill())
.split(area);
hSplit.setBorderPos(hChunks.get(1).x());
- renderInfoPanel(frame, hChunks.get(0), info, selectedRouteId);
+ detail.renderRouteInfoPanel(frame, hChunks.get(0), info, selectedRouteId);
diagram.renderNativeDiagram(frame, hChunks.get(1), title, diagramMetrics);
} else {
diagram.renderNativeDiagram(frame, area, title, diagramMetrics);
@@ -495,7 +474,7 @@ class DiagramTab extends AbstractTab {
return;
} else if (!topologyMode && drillDownRouteId != null
&& diagram.getRouteLayout(drillDownRouteId) != null) {
- Line title = buildBreadcrumbTitle();
+ Line title = DiagramDetailSupport.buildBreadcrumbTitle(routeNavigationStack, drillDownRouteId);
var routeLayout = diagram.getRouteLayout(drillDownRouteId);
if (area.width() > 60) {
infoPanelWidth = Math.max(10, Math.min(infoPanelWidth, area.width() - 20));
@@ -503,7 +482,7 @@ class DiagramTab extends AbstractTab {
.constraints(Constraint.length(infoPanelWidth), Constraint.fill())
.split(area);
hSplit.setBorderPos(hChunks.get(1).x());
- renderEipInfoPanel(frame, hChunks.get(0));
+ detail.renderEipInfoPanel(frame, hChunks.get(0), drillDownRouteId);
if (detailMode) {
int detailH = Math.max(5, hChunks.get(1).height() * 60 / 100);
List<Rect> vChunks = Layout.vertical()
@@ -512,7 +491,7 @@ class DiagramTab extends AbstractTab {
vSplit.setBorderPos(vChunks.get(1).y());
diagram.renderNativeRouteDiagram(
frame, vChunks.get(0), title, diagramMetrics, drillDownRouteId, routeLayout);
- renderDetail(frame, vChunks.get(1), info);
+ detail.renderDetail(frame, vChunks.get(1), info, drillDownRouteId);
} else {
diagram.renderNativeRouteDiagram(
frame, hChunks.get(1), title, diagramMetrics, drillDownRouteId, routeLayout);
@@ -526,7 +505,7 @@ class DiagramTab extends AbstractTab {
vSplit.setBorderPos(vChunks.get(1).y());
diagram.renderNativeRouteDiagram(
frame, vChunks.get(0), title, diagramMetrics, drillDownRouteId, routeLayout);
- renderDetail(frame, vChunks.get(1), info);
+ detail.renderDetail(frame, vChunks.get(1), info, drillDownRouteId);
} else {
diagram.renderNativeRouteDiagram(
frame, area, title, diagramMetrics, drillDownRouteId, routeLayout);
@@ -553,285 +532,6 @@ class DiagramTab extends AbstractTab {
area);
}
- private void renderInfoPanel(Frame frame, Rect area, IntegrationInfo info, String routeId) {
- RouteInfo route = null;
- for (RouteInfo r : info.routes) {
- if (routeId.equals(r.routeId)) {
- route = r;
- break;
- }
- }
-
- List<Line> lines = new ArrayList<>();
- if (route != null) {
- lines.add(Line.from(
- Span.styled(" Route: ", Theme.muted()),
- Span.styled(route.routeId, Style.EMPTY.fg(Theme.baseFg()).bold())));
- lines.add(Line.from(
- Span.styled(" From: ", Theme.muted()),
- Span.raw(route.from != null ? route.from : "")));
- String stateLabel = route.state != null ? route.state : "";
- Style stateStyle = "Started".equals(route.state) ? Theme.success() : Theme.error();
- lines.add(Line.from(
- Span.styled(" State: ", Theme.muted()),
- Span.styled(stateLabel, stateStyle)));
-
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(" Uptime: ", Theme.muted()),
- Span.raw(route.uptime != null ? route.uptime : "")));
- String tpUnit = ctx.ratePerMinute ? " msg/m" : " msg/s";
- String tpValue = route.throughput != null
- ? (ctx.ratePerMinute ? TuiHelper.throughputPerMinute(route.throughput) : route.throughput)
- : "";
- lines.add(Line.from(
- Span.styled(" Rate: ", Theme.muted()),
- Span.raw(tpValue),
- Span.styled(tpUnit, Theme.muted())));
- if (route.coverage != null) {
- lines.add(Line.from(
- Span.styled(" Coverage: ", Theme.muted()),
- Span.raw(route.coverage)));
- }
-
- lines.add(Line.from(Span.raw("")));
- int w = numWidth(route.total, route.failed, route.inflight);
- lines.add(Line.from(
- Span.styled(" Total: ", Theme.muted()),
- Span.raw(String.format("%" + w + "d", route.total))));
- Style failStyle = route.failed > 0 ? Theme.error().bold() : Style.EMPTY;
- lines.add(Line.from(
- Span.styled(" Failed: ", Theme.muted()),
- Span.styled(String.format("%" + w + "d", route.failed), failStyle)));
- lines.add(Line.from(
- Span.styled(" Inflight: ", Theme.muted()),
- Span.raw(String.format("%" + w + "d", route.inflight))));
-
- lines.add(Line.from(Span.raw("")));
- if (route.total > 0) {
- lines.add(Line.from(
- Span.styled(" Mean: ", Theme.muted()),
- Span.raw(formatDurationMs(route.meanTime))));
- lines.add(Line.from(
- Span.styled(" Max: ", Theme.muted()),
- Span.raw(formatDurationMs(route.maxTime))));
- lines.add(Line.from(
- Span.styled(" Min: ", Theme.muted()),
- Span.raw(formatDurationMs(route.minTime))));
- if (route.p50Time >= 0) {
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(" p50: ", Theme.muted()),
- Span.raw(formatDurationMs(route.p50Time))));
- lines.add(Line.from(
- Span.styled(" p95: ", Theme.muted()),
- Span.raw(formatDurationMs(route.p95Time))));
- lines.add(Line.from(
- Span.styled(" p99: ", Theme.muted()),
- Span.raw(formatDurationMs(route.p99Time))));
- lines.add(buildPercentileBarLine(
- route.p50Time, route.p95Time, route.p99Time, area.width() - 3));
- }
- }
-
- if (route.sinceLastCompleted != null || route.sinceLastFailed != null) {
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(" Since last:", Theme.muted())));
- if (route.sinceLastCompleted != null) {
- lines.add(Line.from(
- Span.styled(" ok: ", Theme.muted()),
- Span.raw(route.sinceLastCompleted)));
- }
- if (route.sinceLastFailed != null) {
- lines.add(Line.from(
- Span.styled(" fail: ", Theme.muted()),
- Span.styled(route.sinceLastFailed,
- Theme.error())));
- }
- }
-
- } else {
- // External endpoint — show topology node data
- var topoNode = diagram.getSelectedTopologyNode();
- if (topoNode != null) {
- boolean isInbound = "external-in".equals(topoNode.nodeType);
- boolean isBridge = "external".equals(topoNode.nodeType);
- String label = isBridge ? " External" : isInbound ? " Inbound" : " Outbound";
- lines.add(Line.from(
- Span.styled(label, Style.EMPTY.fg(Theme.accent()).bold())));
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(" URI: ", Theme.muted()),
- Span.raw(topoNode.from != null ? topoNode.from : "")));
- if (topoNode.description != null && !topoNode.description.isBlank()) {
- lines.add(Line.from(
- Span.styled(" Path: ", Theme.muted()),
- Span.raw(topoNode.description)));
- }
- if (!isBridge) {
- String connectedRoute = diagram.getConnectedRouteId(routeId);
- if (connectedRoute != null) {
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(isInbound ? " To route: " : " From route: ", Theme.muted()),
- Span.styled(connectedRoute, Style.EMPTY.fg(Theme.baseFg()))));
- }
- }
- if (topoNode.exchangesTotal > 0 || topoNode.exchangesFailed > 0) {
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(" Total: ", Theme.muted()),
- Span.raw(String.valueOf(topoNode.exchangesTotal))));
- if (topoNode.exchangesFailed > 0) {
- lines.add(Line.from(
- Span.styled(" Failed: ", Theme.muted()),
- Span.styled(String.valueOf(topoNode.exchangesFailed),
- Theme.error().bold())));
- }
- }
- } else {
- lines.add(Line.from(
- Span.styled(" " + routeId, Style.EMPTY.fg(Theme.accent()).bold())));
- lines.add(Line.from(
- Span.styled(" (external endpoint)", Style.EMPTY.dim())));
- }
- }
-
- Paragraph paragraph = Paragraph.builder()
- .text(Text.from(lines))
- .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
- .title(" Info ").build())
- .build();
- frame.renderWidget(paragraph, area);
- }
-
- private void renderEipInfoPanel(Frame frame, Rect area) {
- List<Line> lines = new ArrayList<>();
- var selected = diagram.getSelectedEipNodeBox();
- if (selected != null && selected.layoutNode() != null) {
- var ln = selected.layoutNode();
-
- String typeLabel = ln.type != null ? ln.type : "unknown";
- Color eipColor = org.apache.camel.dsl.jbang.core.commands.tui.diagram.DiagramColors.getEipColor(typeLabel);
- lines.add(Line.from(
- Span.styled(" [" + typeLabel + "]", Style.EMPTY.fg(eipColor).bold())));
-
- String label = String.join("", ln.wrappedLines);
- if (!label.isBlank()) {
- lines.add(Line.from(
- Span.styled(" ", Style.EMPTY.dim()),
- Span.raw(label)));
- }
-
- if (ln.id != null) {
- lines.add(Line.from(
- Span.styled(" ID: ", Theme.muted()),
- Span.raw(ln.id)));
- }
-
- String linkedRoute = diagram.findLinkedRouteId(drillDownRouteId);
- if (linkedRoute != null && diagram.getRouteLayout(linkedRoute) != null) {
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(" ↵ ", Theme.label().bold()),
- Span.styled(linkedRoute, Style.EMPTY.fg(Theme.baseFg()))));
- } else if (ln.treeNode != null && ln.treeNode.info.remote) {
- lines.add(Line.from(Span.raw("")));
- String arrow = "from".equals(ln.type) ? " external → " : " → external";
- lines.add(Line.from(
- Span.styled(arrow, Theme.muted())));
- }
-
- if (ln.treeNode != null && ln.treeNode.info.stat != null) {
- var stat = ln.treeNode.info.stat;
- lines.add(Line.from(Span.raw("")));
- int w = numWidth(stat.exchangesTotal, stat.exchangesFailed, stat.exchangesInflight);
- lines.add(Line.from(
- Span.styled(" Total: ", Theme.muted()),
- Span.raw(String.format("%" + w + "d", stat.exchangesTotal))));
- Style failStyle = stat.exchangesFailed > 0
- ? Theme.error().bold() : Style.EMPTY;
- lines.add(Line.from(
- Span.styled(" Failed: ", Theme.muted()),
- Span.styled(String.format("%" + w + "d", stat.exchangesFailed), failStyle)));
- lines.add(Line.from(
- Span.styled(" Inflight: ", Theme.muted()),
- Span.raw(String.format("%" + w + "d", stat.exchangesInflight))));
- if (stat.exchangesThroughput != null && !stat.exchangesThroughput.isEmpty()) {
- String tpUnit = ctx.ratePerMinute ? " msg/m" : " msg/s";
- String tpValue = ctx.ratePerMinute
- ? TuiHelper.throughputPerMinute(stat.exchangesThroughput)
- : stat.exchangesThroughput;
- lines.add(Line.from(
- Span.styled(" Rate: ", Theme.muted()),
- Span.raw(tpValue),
- Span.styled(tpUnit, Theme.muted())));
- }
-
- if (stat.exchangesTotal > 0) {
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(" Mean: ", Theme.muted()),
- Span.raw(formatDurationMs(stat.meanProcessingTime))));
- lines.add(Line.from(
- Span.styled(" Max: ", Theme.muted()),
- Span.raw(formatDurationMs(stat.maxProcessingTime))));
- lines.add(Line.from(
- Span.styled(" Min: ", Theme.muted()),
- Span.raw(formatDurationMs(stat.minProcessingTime))));
- lines.add(Line.from(
- Span.styled(" Last: ", Theme.muted()),
- Span.raw(formatDurationMs(stat.lastProcessingTime))));
- if (stat.p50ProcessingTime >= 0) {
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(" p50: ", Theme.muted()),
- Span.raw(formatDurationMs(stat.p50ProcessingTime))));
- lines.add(Line.from(
- Span.styled(" p95: ", Theme.muted()),
- Span.raw(formatDurationMs(stat.p95ProcessingTime))));
- lines.add(Line.from(
- Span.styled(" p99: ", Theme.muted()),
- Span.raw(formatDurationMs(stat.p99ProcessingTime))));
- lines.add(buildPercentileBarLine(
- stat.p50ProcessingTime, stat.p95ProcessingTime,
- stat.p99ProcessingTime, area.width() - 3));
- }
-
- if (stat.lastCompletedExchangeTimestamp > 0 || stat.lastFailedExchangeTimestamp > 0) {
- long now = System.currentTimeMillis();
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(" Since last:", Theme.muted())));
- if (stat.lastCompletedExchangeTimestamp > 0) {
- long ago = now - stat.lastCompletedExchangeTimestamp;
- lines.add(Line.from(
- Span.styled(" ok: ", Theme.muted()),
- Span.raw(TimeUtils.printDuration(ago, false))));
- }
- if (stat.lastFailedExchangeTimestamp > 0) {
- long ago = now - stat.lastFailedExchangeTimestamp;
- lines.add(Line.from(
- Span.styled(" fail: ", Theme.muted()),
- Span.styled(TimeUtils.printDuration(ago, false),
- Theme.error())));
- }
- }
- }
- }
- } else {
- lines.add(Line.from(Span.styled(" (no node selected)", Style.EMPTY.dim())));
- }
-
- Paragraph paragraph = Paragraph.builder()
- .text(Text.from(lines))
- .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
- .title(" Info ").build())
- .build();
- frame.renderWidget(paragraph, area);
- }
-
@Override
public void renderFooter(List<Span> spans) {
if (sourceViewer.isVisible()) {
@@ -916,133 +616,7 @@ class DiagramTab extends AbstractTab {
@Override
public String getHelpText() {
- return """
- # Diagram
-
- The Diagram tab shows a visual topology of how routes connect to each other.
- This helps you understand the overall message flow in your integration.
-
- ## Topology View
-
- The topology view shows all routes and their connections:
- - **Trigger routes** (timer, cron, etc.) appear at the top
- - **Downstream routes** appear below, connected by arrows
- - Routes that are connected show edges between them
-
- ## Example Topology
-
- ```
- ┌──────────────────┐
- │ order-generator │
- │ (timer://gen) │
- │ │
- │ 3748 │
- └──────────────────┘
- │
- ▼
- ┌──────────────────┐
- │ process-order │
- │ (direct:process) │
- │ │
- │ 3748/12! │
- └──────────────────┘
- ```
-
- Each box represents a route. The first line is the route ID,
- the second line shows the `from` endpoint, and the bottom line
- shows metrics when enabled. Arrows show how routes connect.
-
- ## Metrics
-
- When metrics are enabled, each route box shows exchange counts:
- - **Green** number — successful exchanges
- - **Red** number — failed exchanges
- - Combined as `3748/12` means 3748 ok and 12 failed
-
- ## External Systems
-
- Press `e` to cycle through three external modes:
-
- - **off** — no external endpoints shown
- - **edges** — external endpoints that are truly outside Camel are shown
- as dashed boxes in top/bottom bands. Routes sharing an external
- endpoint (e.g. kafka) are connected with a direct arrow.
- - **all** — same as edges, but routes sharing an external endpoint
- are connected through an intermediary dashed box showing the
- endpoint name, instead of a direct arrow.
-
- External system boxes are drawn with dashed borders to distinguish
- them from route boxes. Dashed edges connect routes to external systems.
-
- ## Navigation
-
- In the topology view, use arrow keys to select route boxes:
- - `↑↓` moves between layers (upstream/downstream routes)
- - `←→` moves between routes in the same layer
-
- When a route is selected, an **Info panel** appears on the left
- showing key metrics: state, uptime, throughput, exchange counts,
- and processing times.
-
- Press `Enter` on a selected route to **drill down** into its
- internal EIP structure (the route diagram). Press `Esc` to
- return to the topology view.
-
- ## Route Diagram
-
- In the route diagram, each EIP node shows its type tag (colored)
- and endpoint URI or description. Nodes that connect to other routes
- display a `↵` indicator — press `Enter` to jump directly to the
- linked route's diagram.
-
- Navigation history is maintained as a stack: pressing `Esc` goes
- back to the previous route, and eventually back to the topology view.
-
- ## Route Structure Preview
-
- A compact tree structure preview appears in the bottom-right corner
- of the diagram area — like a minimap of the route's EIP structure.
-
- In **topology mode**, the preview shows the structure of the currently
- selected route and updates as you navigate between route boxes.
-
- In **drill-down mode**, the preview highlights the currently selected
- EIP node (shown in yellow) as you navigate with arrow keys, giving
- you an at-a-glance view of where you are in the route.
-
- ## Keys
-
- **Topology view:**
- - `↑↓←→` — navigate between route boxes
- - `Enter` — drill down into selected route
- - `c` — show route source code
- - `Esc` — close diagram
-
- **Route diagram:**
- - `↑↓←→` — navigate between EIP nodes
- - `Enter` — jump to linked route (when `↵` indicator shown)
- - `c` — show source code at selected node
- - `d` — toggle EIP detail panel (shows configured options)
- - `g` — go to node (fuzzy search popup)
- - `Esc` — go back (previous route or topology)
- - `t` — jump back to topology view
-
- **Source view:**
- - `↑↓` — move cursor between lines
- - `Ctrl+↑↓` — scroll viewport without moving cursor
- - `←→` — horizontal scroll
- - `PgUp/PgDn` — page jump
- - `Home/End` — go to top/bottom
- - `Enter` — select the closest diagram node at cursor line
- - `Esc/c` — close source view
-
- **Common:**
- - `m` — toggle metrics on/off (default: on)
- - `e` — toggle external systems on/off (topology only)
- - `n` — toggle description labels on/off
- - `PgUp/PgDn` — page scroll
- - `Home/End` — top/end
- """;
+ return DocHelper.loadHelpText("diagram");
}
@Override
@@ -1054,23 +628,6 @@ class DiagramTab extends AbstractTab {
return diagram.getTopologyDataAsJson();
}
- private Line buildBreadcrumbTitle() {
- Style nameStyle = Theme.label().bold();
- List<Span> spans = new ArrayList<>();
- spans.add(Span.raw(" Route ["));
- if (routeNavigationStack.isEmpty()) {
- spans.add(Span.styled(drillDownRouteId, nameStyle));
- } else {
- for (var it = routeNavigationStack.descendingIterator(); it.hasNext();) {
- spans.add(Span.styled(it.next(), nameStyle));
- spans.add(Span.raw(" → "));
- }
- spans.add(Span.styled(drillDownRouteId, nameStyle));
- }
- spans.add(Span.raw("] "));
- return Line.from(spans);
- }
-
private void loadSourceForSelectedTopologyRoute() {
String routeId = diagram.getSelectedRouteId();
if (routeId == null) {
@@ -1092,14 +649,14 @@ class DiagramTab extends AbstractTab {
if (diagram.getRouteLayout(routeId) == null) {
reloadDiagram();
}
- int bestIdx = findClosestEipNode(sourceLine);
+ int bestIdx = diagram.findClosestEipNode(sourceLine);
if (bestIdx >= 0) {
diagram.setSelectedEipNodeIndex(bestIdx);
diagram.scrollToSelectedEipNode();
}
});
- sourceViewer.setQuickDocProvider(this::provideAllQuickDocs);
- ensureProcessorDetailLoaded(routeId);
+ sourceViewer.setQuickDocProvider(detail::provideAllQuickDocs);
+ detail.ensureProcessorDetailLoaded(routeId);
var rl = diagram.getRouteLayout(routeId);
sourceViewer.loadSource(ctx, routeId, 0, rl != null ? rl.source : null);
}
@@ -1115,371 +672,21 @@ class DiagramTab extends AbstractTab {
targetLine = selected.layoutNode().treeNode.info.line;
}
sourceViewer.setOnLineSelected(sourceLine -> {
- int bestIdx = findClosestEipNode(sourceLine);
+ int bestIdx = diagram.findClosestEipNode(sourceLine);
if (bestIdx >= 0) {
diagram.setSelectedEipNodeIndex(bestIdx);
diagram.scrollToSelectedEipNode();
sourceViewer.hide();
}
});
- sourceViewer.setQuickDocProvider(this::provideAllQuickDocs);
- ensureProcessorDetailLoaded(drillDownRouteId);
+ sourceViewer.setQuickDocProvider(detail::provideAllQuickDocs);
+ detail.ensureProcessorDetailLoaded(drillDownRouteId);
var rl2 = diagram.getRouteLayout(drillDownRouteId);
sourceViewer.loadSource(ctx, drillDownRouteId, targetLine, rl2 != null ? rl2.source : null);
}
- private int findClosestEipNode(int sourceLine) {
- var boxes = diagram.getEipNodeBoxes();
- if (boxes.isEmpty()) {
- return -1;
- }
- int bestBeforeIdx = -1;
- int bestBeforeDist = Integer.MAX_VALUE;
- int bestAfterIdx = -1;
- int bestAfterDist = Integer.MAX_VALUE;
- for (int i = 0; i < boxes.size(); i++) {
- var box = boxes.get(i);
- if (box.layoutNode() == null || box.layoutNode().treeNode == null) {
- continue;
- }
- int nodeLine = box.layoutNode().treeNode.info.line;
- if (nodeLine <= 0) {
- continue;
- }
- if (nodeLine == sourceLine) {
- return i;
- }
- if (nodeLine < sourceLine) {
- int dist = sourceLine - nodeLine;
- if (dist < bestBeforeDist) {
- bestBeforeDist = dist;
- bestBeforeIdx = i;
- }
- } else {
- int dist = nodeLine - sourceLine;
- if (dist < bestAfterDist) {
- bestAfterDist = dist;
- bestAfterIdx = i;
- }
- }
- }
- return bestBeforeIdx >= 0 ? bestBeforeIdx : bestAfterIdx;
- }
-
- private void renderDetail(Frame frame, Rect area, IntegrationInfo info) {
- lastDetailArea = area;
- var selected = diagram.getSelectedEipNodeBox();
- if (selected == null || selected.layoutNode() == null) {
- frame.renderWidget(
- MarkdownView.builder()
- .source("*Select an EIP node*")
- .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
- .title(" EIP Detail ").build())
- .styles(Theme.markdownStyles())
- .build(),
- area);
- return;
- }
-
- String nodeId = selected.layoutNode().id;
- String eipType = selected.layoutNode().type;
- if (nodeId == null || eipType == null) {
- frame.renderWidget(
- MarkdownView.builder()
- .source("*No detail available*")
- .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
- .title(" EIP Detail ").build())
- .styles(Theme.markdownStyles())
- .build(),
- area);
- return;
- }
-
- // reset scroll when navigating to a different node
- if (!nodeId.equals(lastDetailNodeId)) {
- lastDetailNodeId = nodeId;
- detailScroll = 0;
- }
-
- // load route detail once (covers all routes and processors)
- if (drillDownRouteId != null && cachedRouteDetail == null
- && !"*".equals(detailLoadingRouteId)) {
- detailLoadingRouteId = "*";
- detailLoading = true;
- if (ctx.runner != null) {
- ctx.backgroundExecutor.execute(() -> {
- JsonObject result = requestRouteProcessorDetail("*");
- cachedRouteDetail = result;
- cachedRouteDetailId = "*";
- detailLoading = false;
- });
- }
- }
-
- // find the selected processor in the cached route data
- JsonObject processorEntry = findProcessorEntry(nodeId);
-
- StringBuilder md = new StringBuilder();
- CamelCatalog catalog = getCatalog(info);
-
- if (processorEntry != null) {
- String type = processorEntry.getString("type");
- String endpointUri = processorEntry.getString("endpointUri");
-
- if ("from".equals(type) && endpointUri != null && catalog != null) {
- renderEndpointDetail(md, catalog, endpointUri);
- } else if (type != null) {
- renderEipDetail(md, catalog, type, processorEntry.getMap("options"));
- } else {
- md.append("*No detail available*\n");
- }
- } else if (detailLoading) {
- md.append("*Loading...*\n");
- } else {
- md.append("*No detail available*\n");
- }
-
- String title = " " + eipType + " [" + nodeId + "] ";
- if (CharWidth.of(title) > area.width() - 4) {
- title = " " + CharWidth.truncateWithEllipsis(
- eipType + " [" + nodeId + "]", area.width() - 6, CharWidth.TruncatePosition.MIDDLE) + " ";
- }
-
- frame.renderWidget(
- MarkdownView.builder()
- .source(md.toString())
- .scroll(detailScroll)
- .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
- .title(title).build())
- .styles(Theme.markdownStyles())
- .build(),
- area);
- }
-
- private void renderEipDetail(StringBuilder md, CamelCatalog catalog, String type, JsonObject opts) {
- EipModel model = catalog != null ? catalog.eipModel(type) : null;
-
- if (model != null && model.getTitle() != null) {
- md.append("## ").append(model.getTitle()).append("\n\n");
- if (model.getDescription() != null && !model.getDescription().isEmpty()) {
- md.append(model.getDescription()).append("\n\n");
- }
- } else {
- md.append("## ").append(type).append("\n\n");
- }
-
- if (opts != null && !opts.isEmpty()) {
- Map<String, BaseOptionModel> optionDocs = new LinkedHashMap<>();
- if (model != null) {
- for (BaseOptionModel opt : model.getOptions()) {
- if (opt.getName() != null) {
- optionDocs.put(opt.getName(), opt);
- }
- }
- }
-
- for (Map.Entry<String, Object> entry : opts.entrySet()) {
- String optName = entry.getKey();
- String optValue = String.valueOf(entry.getValue());
- appendOptionDetail(md, optName, optValue, optionDocs.get(optName));
- }
- } else {
- md.append("*No configured options*\n");
- }
- }
-
- private void renderEndpointDetail(StringBuilder md, CamelCatalog catalog, String uri) {
- String component = uri.contains(":") ? uri.substring(0, uri.indexOf(':')) : uri;
- ComponentModel model = catalog.componentModel(component);
-
- if (model != null) {
- String compTitle = model.getTitle() != null ? model.getTitle() : component;
- md.append("## ").append(compTitle).append("\n\n");
- if (model.getDescription() != null && !model.getDescription().isEmpty()) {
- md.append(model.getDescription()).append("\n\n");
- }
-
- Map<String, String> parsedOptions;
- try {
- parsedOptions = catalog.endpointProperties(uri);
- } catch (URISyntaxException e) {
- parsedOptions = Map.of();
- }
-
- if (parsedOptions.isEmpty()) {
- md.append("*No configured options*\n");
- } else {
- Map<String, BaseOptionModel> optionDocs = new LinkedHashMap<>();
- for (ComponentModel.EndpointOptionModel opt : model.getEndpointOptions()) {
- if (opt.getName() != null) {
- optionDocs.put(opt.getName(), opt);
- }
- }
-
- for (Map.Entry<String, String> entry : parsedOptions.entrySet()) {
- appendOptionDetail(md, entry.getKey(), entry.getValue(), optionDocs.get(entry.getKey()));
- }
- }
- } else {
- md.append("## ").append(component).append("\n\n");
- md.append("*No catalog documentation for: ").append(component).append("*\n");
- }
- }
-
- private static void appendOptionDetail(StringBuilder md, String optName, String optValue, BaseOptionModel doc) {
- md.append("---\n\n");
- md.append("**").append(optName).append("** = **").append(optValue).append("**\n\n");
-
- if (doc != null) {
- if (doc.getDescription() != null && !doc.getDescription().isEmpty()) {
- md.append(doc.getDescription()).append("\n\n");
- }
- List<String> meta = new ArrayList<>();
- if (doc.getType() != null) {
- meta.add("Type: `" + doc.getType() + "`");
- }
- if (doc.getDefaultValue() != null) {
- meta.add("Default: `" + doc.getDefaultValue() + "`");
- }
- if (doc.isRequired()) {
- meta.add("Required: yes");
- }
- if (doc.getEnums() != null && !doc.getEnums().isEmpty()) {
- meta.add("Enum: " + String.join(", ", doc.getEnums()));
- }
- if (doc.getGroup() != null && !doc.getGroup().isEmpty()) {
- meta.add("Group: " + doc.getGroup());
- }
- if (doc.isDeprecated()) {
- String depText = "Deprecated";
- if (doc.getDeprecationNote() != null && !doc.getDeprecationNote().isEmpty()) {
- depText += " — " + doc.getDeprecationNote();
- }
- meta.add(depText);
- }
- if (!meta.isEmpty()) {
- for (String m : meta) {
- md.append("- ").append(m).append("\n");
- }
- md.append("\n");
- }
- }
- }
-
- private CamelCatalog getCatalog(IntegrationInfo info) {
- String version = info.camelVersion;
- if (version == null) {
- return null;
- }
- CamelCatalog cached = catalogCache.get(version);
- if (cached != null) {
- return cached;
- }
- if (catalogLoadFailed.contains(version)) {
- return null;
- }
- try {
- cached = CatalogLoader.loadCatalog(null, version, true);
- if (cached != null) {
- catalogCache.put(version, cached);
- } else {
- catalogLoadFailed.add(version);
- }
- return cached;
- } catch (Exception e) {
- catalogLoadFailed.add(version);
- return null;
- }
- }
-
- private JsonObject findProcessorEntry(String nodeId) {
- if (cachedRouteDetail == null || nodeId == null) {
- return null;
- }
- for (JsonObject p : RoutesTab.getAllProcessors(cachedRouteDetail)) {
- if (nodeId.equals(p.getString("id"))) {
- return p;
- }
- }
- return null;
- }
-
- private JsonObject requestRouteProcessorDetail(String routeId) {
- if (ctx.selectedPid == null) {
- return null;
- }
- try {
- JsonObject root = new JsonObject();
- root.put("action", "processor-detail");
- root.put("routeId", "*");
- return ctx.executeAction(ctx.selectedPid, root, 5000);
- } catch (Exception e) {
- return null;
- }
- }
-
// ---- Quick doc (i toggle in source viewer) ----
- private Map<Integer, List<SourceViewer.DocEntry>> provideAllQuickDocs(List<JsonObject> cd) {
- if (cachedRouteDetail == null || cd.isEmpty()) {
- return Map.of();
- }
-
- List<JsonObject> processors = RoutesTab.getAllProcessors(cachedRouteDetail);
- if (processors.isEmpty()) {
- return Map.of();
- }
-
- IntegrationInfo info = ctx.findSelectedIntegration();
- CamelCatalog catalog = info != null ? getCatalog(info) : null;
-
- Map<Integer, List<SourceViewer.DocEntry>> result = new LinkedHashMap<>();
- for (JsonObject proc : processors) {
- Integer line = proc.getInteger("line");
- if (line == null || line <= 0) {
- continue;
- }
-
- int eipIdx = RoutesTab.findCodeDataIndex(cd, line, -1);
- if (eipIdx < 0 || result.containsKey(eipIdx)) {
- continue;
- }
- String endpointUri = proc.getString("endpointUri");
- String type = proc.getString("type");
-
- if (endpointUri != null && catalog != null) {
- RoutesTab.buildEndpointInlineDoc(result, cd, catalog, endpointUri, eipIdx);
- } else if (type != null) {
- RoutesTab.buildEipInlineDoc(result, cd, catalog, type, proc.getMap("options"), eipIdx);
- }
- }
- return result;
- }
-
- private void ensureProcessorDetailLoaded(String routeId) {
- if (routeId != null && cachedRouteDetail == null
- && !"*".equals(detailLoadingRouteId)) {
- detailLoadingRouteId = "*";
- detailLoading = true;
- if (ctx.runner != null) {
- ctx.backgroundExecutor.execute(() -> {
- JsonObject result = requestRouteProcessorDetail("*");
- cachedRouteDetail = result;
- cachedRouteDetailId = "*";
- detailLoading = false;
- });
- }
- }
- }
-
- private static int numWidth(long... values) {
- long max = 0;
- for (long v : values) {
- max = Math.max(max, Math.abs(v));
- }
- return Math.max(1, String.valueOf(max).length());
- }
-
// ---- MCP programmatic navigation ----
boolean selectRoute(String routeId) {
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DocHelper.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DocHelper.java
index 823b94ae3a99..2e1c92174b78 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DocHelper.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DocHelper.java
@@ -24,14 +24,33 @@ import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
import org.apache.camel.dsl.jbang.core.common.ExampleHelper;
final class DocHelper {
+ private static final Map<String, String> HELP_CACHE = new ConcurrentHashMap<>();
+
private DocHelper() {
}
+ /**
+ * Loads the markdown help text for a tab from {@code tui/help/<name>.md} on the classpath. Results are cached;
+ * returns null when no help resource exists for the name.
+ */
+ static String loadHelpText(String name) {
+ String cached = HELP_CACHE.get(name);
+ if (cached == null) {
+ cached = loadResourceContent("tui/help/" + name + ".md");
+ if (cached != null) {
+ HELP_CACHE.put(name, cached);
+ }
+ }
+ return cached;
+ }
+
static String loadResourceContent(String resourcePath) {
try (InputStream is = ExampleHelper.class.getClassLoader().getResourceAsStream(resourcePath)) {
if (is != null) {
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/EipDocSupport.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/EipDocSupport.java
new file mode 100644
index 000000000000..0372937f204b
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/EipDocSupport.java
@@ -0,0 +1,507 @@
+/*
+ * 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.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.camel.catalog.CamelCatalog;
+import org.apache.camel.tooling.model.BaseOptionModel;
+import org.apache.camel.tooling.model.ComponentModel;
+import org.apache.camel.tooling.model.EipModel;
+import org.apache.camel.util.json.JsonArray;
+import org.apache.camel.util.json.JsonObject;
+
+/**
+ * Stateless helpers that turn catalog metadata (EIP and component models) into markdown detail text and inline
+ * quick-doc entries for the source viewer.
+ * <p>
+ * Shared by {@link RoutesTab}, {@link DiagramTab} and {@link SourceTab}.
+ */
+final class EipDocSupport {
+
+ private EipDocSupport() {
+ }
+
+ static List<JsonObject> getAllProcessors(JsonObject routeDetail) {
+ if (routeDetail == null) {
+ return List.of();
+ }
+ JsonArray routes = (JsonArray) routeDetail.get("routes");
+ if (routes != null) {
+ List<JsonObject> all = new ArrayList<>();
+ for (Object obj : routes) {
+ JsonObject route = (JsonObject) obj;
+ JsonArray procs = (JsonArray) route.get("processors");
+ if (procs != null) {
+ for (Object p : procs) {
+ all.add((JsonObject) p);
+ }
+ }
+ }
+ return all;
+ }
+ JsonArray procs = (JsonArray) routeDetail.get("processors");
+ if (procs != null) {
+ List<JsonObject> all = new ArrayList<>();
+ for (Object p : procs) {
+ all.add((JsonObject) p);
+ }
+ return all;
+ }
+ return List.of();
+ }
+
+ static void buildEndpointInlineDoc(
+ Map<Integer, List<SourceViewer.DocEntry>> result, List<JsonObject> cd,
+ CamelCatalog catalog, String endpointUri, int eipIdx) {
+
+ String component = endpointUri.contains(":") ? endpointUri.substring(0, endpointUri.indexOf(':')) : endpointUri;
+ ComponentModel model = catalog.componentModel(component);
+ if (model == null) {
+ return;
+ }
+
+ String compTitle = model.getTitle() != null ? model.getTitle() : component;
+ String desc = model.getDescription() != null ? truncateText(model.getDescription(), 80) : "";
+
+ Map<String, BaseOptionModel> optionDocs = new LinkedHashMap<>();
+ for (ComponentModel.EndpointOptionModel opt : model.getEndpointOptions()) {
+ if (opt.getName() != null) {
+ optionDocs.put(opt.getName(), opt);
+ }
+ }
+
+ int beforeSize = result.size();
+ List<SourceViewer.DocEntry> titleLines = new ArrayList<>();
+ titleLines.add(SourceViewer.DocEntry.of(compTitle + " — " + desc));
+ result.put(eipIdx, titleLines);
+
+ inlineParameterDocs(result, cd, eipIdx, optionDocs);
+
+ // For Java/XML where params are in the URI (not on separate source lines),
+ // cluster the option docs under the title
+ if (result.size() == beforeSize + 1) {
+ clusterEndpointOptions(titleLines, catalog, endpointUri, optionDocs);
+ }
+ }
+
+ private static void clusterEndpointOptions(
+ List<SourceViewer.DocEntry> docLines, CamelCatalog catalog,
+ String endpointUri, Map<String, BaseOptionModel> optionDocs) {
+ try {
+ Map<String, String> props = catalog.endpointProperties(endpointUri);
+ if (props != null) {
+ for (Map.Entry<String, String> entry : props.entrySet()) {
+ BaseOptionModel optModel = optionDocs.get(entry.getKey());
+ if (optModel != null) {
+ String optDoc = formatOptionDoc(optModel);
+ if (optDoc != null) {
+ String text = entry.getKey() + ": " + entry.getValue() + " — " + optDoc;
+ docLines.add(optModel.isDeprecated()
+ ? SourceViewer.DocEntry.deprecated(text)
+ : SourceViewer.DocEntry.of(text));
+ }
+ }
+ }
+ }
+ } catch (Exception e) {
+ // ignore URI parse errors
+ }
+ }
+
+ static void buildEipInlineDoc(
+ Map<Integer, List<SourceViewer.DocEntry>> result, List<JsonObject> cd,
+ CamelCatalog catalog, String type, JsonObject opts, int eipIdx) {
+
+ EipModel model = catalog != null ? catalog.eipModel(type) : null;
+
+ // For endpoint-bearing EIPs, resolve the component from the uri option
+ ComponentModel compModel = null;
+ if (opts != null && catalog != null) {
+ Object uriObj = opts.get("uri");
+ if (uriObj != null) {
+ String uri = uriObj.toString();
+ String comp = uri.contains(":") ? uri.substring(0, uri.indexOf(':')) : uri;
+ compModel = catalog.componentModel(comp);
+ }
+ }
+
+ List<SourceViewer.DocEntry> titleLines = new ArrayList<>();
+ if (model != null && model.getTitle() != null) {
+ String eipTitle = model.getTitle();
+ if (compModel != null && compModel.getTitle() != null) {
+ eipTitle += " (" + compModel.getTitle() + ")";
+ }
+ String desc;
+ if (compModel != null && compModel.getDescription() != null) {
+ desc = truncateText(compModel.getDescription(), 80);
+ } else {
+ desc = model.getDescription() != null ? truncateText(model.getDescription(), 80) : "";
+ }
+ titleLines.add(SourceViewer.DocEntry.of(eipTitle + " — " + desc));
+ } else {
+ titleLines.add(SourceViewer.DocEntry.of(type));
+ }
+
+ int beforeSize = result.size();
+ result.put(eipIdx, titleLines);
+
+ if (model != null) {
+ Map<String, BaseOptionModel> optionDocs = new LinkedHashMap<>();
+ for (BaseOptionModel opt : model.getOptions()) {
+ if (opt.getName() != null) {
+ optionDocs.put(opt.getName(), opt);
+ }
+ }
+ if (compModel != null) {
+ for (ComponentModel.EndpointOptionModel opt : compModel.getEndpointOptions()) {
+ if (opt.getName() != null && !optionDocs.containsKey(opt.getName())) {
+ optionDocs.put(opt.getName(), opt);
+ }
+ }
+ }
+ inlineParameterDocs(result, cd, eipIdx, optionDocs);
+
+ // For Java/XML where options are on the same line,
+ // cluster the option docs under the title
+ if (result.size() == beforeSize + 1 && opts != null) {
+ boolean hasParams = hasParametersChild(cd, eipIdx);
+ clusterEipOptions(titleLines, opts, optionDocs, hasParams);
+ }
+ }
+ }
+
+ private static void clusterEipOptions(
+ List<SourceViewer.DocEntry> docLines, JsonObject opts,
+ Map<String, BaseOptionModel> optionDocs, boolean skipUri) {
+ for (Map.Entry<String, Object> entry : opts.entrySet()) {
+ if (skipUri && "uri".equals(entry.getKey())) {
+ continue;
+ }
+ BaseOptionModel optModel = optionDocs.get(entry.getKey());
+ if (optModel != null) {
+ String optDoc = formatOptionDoc(optModel);
+ if (optDoc != null) {
+ String text = entry.getKey() + ": " + entry.getValue() + " — " + optDoc;
+ docLines.add(optModel.isDeprecated()
+ ? SourceViewer.DocEntry.deprecated(text)
+ : SourceViewer.DocEntry.of(text));
+ }
+ }
+ }
+ }
+
+ static boolean hasParametersChild(List<JsonObject> cd, int eipIdx) {
+ int eipIndent = lineIndent(cd, eipIdx);
+ for (int i = eipIdx + 1; i < cd.size(); i++) {
+ String code = cd.get(i).get("code") != null ? cd.get(i).get("code").toString() : "";
+ int indent = leadingSpaces(code);
+ if (indent < eipIndent && !code.isBlank()) {
+ break;
+ }
+ String trimmed = code.stripLeading();
+ if (trimmed.startsWith("parameters:")) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ static void inlineParameterDocs(
+ Map<Integer, List<SourceViewer.DocEntry>> result, List<JsonObject> cd,
+ int eipIdx, Map<String, BaseOptionModel> optionDocs) {
+
+ if (optionDocs.isEmpty()) {
+ return;
+ }
+
+ int eipIndent = lineIndent(cd, eipIdx);
+ int childIndent = -1;
+ boolean inParameters = false;
+ int paramIndent = -1;
+ int parametersLineIndent = -1;
+
+ for (int i = eipIdx + 1; i < cd.size(); i++) {
+ String code = cd.get(i).get("code") != null ? cd.get(i).get("code").toString() : "";
+ int indent = leadingSpaces(code);
+ if (indent < eipIndent && !code.isBlank()) {
+ break;
+ }
+ if (childIndent < 0 && indent > eipIndent) {
+ childIndent = indent;
+ }
+
+ if (inParameters) {
+ if (paramIndent < 0 && indent > parametersLineIndent && !code.isBlank()) {
+ paramIndent = indent;
+ }
+ if (paramIndent > 0 && indent <= parametersLineIndent && !code.isBlank()) {
+ inParameters = false;
+ paramIndent = -1;
+ parametersLineIndent = -1;
+ } else if (paramIndent > 0 && indent == paramIndent) {
+ String trimmed = code.stripLeading();
+ int colon = trimmed.indexOf(':');
+ if (colon > 0) {
+ String key = trimmed.substring(0, colon).strip();
+ BaseOptionModel doc = optionDocs.get(key);
+ if (doc != null) {
+ String docLine = formatOptionDoc(doc);
+ if (docLine != null) {
+ int docIdx = lastContinuationLine(cd, i, indent);
+ result.put(docIdx, List.of(doc.isDeprecated()
+ ? SourceViewer.DocEntry.deprecated(docLine)
+ : SourceViewer.DocEntry.of(docLine)));
+ }
+ }
+ }
+ continue;
+ } else {
+ continue;
+ }
+ }
+
+ if (childIndent > 0 && indent != childIndent) {
+ continue;
+ }
+ String trimmed = code.stripLeading();
+ int colon = trimmed.indexOf(':');
+ if (colon <= 0) {
+ continue;
+ }
+ String key = trimmed.substring(0, colon).strip();
+ if ("parameters".equals(key)) {
+ inParameters = true;
+ parametersLineIndent = indent;
+ continue;
+ }
+ if ("uri".equals(key) || "steps".equals(key)
+ || "id".equals(key) || "description".equals(key)) {
+ continue;
+ }
+
+ BaseOptionModel doc = optionDocs.get(key);
+ if (doc != null) {
+ String docLine = formatOptionDoc(doc);
+ if (docLine != null) {
+ int docIdx = lastContinuationLine(cd, i, indent);
+ result.put(docIdx, List.of(doc.isDeprecated()
+ ? SourceViewer.DocEntry.deprecated(docLine)
+ : SourceViewer.DocEntry.of(docLine)));
+ }
+ }
+ }
+ }
+
+ static int lastContinuationLine(List<JsonObject> cd, int keyIdx, int keyIndent) {
+ int last = keyIdx;
+ for (int j = keyIdx + 1; j < cd.size(); j++) {
+ String c = cd.get(j).get("code") != null ? cd.get(j).get("code").toString() : "";
+ if (c.isBlank()) {
+ continue;
+ }
+ if (leadingSpaces(c) > keyIndent) {
+ last = j;
+ } else {
+ break;
+ }
+ }
+ return last;
+ }
+
+ static String formatOptionDoc(BaseOptionModel doc) {
+ StringBuilder sb = new StringBuilder();
+ if (doc.getDescription() != null && !doc.getDescription().isEmpty()) {
+ sb.append(truncateText(doc.getDescription(), 80));
+ }
+ List<String> meta = new ArrayList<>();
+ if (doc.getType() != null) {
+ meta.add(doc.getType());
+ }
+ if (doc.isRequired()) {
+ meta.add("required");
+ }
+ if (doc.getDefaultValue() != null) {
+ meta.add("default: " + doc.getDefaultValue());
+ }
+ if (!meta.isEmpty()) {
+ if (!sb.isEmpty()) {
+ sb.append(" ");
+ }
+ sb.append("(").append(String.join(", ", meta)).append(")");
+ }
+ return !sb.isEmpty() ? sb.toString() : null;
+ }
+
+ static int lineIndent(List<JsonObject> cd, int idx) {
+ if (idx < 0 || idx >= cd.size()) {
+ return 0;
+ }
+ String code = cd.get(idx).get("code") != null ? cd.get(idx).get("code").toString() : "";
+ return leadingSpaces(code);
+ }
+
+ static int leadingSpaces(String s) {
+ int count = 0;
+ for (int i = 0; i < s.length(); i++) {
+ if (s.charAt(i) == ' ') {
+ count++;
+ } else {
+ break;
+ }
+ }
+ return count;
+ }
+
+ static int findCodeDataIndex(List<JsonObject> cd, int targetLine, int fallback) {
+ for (int i = 0; i < cd.size(); i++) {
+ Integer lineNum = cd.get(i).getInteger("line");
+ if (lineNum != null && lineNum == targetLine) {
+ return i;
+ }
+ }
+ return Math.max(0, fallback);
+ }
+
+ static String truncateText(String text, int maxLen) {
+ if (text == null) {
+ return "";
+ }
+ int dot = text.indexOf('.');
+ if (dot > 0 && dot < maxLen) {
+ return text.substring(0, dot + 1);
+ }
+ if (text.length() <= maxLen) {
+ return text;
+ }
+ return text.substring(0, maxLen - 3) + "...";
+ }
+
+ private static void appendOptionDetail(StringBuilder md, String optName, String optValue, BaseOptionModel doc) {
+ md.append("---\n\n");
+ md.append("**").append(optName).append("** = **").append(optValue).append("**\n\n");
+
+ if (doc != null) {
+ if (doc.getDescription() != null && !doc.getDescription().isEmpty()) {
+ md.append(doc.getDescription()).append("\n\n");
+ }
+ List<String> meta = new ArrayList<>();
+ if (doc.getType() != null) {
+ meta.add("Type: `" + doc.getType() + "`");
+ }
+ if (doc.getDefaultValue() != null) {
+ meta.add("Default: `" + doc.getDefaultValue() + "`");
+ }
+ if (doc.isRequired()) {
+ meta.add("Required: yes");
+ }
+ if (doc.getEnums() != null && !doc.getEnums().isEmpty()) {
+ meta.add("Enum: " + String.join(", ", doc.getEnums()));
+ }
+ if (doc.getGroup() != null && !doc.getGroup().isEmpty()) {
+ meta.add("Group: " + doc.getGroup());
+ }
+ if (doc.isDeprecated()) {
+ String depText = "Deprecated";
+ if (doc.getDeprecationNote() != null && !doc.getDeprecationNote().isEmpty()) {
+ depText += " — " + doc.getDeprecationNote();
+ }
+ meta.add(depText);
+ }
+ if (!meta.isEmpty()) {
+ for (String m : meta) {
+ md.append("- ").append(m).append("\n");
+ }
+ md.append("\n");
+ }
+ }
+ }
+
+ static void renderEipDetail(StringBuilder md, CamelCatalog catalog, String type, JsonObject opts) {
+ EipModel model = catalog != null ? catalog.eipModel(type) : null;
+
+ if (model != null && model.getTitle() != null) {
+ md.append("## ").append(model.getTitle()).append("\n\n");
+ if (model.getDescription() != null && !model.getDescription().isEmpty()) {
+ md.append(model.getDescription()).append("\n\n");
+ }
+ } else {
+ md.append("## ").append(type).append("\n\n");
+ }
+
+ if (opts != null && !opts.isEmpty()) {
+ Map<String, BaseOptionModel> optionDocs = new LinkedHashMap<>();
+ if (model != null) {
+ for (BaseOptionModel opt : model.getOptions()) {
+ if (opt.getName() != null) {
+ optionDocs.put(opt.getName(), opt);
+ }
+ }
+ }
+
+ for (Map.Entry<String, Object> entry : opts.entrySet()) {
+ String optName = entry.getKey();
+ String optValue = String.valueOf(entry.getValue());
+ appendOptionDetail(md, optName, optValue, optionDocs.get(optName));
+ }
+ } else {
+ md.append("*No configured options*\n");
+ }
+ }
+
+ static void renderEndpointDetail(StringBuilder md, CamelCatalog catalog, String uri) {
+ String component = uri.contains(":") ? uri.substring(0, uri.indexOf(':')) : uri;
+ ComponentModel model = catalog.componentModel(component);
+
+ if (model != null) {
+ String compTitle = model.getTitle() != null ? model.getTitle() : component;
+ md.append("## ").append(compTitle).append("\n\n");
+ if (model.getDescription() != null && !model.getDescription().isEmpty()) {
+ md.append(model.getDescription()).append("\n\n");
+ }
+
+ Map<String, String> parsedOptions;
+ try {
+ parsedOptions = catalog.endpointProperties(uri);
+ } catch (URISyntaxException e) {
+ parsedOptions = Map.of();
+ }
+
+ if (parsedOptions.isEmpty()) {
+ md.append("*No configured options*\n");
+ } else {
+ Map<String, BaseOptionModel> optionDocs = new LinkedHashMap<>();
+ for (ComponentModel.EndpointOptionModel opt : model.getEndpointOptions()) {
+ if (opt.getName() != null) {
+ optionDocs.put(opt.getName(), opt);
+ }
+ }
+
+ for (Map.Entry<String, String> entry : parsedOptions.entrySet()) {
+ appendOptionDetail(md, entry.getKey(), entry.getValue(), optionDocs.get(entry.getKey()));
+ }
+ }
+ } else {
+ md.append("## ").append(component).append("\n\n");
+ md.append("*No catalog documentation for: ").append(component).append("*\n");
+ }
+ }
+}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/EndpointsTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/EndpointsTab.java
index 6fb44bcc993d..997980952706 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/EndpointsTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/EndpointsTab.java
@@ -18,13 +18,10 @@ package org.apache.camel.dsl.jbang.core.commands.tui;
import java.net.URISyntaxException;
import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
-import java.util.Set;
import dev.tamboui.layout.Constraint;
import dev.tamboui.layout.Layout;
@@ -47,7 +44,6 @@ import dev.tamboui.widgets.table.Cell;
import dev.tamboui.widgets.table.Row;
import dev.tamboui.widgets.table.Table;
import org.apache.camel.catalog.CamelCatalog;
-import org.apache.camel.dsl.jbang.core.common.CatalogLoader;
import org.apache.camel.tooling.model.BaseOptionModel;
import org.apache.camel.tooling.model.ComponentModel;
import org.apache.camel.util.json.JsonArray;
@@ -89,8 +85,7 @@ class EndpointsTab extends AbstractTableTab {
private int flowPanelWidth = 38;
private final DragSplit hSplit = new DragSplit();
- private final Map<String, CamelCatalog> catalogCache = new HashMap<>();
- private final Set<String> catalogLoadFailed = new HashSet<>();
+ private final CatalogCache catalogCache = new CatalogCache();
EndpointsTab(MonitorContext ctx, MetricsCollector metrics) {
super(ctx, "component", "route", "dir", "total", "body", "hdr", "uri");
@@ -693,29 +688,7 @@ class EndpointsTab extends AbstractTableTab {
}
private CamelCatalog getCatalog(IntegrationInfo info) {
- String version = info.camelVersion;
- if (version == null) {
- return null;
- }
- CamelCatalog cached = catalogCache.get(version);
- if (cached != null) {
- return cached;
- }
- if (catalogLoadFailed.contains(version)) {
- return null;
- }
- try {
- cached = CatalogLoader.loadCatalog(null, version, true);
- if (cached != null) {
- catalogCache.put(version, cached);
- } else {
- catalogLoadFailed.add(version);
- }
- return cached;
- } catch (Exception e) {
- catalogLoadFailed.add(version);
- return null;
- }
+ return catalogCache.get(info);
}
@Override
@@ -751,107 +724,7 @@ class EndpointsTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Endpoints
-
- Endpoints are the addresses that messages flow to and from. Every Camel
- component (kafka, http, file, log, etc.) provides endpoints that routes
- use to receive and send data. An endpoint URI like `kafka://my-topic`
- identifies both the component and the specific resource.
-
- ## Table Columns
-
- - **COMPONENT** — The Camel component name (e.g., `kafka`, `http`, `file`, `log`, `seda`). This is the scheme part of the endpoint URI
- - **ROUTE** — Which route uses this endpoint
- - **DIR** — Direction of message flow: `in` (consuming/receiving from this endpoint), `out` (producing/sending to this endpoint), or `both` (used in both directions)
- - **TOTAL** — Hit count: how many times a message has passed through this endpoint in the given direction
- - **BODY** — Average message body size in bytes passing through this endpoint. Helps identify which endpoints handle large payloads
- - **HDR** — Average message headers size in bytes. Large headers may indicate excessive metadata being passed
- - **STUB** — Marked `x` if the endpoint has been replaced by a stub component (useful during testing to avoid connecting to real external systems)
- - **REMOTE** — Marked `x` if the endpoint connects to an external system outside the JVM (e.g., `kafka`, `http`, `ftp`). Local endpoints like `seda`, `direct`, `log` are not remote
- - **URI** — Full endpoint URI with parameters (e.g., `timer://hello?period=2000`)
-
- ## Example Screen
-
- ```
- COMPONENT ROUTE DIR TOTAL BODY HDR STUB REMOTE URI
- timer timer-to-log in 21 0 0 timer://hello?period=2000
- timer timer-to-seda in 14 0 0 timer://pump?period=3000
- seda seda-consumer in 14 14 0 seda://queue
- seda timer-to-seda out 14 14 0 seda://queue
- ```
-
- Notice that `seda://queue` appears twice — once as `in` (the
- `seda-consumer` route reads from it) and once as `out` (the
- `timer-to-seda` route writes to it). The BODY column shows 14
- bytes for seda because the message `Pumped message` is 14 bytes.
-
- ## Flow Chart
-
- The top-left panel shows a visual flow of messages through the
- integration:
-
- ```
- ┌─────────┐ ┌──────────┐
- │ kafka │ ──▸ [integration] ──▸ │ http │
- │ file │ │ log │
- └─────────┘ └──────────┘
- inbound outbound
- ```
-
- The left box lists all inbound components (consumers), the right
- box lists all outbound components (producers). The integration
- name sits in the middle, showing the overall message flow direction.
-
- ## Throughput Chart
-
- A mirrored sparkline chart shows message rates over time:
-
- - **Top half (green)**: inbound messages per second
- - **Bottom half (cyan)**: outbound messages per second
-
- This helps you see if input and output rates are balanced. If
- inbound consistently exceeds outbound, messages may be queuing up.
-
- ## Payload Size Chart
-
- When message size tracking is available, a separate chart shows
- body sizes over time. Sudden increases in message size may indicate
- unexpected large payloads that could cause memory pressure.
-
- ## Filter Modes
-
- Use `f` to cycle between filter modes:
- - **all** — show all endpoints
- - **remote** — show only remote endpoints (external connections)
- - **stub** — show only stubbed endpoints
-
- ## Endpoint Documentation
-
- Press `d` to toggle the documentation panel. When enabled, the
- bottom panel shows detailed documentation for the selected endpoint's
- configured options — parsed from the endpoint URI and looked up in
- the Camel catalog matching the integration's Camel version.
-
- For each configured option you'll see:
- - **Name** and **current value** (highlighted)
- - **Description** — what the option does
- - **Type** — the expected value type
- - **Default** — the default value if not set
- - **Enum values** — valid choices for enum options
- - **Group** — whether it's a common, consumer, producer, or advanced option
-
- Use `PgUp/PgDn` to scroll the documentation panel.
-
- ## Keys
-
- - `Up/Down` — select endpoint
- - `s` — cycle sort column
- - `S` — reverse sort order
- - `f` — cycle filter mode
- - `d` — toggle endpoint documentation panel
- - `PgUp/PgDn` — scroll documentation (when doc panel is open)
- """;
+ return DocHelper.loadHelpText("endpoints");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ErrorsTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ErrorsTab.java
index d46270942355..ecb0850e3be3 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ErrorsTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ErrorsTab.java
@@ -776,130 +776,7 @@ class ErrorsTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Errors
-
- The Errors tab shows exchanges that have failed with exceptions. This is
- your primary tool for debugging integration problems — it captures the
- exception, the exchange state at the time of failure, and the full path
- the message took through the route before it failed.
-
- Camel maintains an error registry that keeps the most recent errors
- (up to a configurable limit). Older errors are automatically purged.
-
- ## Error List
-
- - **ID** — Exchange identifier (e.g., `ID-myhost-1234-5`). This uniquely identifies the message that failed
- - **AGO** — How long ago the error occurred (e.g., `5s`, `2m`, `1h`). Recent errors appear first by default
- - **ROUTE** — Route where the error happened
- - **NODE** — The specific processor/node in the route where the exception was thrown (e.g., `to1`, `bean2`, `process3`). This tells you exactly which step failed
- - **HANDLED** — Whether the error was caught by Camel's error handling: `true` (handled) or `false` (unhandled)
- - **EXCEPTION** — Exception class name in short form (e.g., `IOException`, `HttpOperationFailedException`)
- - **MESSAGE** — The exception message text explaining what went wrong
-
- ## Example Screen
-
- ```
- ID AGO ROUTE NODE HANDLED EXCEPTION MESSAGE
- ID-myhost-1234-5 5s timer-route to1 false IOException Connection refused
- ID-myhost-1234-3 2m kafka-route bean2 true NPE null reference in processor
- ```
-
- ## Understanding HANDLED
-
- - **handled=true**: The error was caught by Camel's error handling
- mechanism. This includes:
- - `onException` blocks that handle specific exception types
- - `errorHandler` configured on the route or context
- - `deadLetterChannel` that redirects failed messages to an error queue
- - `doTry/doCatch` blocks in the route
-
- The route continued executing (or the message was redirected),
- so the caller may not even know an error occurred.
-
- - **handled=false**: The error was not caught by any error handler.
- The exchange failed completely and the exception propagated back to
- the caller. For a consumer like Kafka, this might trigger a message
- redelivery. For an HTTP endpoint, the caller gets a 500 error.
-
- ## Detail View
-
- Press `Enter` on an error to see the full details:
-
- - **Stack trace**: Complete Java exception chain showing exactly where
- in the code the error occurred. Look for your own classes and Camel
- component classes — framework internals can usually be skipped
- - **Message History**: Step-by-step trace showing every node the
- exchange visited before failing. This is invaluable for understanding
- the path the message took:
-
- ```
- RouteId ProcessorId Processor Elapsed
- my-route from1 timer://tick 0ms
- my-route setBody1 setBody 0ms
- my-route to1 http://api 5023ms <-- failed here
- ```
-
- The last entry is where the failure occurred. The elapsed time for
- that step often reveals the problem (e.g., 5023ms suggests a
- connection timeout).
-
- - **Headers**: Exchange message headers at the time of failure
- - **Body**: Message body content
- - **Properties**: Exchange-level properties
- - **Variables**: Exchange variables
-
- Use `h`, `b`, `p`, `v` keys to toggle each section.
-
- ## Common Error Patterns
-
- - **Connection refused / timeout**: Downstream service is down or
- unreachable. Check network and service status.
- - **HttpOperationFailedException**: HTTP call returned an error
- status code. Check the response body for details.
- - **TypeConversionException**: Camel cannot convert a message to the
- required type. Check message format and data types.
- - **NullPointerException**: A processor received unexpected null data.
- Check if the message body or headers are populated correctly.
-
- ## Error Diagram
-
- Press `d` in the detail view to open a visual route diagram showing
- the path the failed exchange took through the route. Visited nodes are
- highlighted in red to trace the error path.
-
- Use `Up/Down` arrow keys to step through the visited nodes one by one —
- the diagram progressively highlights each step in order, showing exactly
- how the exchange flowed through the route before failing. The current
- step is shown with a selection highlight. Use `Left/Right` to scroll
- the diagram horizontally if it extends beyond the screen.
-
- **Info Panel** — An info panel on the left side of the diagram shows
- metadata for the selected error: exchange ID, route, node, elapsed
- time, thread, handled status, and the full exception. It also shows
- body, headers, properties, and variables respecting the `b/h/p/v`
- toggles. Press `i` to cycle the panel size: narrow (35 chars),
- wide (half screen), or full (entire area). In wide mode, the minimap
- and tree preview are hidden. Word wrap (`w`) is also supported.
-
- Press `d` to close the diagram and return to the detail view.
- Press `Esc` to navigate back one route in drill-down mode.
-
- ## Keys
-
- - `Up/Down` — select error (list) / navigate path steps (diagram)
- - `Enter` — view error details
- - `d` — toggle error diagram (open and close)
- - `Esc` — back to list / back one route in diagram drill-down
- - `i` — cycle info panel size (narrow / wide / full) in diagram
- - `h` — toggle headers
- - `b` — toggle body
- - `p` — toggle properties
- - `v` — toggle variables
- - `w` — toggle word wrap
- - `s` — cycle sort column
- - `S` — reverse sort order
- """;
+ return DocHelper.loadHelpText("errors");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/EventTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/EventTab.java
index 0a9ad6be45cc..d609b289dae4 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/EventTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/EventTab.java
@@ -171,34 +171,7 @@ class EventTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Events
-
- Shows Camel lifecycle events captured by the event notifier. Events are
- grouped into three categories:
-
- - **general** — Context-level events: CamelContext starting/started/stopping,
- service add/remove, component add/remove
- - **route** — Route lifecycle events: route added/removed/started/stopped/reloaded
- - **exchange** — Exchange events: exchange created/completed/failed/sending/sent
-
- Events are stored in a circular buffer (default capacity 25 per category).
- Only the most recent events are shown.
-
- ## Table Columns
-
- - **AGO** — How long ago the event occurred (e.g., `2s`, `1m30s`)
- - **CATEGORY** — Event category: `general`, `route`, or `exchange`
- - **TYPE** — The specific event type (e.g., `CamelContextStartedEvent`,
- `RouteStartedEvent`, `ExchangeCompletedEvent`)
- - **MESSAGE** — Human-readable event description
-
- ## Keys
-
- - `Up/Down` — select event
- - `s` — cycle sort column
- - `S` — reverse sort order
- """;
+ return DocHelper.loadHelpText("event");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/GotoSourceNodePopup.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/GotoSourceNodePopup.java
index 2273963ed493..059790d2edfb 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/GotoSourceNodePopup.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/GotoSourceNodePopup.java
@@ -213,7 +213,7 @@ class GotoSourceNodePopup {
String prefix = buildTreePrefix(filteredEntries, idx, entry);
spans.add(Span.styled(prefix, treeStyle));
String typeTag = entry.type();
- Color eipColor = DiagramColors.getEipColor(SourceViewer.dashToCamelCase(typeTag));
+ Color eipColor = DiagramColors.getEipColor(YamlSourceContext.dashToCamelCase(typeTag));
String label = entry.label().isBlank() ? "" : entry.label();
if (label.length() > maxLabelW && maxLabelW > 3) {
label = label.substring(0, maxLabelW - 1) + "…";
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/HealthTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/HealthTab.java
index 5f431b57049b..eda5db9588fc 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/HealthTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/HealthTab.java
@@ -190,84 +190,7 @@ class HealthTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Health
-
- Health checks verify that the integration and its dependencies are
- functioning correctly. They are essential for container orchestration
- platforms like Kubernetes, but also useful for local monitoring.
-
- ## Table Columns
-
- - **GROUP** — Category of the health check: `camel` (core checks), `routes` (per-route health), `consumers` (consumer health)
- - **NAME** — Specific check name. For route checks this is the route ID; for consumer checks it is the consumer endpoint
- - **STATUS** — Health state: `UP` (green, healthy), `DOWN` (red, unhealthy), `UNKNOWN` (yellow, cannot determine)
- - **KIND** — Check type: `R` = Readiness only, `L` = Liveness only, `R/L` = serves both purposes
- - **MESSAGE** — Status details. Most useful when a check is DOWN — shows what went wrong (e.g., `Connection refused`, `Route stopped`)
-
- ## Example Screen
-
- ```
- GROUP NAME STATUS KIND MESSAGE
- camel context UP R/L
- camel route-controller UP R
- camel security-policy UP R security.status: clean
- routes timer-to-log UP R
- routes seda-consumer UP R
- ```
-
- All checks UP means the integration is healthy and ready to receive
- traffic. If any check shows DOWN, the MESSAGE column explains why.
-
- ## Readiness vs Liveness
-
- These concepts come from Kubernetes but apply to any deployment:
-
- - **Liveness** (`L`): Is the process alive and not stuck in a deadlock
- or infinite loop? If a liveness check fails, the platform should
- **restart** the process. Only fundamental checks use liveness —
- the `context` check verifies the CamelContext is still running.
-
- - **Readiness** (`R`): Is the process ready to handle traffic? During
- startup, a process may be alive but not yet ready (e.g., still
- connecting to a database or loading routes). If readiness fails,
- the platform should **stop sending traffic** but not restart.
-
- A check marked `R/L` serves both purposes. The `context` check is
- typically both — if the CamelContext is down, the process should be
- restarted and traffic should be rerouted.
-
- ## Built-in Health Checks
-
- Camel includes several built-in checks:
-
- - **context** — Is the CamelContext started and running?
- - **route-controller** — Are all routes started successfully?
- - **security-policy** — Are there any security policy violations?
- - **consumers** — Are consumers connected and healthy?
- - **routes** — Per-route health status
-
- Components can also contribute their own health checks. For example,
- a Kafka consumer checks its broker connectivity, and a database
- component checks its connection pool.
-
- ## Kubernetes Integration
-
- When deployed to Kubernetes, these health checks are exposed as
- HTTP endpoints:
-
- - `/observe/health/ready` — returns 200 if all readiness checks pass
- - `/observe/health/live` — returns 200 if all liveness checks pass
-
- Kubernetes uses these to decide when to send traffic to a pod and
- when to restart it.
-
- ## Keys
-
- - `Up/Down` — select health check
- - `s` — cycle sort column
- - `S` — reverse sort order
- """;
+ return DocHelper.loadHelpText("health");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/HeapHistogramTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/HeapHistogramTab.java
index 469129041b64..52927e66acb9 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/HeapHistogramTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/HeapHistogramTab.java
@@ -319,59 +319,7 @@ class HeapHistogramTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Heap Histogram
-
- The Heap Histogram tab shows class-level memory usage in the JVM heap,
- similar to `jcmd <pid> GC.class_histogram`. Each row represents a class
- with the number of live instances and total bytes consumed.
-
- This is useful for diagnosing memory leaks, finding unexpected object
- retention, and understanding which classes dominate heap usage.
-
- ## Table Columns
-
- - **#** — Rank by bytes (from the raw JVM histogram)
- - **CLASS NAME** — Fully qualified class name. Array types use JVM notation (e.g., `[B` = byte array, `[Ljava.lang.Object;` = Object array)
- - **INSTANCES** — Number of live instances of this class on the heap
- - **BYTES** — Total bytes consumed by all instances of this class
-
- The title bar shows total classes, instances, and bytes for the current filter.
-
- ## Detail Panel
-
- The detail panel below the table shows additional context for the selected class:
-
- - **Class** — Full class name, package, instance count and bytes
- - **Package Summary** — Total classes, instances, and bytes for all classes in the same package
- - **JAR** — The Maven artifact (groupId:artifactId:version) and file path of the JAR containing the class. JDK classes show "JDK (built-in)"
-
- ## Filter Modes
-
- - **all** (default) — Show all classes
- - **non-jdk** — Exclude JDK classes (java.*, javax.*, jdk.*, sun.*, com.sun.*, arrays)
- - **camel** — Show only classes from `org.apache.camel` packages
-
- ## What To Look For
-
- - **Large byte counts at the top**: Normal for byte arrays and char arrays — these back Strings and buffers
- - **Unexpected classes with high counts**: May indicate a memory leak
- - **Growing instance counts on refresh**: Press F5 repeatedly to spot classes whose counts keep growing
- - **Package summary**: Use the detail panel to see total memory for an entire package
- - **JAR origin**: Identify which dependency owns the memory-heavy classes
-
- ## Keys
-
- | Key | Action |
- |-----|--------|
- | Up/Down | Select class |
- | s | Cycle sort column (className, instances, bytes) |
- | S | Reverse sort order |
- | f | Toggle filter (all / non-jdk / camel) |
- | F5 | Refresh heap histogram |
- | PgUp/PgDn | Scroll by page |
- | Esc | Back |
- """;
+ return DocHelper.loadHelpText("heap-histogram");
}
private List<HeapEntry> sortedEntries() {
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/HistoryTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/HistoryTab.java
index 8e1808c2fad3..04803bff807a 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/HistoryTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/HistoryTab.java
@@ -150,110 +150,9 @@ class HistoryTab extends AbstractTab {
@Override
public boolean handleKeyEvent(KeyEvent ke) {
- if (diagram.isShowDiagram() && diagram.isHistoryMode() && diagram.hasHistoryData()) {
- if (diagram.isHistoryTopologyMode()) {
- if (ke.isUp()) {
- diagram.selectNodeUp();
- diagram.scrollToSelectedNode();
- return true;
- }
- if (ke.isDown()) {
- diagram.selectNodeDown();
- diagram.scrollToSelectedNode();
- return true;
- }
- if (ke.isLeft()) {
- diagram.selectNodeLeft();
- diagram.scrollToSelectedNode();
- return true;
- }
- if (ke.isRight()) {
- diagram.selectNodeRight();
- diagram.scrollToSelectedNode();
- return true;
- }
- if (ke.isConfirm()) {
- diagram.historyEnterDrillDown();
- return true;
- }
- } else {
- if (ke.isUp()) {
- diagram.historyNavigateUp();
- return true;
- }
- if (ke.isDown()) {
- diagram.historyNavigateDown();
- return true;
- }
- if (ke.isLeft()) {
- diagram.scrollLeft();
- return true;
- }
- if (ke.isRight()) {
- diagram.scrollRight();
- return true;
- }
- if (ke.isChar('t')) {
- diagram.historyReturnToTopology();
- return true;
- }
- }
- if (ke.isHome()) {
- diagram.scrollHome();
- return true;
- }
- if (ke.isCharIgnoreCase('n')) {
- showDescription = !showDescription;
- diagram.setShowDescription(showDescription);
- diagram.endLoad();
- loadDiagramForCurrentView();
- return true;
- }
- boolean isTraceMode = !diagramTraceSteps.isEmpty();
- if (ke.isChar('b')) {
- if (isTraceMode) {
- showTraceBody = !showTraceBody;
- } else {
- showHistoryBody = !showHistoryBody;
- }
- return true;
- }
- if (ke.isChar('h')) {
- if (isTraceMode) {
- showTraceHeaders = !showTraceHeaders;
- } else {
- showHistoryHeaders = !showHistoryHeaders;
- }
- return true;
- }
- if (ke.isChar('p')) {
- if (isTraceMode) {
- showTraceProperties = !showTraceProperties;
- } else {
- showHistoryProperties = !showHistoryProperties;
- }
- return true;
- }
- if (ke.isChar('v')) {
- if (isTraceMode) {
- showTraceVariables = !showTraceVariables;
- } else {
- showHistoryVariables = !showHistoryVariables;
- }
- return true;
- }
- if (ke.isChar('w')) {
- if (isTraceMode) {
- traceWordWrap = !traceWordWrap;
- } else {
- historyWordWrap = !historyWordWrap;
- }
- return true;
- }
- if (ke.isChar('i')) {
- infoPanelSize = (infoPanelSize + 1) % 3;
- return true;
- }
+ if (diagram.isShowDiagram() && diagram.isHistoryMode() && diagram.hasHistoryData()
+ && handleHistoryDiagramKeys(ke)) {
+ return true;
}
if (diagram.handleScrollKeys(ke)) {
return true;
@@ -363,99 +262,233 @@ class HistoryTab extends AbstractTab {
}
if (tracerActive && traceDetailView) {
- if (ke.isCharIgnoreCase('p')) {
- showTraceProperties = !showTraceProperties;
- return true;
- }
- if (ke.isCharIgnoreCase('v')) {
- showTraceVariables = !showTraceVariables;
+ return handleTraceDetailKeys(ke);
+ }
+ if (tracerActive) {
+ return handleTraceListKeys(ke);
+ }
+ return handleHistoryListKeys(ke);
+ }
+
+ /**
+ * Keys while a route or topology diagram is shown for a history/trace exchange: node navigation, section toggles
+ * (body, headers, properties, variables, word wrap) and info panel size. Returns false for keys not handled here.
+ */
+ private boolean handleHistoryDiagramKeys(KeyEvent ke) {
+ if (diagram.isHistoryTopologyMode()) {
+ if (ke.isUp()) {
+ diagram.selectNodeUp();
+ diagram.scrollToSelectedNode();
return true;
}
- if (ke.isCharIgnoreCase('h')) {
- showTraceHeaders = !showTraceHeaders;
+ if (ke.isDown()) {
+ diagram.selectNodeDown();
+ diagram.scrollToSelectedNode();
return true;
}
- if (ke.isCharIgnoreCase('b')) {
- showTraceBody = !showTraceBody;
+ if (ke.isLeft()) {
+ diagram.selectNodeLeft();
+ diagram.scrollToSelectedNode();
return true;
}
- if (ke.isCharIgnoreCase('w')) {
- traceWordWrap = !traceWordWrap;
- traceDetailScroll = 0;
- traceDetailHScroll = 0;
+ if (ke.isRight()) {
+ diagram.selectNodeRight();
+ diagram.scrollToSelectedNode();
return true;
}
- if (ke.isCharIgnoreCase('g')) {
- showWaterfall = !showWaterfall;
- detailFocused = false;
- waterfallScroll = 0;
+ if (ke.isConfirm()) {
+ diagram.historyEnterDrillDown();
return true;
}
- } else if (tracerActive) {
- if (ke.isChar('s')) {
- traceSortIndex = (traceSortIndex + 1) % TRACE_SORT_COLUMNS.length;
- traceSort = TRACE_SORT_COLUMNS[traceSortIndex];
- traceSortReversed = false;
+ } else {
+ if (ke.isUp()) {
+ diagram.historyNavigateUp();
return true;
}
- if (ke.isChar('S')) {
- traceSortReversed = !traceSortReversed;
+ if (ke.isDown()) {
+ diagram.historyNavigateDown();
return true;
}
- if (ke.isConfirm()) {
- Integer sel = traceTableState.selected();
- if (sel != null && sel >= 0 && sel < traceSortedExchangeIds.size()) {
- traceSelectedExchangeId = traceSortedExchangeIds.get(sel);
- traceDetailView = true;
- detailFocused = false;
- traceStepTableState.select(0);
- traceDetailScroll = 0;
- }
+ if (ke.isLeft()) {
+ diagram.scrollLeft();
return true;
}
- if (ke.isKey(KeyCode.F5)) {
- if (ctx.selectedPid != null) {
- traceFilePositions.clear();
- traces.set(Collections.emptyList());
- }
+ if (ke.isRight()) {
+ diagram.scrollRight();
return true;
}
- } else {
- if (ke.isCharIgnoreCase('p')) {
- showHistoryProperties = !showHistoryProperties;
+ if (ke.isChar('t')) {
+ diagram.historyReturnToTopology();
return true;
}
- if (ke.isCharIgnoreCase('v')) {
- showHistoryVariables = !showHistoryVariables;
- return true;
+ }
+ if (ke.isHome()) {
+ diagram.scrollHome();
+ return true;
+ }
+ if (ke.isCharIgnoreCase('n')) {
+ showDescription = !showDescription;
+ diagram.setShowDescription(showDescription);
+ diagram.endLoad();
+ loadDiagramForCurrentView();
+ return true;
+ }
+ boolean isTraceMode = !diagramTraceSteps.isEmpty();
+ if (ke.isChar('b')) {
+ if (isTraceMode) {
+ showTraceBody = !showTraceBody;
+ } else {
+ showHistoryBody = !showHistoryBody;
}
- if (ke.isCharIgnoreCase('h')) {
+ return true;
+ }
+ if (ke.isChar('h')) {
+ if (isTraceMode) {
+ showTraceHeaders = !showTraceHeaders;
+ } else {
showHistoryHeaders = !showHistoryHeaders;
- return true;
}
- if (ke.isCharIgnoreCase('b')) {
- showHistoryBody = !showHistoryBody;
- return true;
+ return true;
+ }
+ if (ke.isChar('p')) {
+ if (isTraceMode) {
+ showTraceProperties = !showTraceProperties;
+ } else {
+ showHistoryProperties = !showHistoryProperties;
+ }
+ return true;
+ }
+ if (ke.isChar('v')) {
+ if (isTraceMode) {
+ showTraceVariables = !showTraceVariables;
+ } else {
+ showHistoryVariables = !showHistoryVariables;
}
- if (ke.isCharIgnoreCase('w')) {
+ return true;
+ }
+ if (ke.isChar('w')) {
+ if (isTraceMode) {
+ traceWordWrap = !traceWordWrap;
+ } else {
historyWordWrap = !historyWordWrap;
- historyDetailScroll = 0;
- historyDetailHScroll = 0;
- return true;
}
- if (ke.isCharIgnoreCase('g')) {
- showWaterfall = !showWaterfall;
+ return true;
+ }
+ if (ke.isChar('i')) {
+ infoPanelSize = (infoPanelSize + 1) % 3;
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Keys in the trace detail view (section toggles, word wrap, waterfall).
+ */
+ private boolean handleTraceDetailKeys(KeyEvent ke) {
+ if (ke.isCharIgnoreCase('p')) {
+ showTraceProperties = !showTraceProperties;
+ return true;
+ }
+ if (ke.isCharIgnoreCase('v')) {
+ showTraceVariables = !showTraceVariables;
+ return true;
+ }
+ if (ke.isCharIgnoreCase('h')) {
+ showTraceHeaders = !showTraceHeaders;
+ return true;
+ }
+ if (ke.isCharIgnoreCase('b')) {
+ showTraceBody = !showTraceBody;
+ return true;
+ }
+ if (ke.isCharIgnoreCase('w')) {
+ traceWordWrap = !traceWordWrap;
+ traceDetailScroll = 0;
+ traceDetailHScroll = 0;
+ return true;
+ }
+ if (ke.isCharIgnoreCase('g')) {
+ showWaterfall = !showWaterfall;
+ detailFocused = false;
+ waterfallScroll = 0;
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Keys in the trace exchange list (sorting, open detail, refresh).
+ */
+ private boolean handleTraceListKeys(KeyEvent ke) {
+ if (ke.isChar('s')) {
+ traceSortIndex = (traceSortIndex + 1) % TRACE_SORT_COLUMNS.length;
+ traceSort = TRACE_SORT_COLUMNS[traceSortIndex];
+ traceSortReversed = false;
+ return true;
+ }
+ if (ke.isChar('S')) {
+ traceSortReversed = !traceSortReversed;
+ return true;
+ }
+ if (ke.isConfirm()) {
+ Integer sel = traceTableState.selected();
+ if (sel != null && sel >= 0 && sel < traceSortedExchangeIds.size()) {
+ traceSelectedExchangeId = traceSortedExchangeIds.get(sel);
+ traceDetailView = true;
detailFocused = false;
- waterfallScroll = 0;
- return true;
+ traceStepTableState.select(0);
+ traceDetailScroll = 0;
}
- if (ke.isKey(KeyCode.F5)) {
- historyEntries = Collections.emptyList();
- historyDetailScroll = 0;
- historyDetailHScroll = 0;
- historyRefreshRequested = true;
- return true;
+ return true;
+ }
+ if (ke.isKey(KeyCode.F5)) {
+ if (ctx.selectedPid != null) {
+ traceFilePositions.clear();
+ traces.set(Collections.emptyList());
}
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Keys in the history exchange list (section toggles, word wrap, waterfall, refresh).
+ */
+ private boolean handleHistoryListKeys(KeyEvent ke) {
+ if (ke.isCharIgnoreCase('p')) {
+ showHistoryProperties = !showHistoryProperties;
+ return true;
+ }
+ if (ke.isCharIgnoreCase('v')) {
+ showHistoryVariables = !showHistoryVariables;
+ return true;
+ }
+ if (ke.isCharIgnoreCase('h')) {
+ showHistoryHeaders = !showHistoryHeaders;
+ return true;
+ }
+ if (ke.isCharIgnoreCase('b')) {
+ showHistoryBody = !showHistoryBody;
+ return true;
+ }
+ if (ke.isCharIgnoreCase('w')) {
+ historyWordWrap = !historyWordWrap;
+ historyDetailScroll = 0;
+ historyDetailHScroll = 0;
+ return true;
+ }
+ if (ke.isCharIgnoreCase('g')) {
+ showWaterfall = !showWaterfall;
+ detailFocused = false;
+ waterfallScroll = 0;
+ return true;
+ }
+ if (ke.isKey(KeyCode.F5)) {
+ historyEntries = Collections.emptyList();
+ historyDetailScroll = 0;
+ historyDetailHScroll = 0;
+ historyRefreshRequested = true;
+ return true;
}
return false;
}
@@ -2397,165 +2430,7 @@ class HistoryTab extends AbstractTab {
@Override
public String getHelpText() {
- return """
- # Inspect
-
- The Inspect tab shows a history of recently processed exchanges
- (messages). This is one of the most powerful debugging tools — it
- lets you see exactly what happened to each message as it traveled
- through the integration, including every step it passed through.
-
- Camel uses a BacklogTracer to record exchange details. The most
- recent exchanges are kept in memory for inspection.
-
- ## Exchange List
-
- - **ID** — Unique exchange identifier (e.g., `ID-myhost-1234-5`). Every message passing through Camel gets a unique ID
- - **STATUS** — Whether the exchange completed successfully (`done`) or failed (`fail`). Failed exchanges also appear on the Errors tab
- - **ROUTE** — The route that processed this exchange
- - **AGO** — How long ago this exchange was processed (e.g., `2s`, `1m`, `5m`)
- - **ELAPSED** — Total processing time from when the exchange entered the route until it completed. Long elapsed times may indicate slow downstream services
-
- ## Example Screen
-
- ```
- ID STATUS ROUTE AGO ELAPSED
- ID-myhost-1234-10 done timer-to-log 1s 0ms
- ID-myhost-1234-9 done seda-consumer 2s 0ms
- ID-myhost-1234-8 done timer-to-seda 2s 1ms
- ID-myhost-1234-7 fail kafka-route 5s 5023ms
- ```
-
- The last exchange (`kafka-route`) failed after 5 seconds — likely a
- connection timeout to the Kafka broker.
-
- ## Detail View
-
- Press `Enter` on an exchange to see its full journey:
-
- **Message History** — A step-by-step trace of every node the exchange
- visited. This shows the exact path the message took through the route,
- including which branch was taken in a `choice` and how long each step
- took:
-
- ```
- RouteId NodeId Processor BHPV Elapsed
- *-> timer-to-log timer1 from[timer:hello] 0ms
- timer-to-log setBody1 setBody[simple] B 0ms
- timer-to-log choice1 choice 0ms
- timer-to-log when1 when[simple] 0ms
- ---> timer-to-log to1 to[kafka:orders] H 2ms
- timer-to-log log1 log[HIGH: ${body}] 0ms
- <-* timer-to-log timer1 from[timer:hello] 3ms
- ```
-
- This tells you the message entered via the timer, went through setBody,
- reached a choice node, matched the `when` condition, and was logged.
- The elapsed time for each step helps identify bottlenecks.
-
- **Change Indicators (BHPV)** — The BHPV column shows at a glance
- which parts of the exchange were modified at each step compared to
- the previous step:
-
- - `B` — Body changed
- - `H` — Headers changed
- - `P` — Exchange properties changed
- - `V` — Exchange variables changed
-
- Steps with no changes leave the column blank, so mutations stand
- out visually.
-
- **Depth-first ordering** — When an exchange spans multiple routes
- via async EIPs (multicast, splitter, recipientList), child exchange
- steps are inlined under the parent step that triggered them, indented
- with 2 spaces per depth level. This keeps the logical flow readable
- instead of interleaving concurrent branches.
-
- ## Direction Arrows
-
- The first column shows direction arrows that indicate the type
- of each step:
-
- - `*-->` — First step of a route consuming from a **remote** endpoint (e.g., Kafka, HTTP)
- - `*-> ` — First step of a route consuming from a **local** endpoint (e.g., timer, direct)
- - `<--*` — Last step of a route with a **remote** consumer endpoint
- - `<-* ` — Last step of a route with a **local** consumer endpoint
- - `--->` — A step that sends to a **remote** endpoint (e.g., `to[kafka:orders]`)
- - `~-->` — First step or send to a **stub** endpoint (running with `--stub` mode)
- - `<--~` — Last step of a route with a **stub** consumer endpoint
- - _(blank)_ — A regular processing step (log, setBody, choice, etc.)
-
- **Exchange Content** — Toggle these sections to inspect the message:
-
- - `h` — **Headers**: Key-value pairs carried with the message (e.g., `Content-Type`, `CamelFileName`, custom headers)
- - `b` — **Body**: The actual message content (text, JSON, XML, etc.)
- - `p` — **Properties**: Exchange-level metadata (not forwarded to endpoints, used for internal routing)
- - `v` — **Variables**: Exchange variables set during processing
-
- ## Use Cases
-
- - **Debugging routing logic**: Check which branch a `choice` or `filter` took
- - **Verifying transformations**: Compare body before and after a `transform` or `marshal` step
- - **Finding bottlenecks**: Look for steps with high elapsed times
- - **Understanding failures**: See exactly where in the route a failure occurred
-
- ## Route Diagram
-
- Press `d` to open the route diagram for the selected exchange.
- The diagram shows the route structure as a visual flowchart with
- box-drawing characters, highlighting the path the exchange took
- through the route in green (or red for failed exchanges).
-
- **Progressive Path Highlighting** — Use `Up/Down` to step through
- the exchange's journey node by node. As you navigate forward, each
- visited node lights up progressively in green, creating a visual
- replay of the message's path. Stepping backward removes the
- highlight from the last node. The currently selected node is
- shown with a dark background.
-
- **Multi-route exchanges** — When an exchange spans multiple routes
- (e.g., via `direct` or `seda` endpoints), all involved routes are
- shown stacked vertically. The diagram auto-scrolls to keep the
- current step visible.
-
- **Route Structure Preview** — A compact tree view appears in the
- bottom-right corner showing the full route hierarchy. The currently
- selected node is highlighted, helping you maintain orientation in
- large routes. This is the same minimap available on the Routes and
- Diagram tabs.
-
- **Info Panel** — An info panel on the left side of the diagram shows
- trace metadata for the current step: exchange ID, route, node,
- processor, elapsed time, thread, and direction. It also shows body,
- headers, properties, and variables respecting the same `b/h/p/v`
- toggles as the table view. Press `i` to cycle the panel size:
- narrow (35 chars), wide (half screen), or full (entire area).
- In wide mode, the minimap and tree preview are hidden to give more
- space. Word wrap (`w`) is also supported.
-
- Press `d` to close the diagram and return to the table.
- Press `Esc` to navigate back one route in drill-down mode.
-
- ## Keys
-
- - `Up/Down` — select exchange (or step through path in diagram)
- - `Enter` — view exchange details
- - `d` — toggle route diagram (open and close)
- - `Esc` — back to list / back one route in diagram drill-down
- - `i` — cycle info panel size (narrow / wide / full) in diagram
- - `n` — toggle description mode
- - `g` — toggle waterfall view
- - `h` — toggle headers
- - `b` — toggle body
- - `p` — toggle properties
- - `v` — toggle variables
- - `w` — toggle word wrap
- - `s` — cycle sort column
- - `S` — reverse sort order
- - `Left/Right` — horizontal scroll (diagram or detail)
- - `PgUp/PgDn` — page scroll
- - `F5` — refresh data
- """;
+ return DocHelper.loadHelpText("history");
}
void selectTraceExchange(String exchangeId) {
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/HttpTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/HttpTab.java
index b724005b38ef..38e319944d9b 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/HttpTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/HttpTab.java
@@ -689,66 +689,7 @@ class HttpTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # HTTP
-
- The HTTP tab shows all HTTP endpoints exposed by this integration and
- lets you send test requests interactively — a lightweight Postman built
- into the terminal. This includes REST API endpoints, management endpoints
- (health, metrics), and any other HTTP routes.
-
- ## Endpoint List
-
- - **METHOD** — HTTP method: `GET`, `POST`, `PUT`, `DELETE`, `PATCH`, etc.
- - **PATH** — URL path for this endpoint
- - **TOTAL** — Number of HTTP requests received since startup
- - **CONSUMES** — Content-Type this endpoint accepts
- - **PRODUCES** — Content-Type this endpoint returns
- - **SOURCE** — How the endpoint was registered: REST(code), REST(contract), HTTP, Management
- - **STATE** — Endpoint state: `Started` or `Stopped`
-
- ## HTTP Probe
-
- Press `Enter` on an endpoint to open the interactive HTTP probe.
-
- The probe has these sections:
-
- - **Method**: `Left/Right` arrows to cycle through HTTP methods
- - **URL**: Read-only full URL (with resolved placeholders). Clickable as hyperlink
- - **Path**: Editable URL path template (e.g., `/api/users/{id}`)
- - **Path Params**: Auto-detected from `{xxx}` placeholders in the path. Fill in values and they get substituted in the URL
- - **Query Params**: Key-value pairs appended to the URL as `?key=value`. Press `+` to add
- - **Content-Type**: Cycle through common content types with `Left/Right` arrows
- - **Accept**: Cycle through common accept types with `Left/Right` arrows
- - **Headers**: Custom request headers. Press `+` to add
- - **Body**: Multi-line request body (Enter for newline). Supports `file:payload.json` to load from disk
- - **Response**: HTTP status code, elapsed time, response headers, and body
- - **History**: Recent requests with replay support
-
- Press `F5` to send the request. Press `p` to toggle pretty-print for JSON responses.
-
- ## Keys
-
- ### Endpoint List
- - `Up/Down` — select endpoint
- - `Enter` — open HTTP probe for selected endpoint
- - `s` — cycle sort column
- - `S` — reverse sort order
- - `f` — cycle filter (all / rest / http)
- - `m` — toggle management endpoints
- - `c` — view OpenAPI spec (when available)
-
- ### HTTP Probe
- - `F5` — send request
- - `Tab/Down` — next field
- - `Up` — previous field
- - `Enter` — newline in body, advance in other fields
- - `Left/Right` — cycle method, content-type, accept; cursor in text fields
- - `+` — add query param or header
- - `p` — toggle pretty-print
- - `PgUp/PgDn` — scroll response
- - `Esc` — close probe
- """;
+ return DocHelper.loadHelpText("http");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/InflightTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/InflightTab.java
index 5c0a5d2cf13c..8b9f2944e514 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/InflightTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/InflightTab.java
@@ -213,57 +213,7 @@ class InflightTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Inflight
-
- The Inflight tab shows exchanges that are currently being processed or
- are blocked waiting for a response. This is your real-time view into
- what the integration is doing right now — which messages are in flight
- and how long they have been processing.
-
- This tab requires `--inflight-browse=true` when starting the integration.
- Without it, Camel does not track individual inflight exchanges.
-
- ## Table Columns
-
- - **STATUS** — Exchange state: `inflight` (green, actively processing) or `blocked` (red, waiting for a resource like a lock or a slow downstream service)
- - **EXCHANGE ID** — Unique identifier for this exchange (e.g., `ID-myhost-1234-5`)
- - **ROUTE/NODE** — Which route and specific processor node is currently handling the exchange. Format: `routeId/nodeId` (e.g., `my-route/to1`). This tells you exactly where in the route the message is right now
- - **DURATION** — Time elapsed since processing started (e.g., `1s`, `5s`, `1m30s`). Long durations may indicate a slow downstream service or a deadlock
- - **ELAPSED** — Visual duration bar showing relative processing time. Longer bars mean longer processing. Color indicates severity
-
- ## Example Screen
-
- ```
- STATUS EXCHANGE ID ROUTE/NODE DURATION ELAPSED
- inflight ID-myhost-1234-10 my-route/to1 234ms ██
- inflight ID-myhost-1234-9 my-route/process2 1s ████████
- blocked ID-myhost-1234-7 api-route/to3 12s ████████████████████
- ```
-
- The third exchange has been blocked for 12 seconds — it is likely
- waiting for a response from a slow external service.
-
- ## Duration Colors
-
- - **Green**: less than 1 second — normal processing time
- - **Yellow**: 1-10 seconds — getting slow, worth monitoring
- - **Red**: over 10 seconds — potentially stuck or waiting on an unresponsive service
-
- ## When To Use
-
- - **Diagnosing slow processing**: If messages are taking longer than expected, this tab shows exactly which route and node they are stuck at
- - **Detecting blocked exchanges**: Blocked exchanges are waiting for a resource (e.g., a database connection, a file lock, a thread pool). Multiple blocked exchanges at the same node may indicate contention
- - **Monitoring concurrent load**: The number of inflight exchanges shows how much concurrent work the integration is handling
- - **Identifying stuck messages**: Exchanges that stay inflight for minutes are likely stuck — the ROUTE/NODE column tells you where to investigate
-
- ## Keys
-
- - `Up/Down` — select exchange
- - `s` — cycle sort column
- - `S` — reverse sort order
- - `Esc` — back
- """;
+ return DocHelper.loadHelpText("inflight");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/InternalTasksTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/InternalTasksTab.java
index 7a7b57be39b6..53581b74fcb4 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/InternalTasksTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/InternalTasksTab.java
@@ -161,45 +161,7 @@ class InternalTasksTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Recovery Tasks
-
- Recovery tasks are background operations that Camel components schedule
- for reconnection and retry purposes. For example, when a Kafka broker or
- JMS connection drops, the component registers a recovery task that
- periodically attempts to reconnect.
-
- Tasks self-register when they start running and are removed when they
- complete, fail permanently, or exhaust their retry budget. The table
- shows only **currently active** tasks.
-
- ## Table Columns
-
- - **NAME** — Descriptive name of the task (e.g., connection target or component)
- - **STATUS** — Current state: `Waiting` (waiting for next attempt), `Attempting` (actively trying now), `Completed` (finished successfully), `Failed` (gave up), `Exhausted` (retry budget spent)
- - **ATTEMPTS** — Number of retry attempts made so far
- - **DELAY** — Current delay between attempts in milliseconds
- - **ELAPSED** — Total time since the task started
- - **FIRST** — When the first attempt was made (ago)
- - **LAST** — When the last attempt was made (ago)
- - **NEXT** — Time until the next attempt
- - **ERROR** — Last error message, if any
-
- ## When Tasks Appear
-
- You will typically see recovery tasks when:
- - A messaging broker connection is lost and the consumer is reconnecting
- - A leader election is in progress (e.g., camel-master)
- - A component is retrying a failed initialization
-
- An empty table means all connections and background operations are healthy.
-
- ## Keys
-
- - `Up/Down` — select task
- - `s` — cycle sort column
- - `S` — reverse sort order
- """;
+ return DocHelper.loadHelpText("internal-tasks");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/JfrTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/JfrTab.java
index 6fa628aeed13..5d5cfdb54c12 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/JfrTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/JfrTab.java
@@ -1170,33 +1170,6 @@ class JfrTab extends AbstractTab {
@Override
public String getHelpText() {
- return """
- # JFR
-
- The JFR tab shows the live status of camel-jfr's runtime instrumentation
- and lets you view aggregated runtime data from JFR recordings.
-
- ## Data Views
-
- Press **F5** to take a snapshot of the active JFR recording. The snapshot
- data is aggregated into five views:
-
- - **Routes** — per-route exchange count, failures, and timing with
- a processor panel below showing processors for the selected route
- - **Processors** — per-processor invocation count and timing across all routes
- - **Endpoints** — per-endpoint send count and timing
- - **Failures** — recent exchange failures with exception details
- - **Redeliveries** — recent redelivery attempts
-
- ## Controls
-
- - `F5` — refresh (take new JFR snapshot)
- - `Space` — cycle view
- - `s` / `S` — cycle sort column / reverse sort direction
- - `Esc` — back
-
- Requires at least one active recording; start one via `--jfr`,
- `jcmd <pid> JFR.start`, or JMX.
- """;
+ return DocHelper.loadHelpText("jfr");
}
}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/KafkaTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/KafkaTab.java
index f162ef19d7ca..6cbfc9289571 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/KafkaTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/KafkaTab.java
@@ -220,45 +220,7 @@ class KafkaTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Kafka
-
- Displays live status for all Kafka consumers in the selected integration.
- Data comes from the Kafka dev console built into `camel-kafka`, which
- tracks each consumer worker thread's group membership, current position,
- and health state.
-
- ## Table Columns
-
- - **ROUTE** — Route ID that owns this Kafka consumer
- - **STATUS** — Worker state: `Running` (green, actively polling),
- `Paused` (yellow, consumer paused), or error states (red)
- - **GROUP-ID** — Kafka consumer group ID this consumer belongs to
- - **TOPIC** — Topic of the last consumed record
- - **PARTITION** — Partition number of the last consumed record
- - **OFFSET** — Offset of the last consumed record
- - **ENDPOINT** — Camel endpoint URI for this consumer
- - **ERROR** — Last error message if the consumer is unhealthy
-
- ## What to Look For
-
- - **All consumers Running**: Normal operation. Offsets should be
- advancing steadily if messages are flowing.
- - **Consumer Paused**: The consumer has been programmatically paused
- (e.g., by a route policy or manual suspension).
- - **Error column populated**: The consumer worker is unhealthy.
- Check the error message for connection issues, authentication
- failures, or deserialization errors.
- - **Offset not advancing**: If messages are being produced but the
- offset stays the same, the consumer may be stuck or the topic
- may have no new messages on that partition.
-
- ## Keys
-
- - `Up/Down` — select consumer
- - `s` — cycle sort column
- - `S` — reverse sort order
- """;
+ return DocHelper.loadHelpText("kafka");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/LogTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/LogTab.java
index bf0713268c39..281ce9ccb67e 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/LogTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/LogTab.java
@@ -710,105 +710,7 @@ class LogTab extends AbstractTab {
@Override
public String getHelpText() {
- return """
- # Log
-
- The Log tab shows live log output from the running integration, similar
- to `tail -f` on a log file. Log entries are color-coded by level for
- quick visual scanning.
-
- ## Log Levels
-
- Each log message has a severity level:
-
- - **ERROR** (red) — Something went wrong that needs attention. Check the message and stack trace. Errors often correspond to entries on the Errors tab
- - **WARN** (yellow) — Potential issues that may need attention but are not immediately critical. Examples: deprecated features, connection retries, configuration warnings
- - **INFO** (green) — Normal operational messages: routes starting, endpoints connecting, messages processed. This is the default level
- - **DEBUG** (blue) — Detailed diagnostic information for troubleshooting. Shows internal decision-making, message transformations, and routing logic
- - **TRACE** (dim) — Very fine-grained output showing every step of processing. Generates a lot of output — use only when debugging a specific problem
-
- ## Example Screen
-
- ```
- 10:29:32 INFO [main] CamelContext started in 1s234ms
- 10:29:33 INFO [Camel (camel-demo) thread #2] HIGH: Hello from Camel at 10:29:33
- 10:29:34 INFO [Camel (camel-demo) thread #2] LOW: Hello from Camel at 10:29:34
- 10:29:35 WARN [Camel (camel-demo) thread #3] Connection retry 1 of 3
- 10:29:38 ERROR [Camel (camel-demo) thread #3] Connection refused: localhost:9092
- ```
-
- ## Log Level
-
- Press `l` to open the log level picker. Selecting a level changes the
- running application's root logger to that level:
-
- - Select **ERROR** — only ERROR messages are logged
- - Select **WARN** — WARN and ERROR are logged
- - Select **INFO** — INFO, WARN, and ERROR are logged (default)
- - Select **DEBUG** — everything except TRACE is logged
- - Select **TRACE** — all messages are logged
-
- This changes the actual log level of the running integration, not
- just a display filter. It is useful for temporarily enabling debug
- logging to diagnose an issue.
-
- ## Find and Highlight
-
- **Find** (`/`) — search for text in the log. Type a search term and
- press Enter to jump to the first match. Use `n` to go to the next
- match and `N` for the previous match. The current match is shown
- with a green background, other matches with yellow. Press `Esc`
- to clear the search.
-
- **Highlight** (`h`) — persistently highlight all occurrences of a
- word in the log. Type a word and press Enter — all occurrences
- are highlighted with a yellow background while the log continues
- scrolling in follow mode. Press `h` again and submit an empty
- term to clear the highlight. Both find and highlight can be
- active at the same time.
-
- Both find and highlight are case-insensitive.
-
- ## Thread Names
-
- The thread name in square brackets (e.g., `[Camel (camel-demo) thread #2]`)
- tells you which thread produced the log message. This helps correlate
- log entries with specific routes when multiple routes run concurrently.
-
- ## Pinned Log
-
- Press `Ctrl+L` from any tab to pin the log to the bottom of the screen.
- This lets you watch log output while working in other tabs (Routes,
- Diagram, Overview, etc.) without switching back and forth.
-
- When pinned, pressing `Ctrl+L` again cycles the panel height through
- 25%, 50%, 75%, and then turns the pin off. The default pin size is 50%.
-
- When you navigate to the Log tab itself (key `2`), the log goes
- full-screen as usual. Leaving the Log tab brings the pin back.
-
- If the Shell (`F6`) or AI panel (`F8`) is opened while the log is
- pinned, it temporarily takes over the bottom panel. Closing Shell/AI
- restores the pinned log automatically.
-
- The pinned log panel can also be resized by dragging its top border
- with the mouse.
-
- ## Keys
-
- - `Up/Down` — scroll log
- - `PgUp/PgDn` — scroll by page
- - `Home/End` — jump to beginning/end of log
- - `/` — find (search for text)
- - `n` — next match
- - `N` — previous match
- - `h` — highlight a word
- - `l` — change log level
- - `f` — toggle follow mode
- - `w` — toggle word wrap
- - `Ctrl+L` — pin/cycle/unpin log panel (works from any tab)
- - `Esc` — clear find / back
- """;
+ return DocHelper.loadHelpText("log");
}
JsonObject getLogDataAsJson(int limit, String filter, String level) {
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/MavenDependenciesTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/MavenDependenciesTab.java
index 42f6c77908d6..36794c0f88b0 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/MavenDependenciesTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/MavenDependenciesTab.java
@@ -494,89 +494,7 @@ class MavenDependenciesTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Maven Dependencies
-
- The Maven Dependencies tab shows the declared dependencies for the
- selected integration, as they would appear in a pom.xml file. Unlike
- the Classpath tab (which shows all JARs on the JVM classpath including
- internal infrastructure), this tab filters out internal bootstrap JARs
- and shows only the dependencies the application actually declares.
-
- ## Data Sources
-
- The tab discovers dependencies from (in order of priority):
-
- - **pom.xml** — For exported Maven projects (Spring Boot, Quarkus).
- Parses compile-scoped dependencies from the project's pom.xml.
- - **.camel-jbang/camel-jbang-run.properties** — For Camel CLI (JBang)
- mode. Reads the `dependency=mvn:...` lines that list all declared
- dependencies.
-
- The data source is shown in the title bar (e.g., "pom.xml" or "jbang").
-
- ## Table Columns
-
- - **GROUP:ARTIFACT** — Maven coordinate (e.g., `org.apache.camel:camel-core`)
- - **VERSION** — The dependency version (e.g., `4.22.0`)
-
- Each row shows the Maven coordinate and its version.
-
- ## Sort
-
- Press `s` to cycle sort column (artifact, version).
- Press `S` to reverse sort order.
-
- ## Scope
-
- Press `f` to cycle the scope filter:
-
- - **all** — show all dependencies (default)
- - **camel** — show only Apache Camel dependencies
- - **other** — show only non-Camel (third-party) dependencies
-
- The active scope is shown in the footer and title bar.
-
- ## Transitive Dependencies
-
- Press `t` to resolve transitive dependencies on demand. The first
- press triggers Maven resolution (shown as "resolving..." in the
- footer). Once resolved, transitive dependencies appear dimmed in
- the table with a **VIA** column showing which direct dependency
- pulled them in. Subsequent presses toggle between showing all
- dependencies (direct + transitive) and direct only.
-
- The title shows "(+transitive)" when transitive mode is active.
- This is useful for CVE auditing — when a transitive JAR has a
- known vulnerability, the VIA column tells you which direct
- dependency to upgrade or exclude.
-
- ## Filter
-
- Press `/` to open the filter input. Type a search term and press
- `Enter` to filter by substring match. For example, type `kafka` to
- find Kafka-related dependencies, or `spring` to find Spring
- dependencies. The scope and text filter work together.
-
- ## When To Use
-
- - **CVE auditing**: Review only the real application dependencies, not
- internal infrastructure JARs that leak in via camel-kamelet-main
- - **Dependency review**: Understand what your integration actually
- depends on
- - **Version checking**: Verify specific dependency versions
- - **Transitive analysis**: See the full dependency tree similar to
- `mvn dependency:tree` (flat list)
-
- ## Keys
-
- - `s` — cycle sort column
- - `S` — reverse sort order
- - `f` — cycle scope (all, camel, other)
- - `t` — resolve and toggle transitive dependencies
- - `/` — open filter
- - `Esc` — clear filter or back
- """;
+ return DocHelper.loadHelpText("maven-dependencies");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/MemoryLeakTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/MemoryLeakTab.java
index 4db816e7dde2..564dfdd58608 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/MemoryLeakTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/MemoryLeakTab.java
@@ -1341,137 +1341,7 @@ class MemoryLeakTab extends AbstractTab {
@Override
public String getHelpText() {
- return """
- # Memory Leak
-
- This tab helps diagnose memory leaks by recording which objects
- survive garbage collection and tracing why they are still alive.
-
- It uses Java Flight Recorder (JFR) under the hood to sample
- long-lived objects and capture their reference chains back to
- GC roots. The recording is lightweight and safe for production.
-
- For deep heap analysis, use traditional tools such as
- **jmap** (heap dump), **jhat**, or **Eclipse MAT** alongside
- this tab. This tab is for quick, in-place triage — those tools
- give you the full picture.
-
- ## How To Use
-
- 1. Press **R** to start a recording (default 60 seconds)
- 2. Use **+**/**-** to adjust the duration before starting
- 3. Wait for the recording to complete (or press **X** to stop early)
- 4. Browse the results table and select entries to see details
-
- ## Table Columns
-
- Samples from the same class and allocation site (stack trace) are
- grouped together automatically.
-
- - **#** — Group number
- - **CLASS** — The class of the sampled long-lived object
- - **COUNT** — Number of samples from the same allocation site
- - **SAMPLED** — Sum of sampled allocation sizes during the recording
- - **AGE** — Maximum age across samples in the group
-
- ## Detail Panel
-
- Select an entry to see its reference chain and allocation stack trace:
-
- - **Reference Chain** — Path from the object to its GC root, showing
- each referencing type and field name
- - **Allocation Stack Trace** — Where the object was originally allocated
-
- ## Important: Sizes Are Sampled, Not Totals
-
- The SAMPLED column shows the sum of allocation sizes that JFR captured
- during the recording window — it is NOT the total heap footprint of
- that class. Use the values to compare classes relative to each other
- and to spot trends, not as absolute heap usage numbers.
-
- ## What To Look For
-
- - **Objects with very long ages**: These have survived many GC cycles
- - **Unexpected reference chains**: Objects held by caches, maps, or
- static fields that prevent garbage collection
- - **Growing collections**: HashMap, ArrayList, ConcurrentHashMap entries
- that keep accumulating
-
- ## Dual Recording Mode (Default)
-
- Dual mode runs two sequential recordings and compares them,
- which is the most effective way to detect leaks. Press **d**
- to toggle between **dual** and **single** mode.
-
- In **dual** mode, pressing **r** runs:
- - **Run 1** at the configured duration (e.g. 60s)
- - **Run 2** at 2x the duration (e.g. 120s)
-
- After both complete, a comparison table shows how each class
- behaved across the two runs. The **RUN1** and **RUN2**
- columns show the raw sampled sizes. For stable objects,
- the sampled size stays roughly the same regardless of
- duration. For leaking objects, the sampled size grows
- because more allocations accumulate over the longer run.
- The **GROWTH** column shows the percentage change.
- Entries under 1KB in both runs are filtered out as noise.
-
- ### Trend Indicators
-
- - **↑ leak!** (red) — Growth >= +50%%, very likely leak
- - **↑ leak?** (yellow) — Growth +30%% to +50%%, suspicious
- - **→ stable** (green) — Growth -30%% to +30%%, normal
- - **↓** (dim) — Growth < -30%%, shrinking
- - **new** (yellow) — Only appeared in Run 2
- - **gone** (dim) — Only appeared in Run 1
-
- ### Low Confidence %s
-
- A **%s** warning appears when sample counts are too low
- (fewer than 5 in either run) or diverge significantly from
- the expected duration ratio. The growth percentage is shown
- with a **~** prefix (e.g. ~+53%%) to indicate the value may
- not be reliable. JFR sampling is statistical — low sample
- counts produce noisy results. Re-run with a longer duration
- to collect more samples.
-
- ## Dominators View
-
- Press **v** to toggle between the default **samples** view (grouped by
- allocation class) and the **dominators** view. The dominators view
- re-groups results by the **root holder** — the object closest to the
- GC root in each reference chain. This answers the question: "which
- Map, cache, or field is accumulating the most objects?"
-
- Each row shows the holder (e.g. `LeakyCache.cache`), how many distinct
- classes it retains, the total object count, and the aggregate sampled
- size. Select a row to see the breakdown by allocation class, the
- reference chain, and the allocation stack trace.
-
- ## Comparison With Heap Histogram
-
- The **Heap Histogram** tab shows WHAT is using memory (class instance
- counts and total sizes). This tab shows WHY objects are still alive
- (reference chains to GC roots). Use both together: find suspicious
- classes in Heap Histogram, then use Memory Leak to trace why they
- are not being collected.
-
- ## Keys
-
- | Key | Action |
- |-----|--------|
- | R | Start/restart recording |
- | X | Stop recording early |
- | d | Toggle single/dual recording mode |
- | v | Toggle samples/dominators view |
- | +/- | Adjust recording duration |
- | Up/Down | Select sample |
- | s | Cycle sort column (class, size, age) |
- | S | Reverse sort order |
- | m | Cycle minimum size filter |
- | PgUp/PgDn | Scroll detail panel |
- | Esc | Back |
- """.formatted(TuiIcons.HEALTH_WARN, TuiIcons.HEALTH_WARN);
+ return DocHelper.loadHelpText("memory-leak").formatted(TuiIcons.HEALTH_WARN, TuiIcons.HEALTH_WARN);
}
// ---- Action methods ----
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/MemoryTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/MemoryTab.java
index 63227d41e9d8..06ccd219bd10 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/MemoryTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/MemoryTab.java
@@ -464,92 +464,7 @@ class MemoryTab extends AbstractTab {
@Override
public String getHelpText() {
- return """
- # Memory
-
- The Memory tab shows JVM memory usage, garbage collection stats, and a
- real-time heap usage chart. This helps you monitor memory consumption,
- detect memory leaks, and understand GC behavior.
-
- ## Heap Memory
-
- The JVM heap is where Java objects live. Three values matter:
-
- - **used**: Memory currently occupied by live objects. This value goes up as objects are created and drops when garbage collection runs
- - **committed**: Memory the JVM has reserved from the operating system. This is your working set — the JVM can use this much without requesting more from the OS. The JVM may increase committed memory up to the max limit as needed
- - **max**: The absolute upper limit set by `-Xmx`. The JVM will never use more than this. If used reaches max and GC cannot free enough space, you get an `OutOfMemoryError`
-
- Two gauge bars show how full the heap is:
-
- ```
- committed: 80 MB ████████████████░░░░░░░░░░░░░░ 53%
- max: 16 GB ██░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 2%
- ```
-
- The committed bar shows how much of the reserved memory is in use —
- this is the most useful indicator for day-to-day monitoring. The max
- bar shows how much headroom remains before the JVM hits its hard limit.
-
- ## Example Screen
-
- ```
- Heap: used 55 MB / committed 80 MB / max 16 GB
- committed: 80 MB ████████████████░░░░░░░░░░░░░░ 68%
- max: 16 GB ██░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 0%
-
- Old Gen: used 19 MB / committed 24 MB / max 16 GB
- Non-Heap: used 66 MB / committed 68 MB
- Metaspace: used 43 MB / committed 44 MB
-
- GC: 19 collections, 28 ms total
- ```
-
- ## Old Gen
-
- When objects survive multiple garbage collections, they are promoted to
- the Old Generation memory pool. Old Gen stores long-lived objects like
- caches, connection pools, and singleton beans.
-
- **Watch for**: Old Gen usage that keeps growing over time without going
- back down after GC. This pattern often indicates a **memory leak** —
- objects being retained that should have been released.
-
- ## Non-Heap and Metaspace
-
- - **Non-Heap**: Memory outside the heap used by the JVM itself — JIT compiled code, thread stacks, internal data structures
- - **Metaspace**: A subset of non-heap where Java class metadata is stored (class definitions, method tables, constant pools). Replaced the old PermGen space in Java 8+. Metaspace grows automatically but can be limited with `-XX:MaxMetaspaceSize`
-
- High Metaspace usage is normal for large applications with many classes.
- It typically stays stable after startup.
-
- ## Garbage Collection
-
- - **Collections**: Total number of GC cycles. The JVM runs GC automatically when it needs to free memory. Modern collectors (G1, ZGC) run frequently with short pauses
- - **Time**: Total time spent in GC (milliseconds). High GC time relative to uptime means the JVM is spending too much time cleaning up — consider increasing heap size
-
- **GC key**: The key at the top identifies which GC algorithm is active
- (e.g., `G1 Young Generation`, `ZGC`). Different algorithms have
- different trade-offs between throughput and pause times.
-
- ## Sparkline Chart
-
- The chart shows heap usage over time. Color indicates how full the
- heap is relative to committed memory:
-
- - **Green**: below 60% — healthy, plenty of headroom
- - **Yellow**: 60-80% — getting full, GC is working harder
- - **Red**: above 80% — high pressure, risk of long GC pauses or OOM
-
- A sawtooth pattern (usage rises then drops sharply) is normal — it shows
- GC reclaiming memory periodically. A steadily rising baseline that
- never drops back suggests a memory leak.
-
- ## Keys
-
- - `g` — trigger garbage collection on the running integration (sends a GC request to the JVM — useful for testing if high usage is just uncollected garbage)
- - `h` — write a heap dump (.hprof) file for deep analysis with tools like Eclipse MAT or VisualVM
- - `Esc` — back
- """;
+ return DocHelper.loadHelpText("memory");
}
private static String buildGaugeBar(long pct, int width) {
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/MetricsTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/MetricsTab.java
index 0dd26bc5478f..4de3ac25cba7 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/MetricsTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/MetricsTab.java
@@ -899,102 +899,7 @@ class MetricsTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Metrics
-
- The Metrics tab shows Micrometer metrics collected by the integration.
- Micrometer is the standard metrics library for Java — Camel automatically
- instruments exchanges, routes, and JVM internals when the `camel-micrometer`
- component is present.
-
- These metrics can be exported to monitoring systems like Prometheus,
- Grafana, Datadog, or InfluxDB.
-
- ## Dashboard Mode (default)
-
- A high-level overview organized into panels showing the most important
- metrics at a glance:
-
- **Camel Exchanges:**
- - **Total** — Total exchanges processed across all routes
- - **Succeeded** — Exchanges that completed without error
- - **Failed** — Exchanges that ended with an exception
- - **Inflight** — Exchanges currently being processed
- - **Ext Reloaded** — External reloads counter (how many times routes were reloaded from file changes or API calls)
-
- **Route Timers:**
- Per-route processing time statistics. Shows the mean and max processing
- time in milliseconds for each route. A rising mean indicates degrading
- performance; a high max with low mean suggests occasional slow outliers.
-
- **Event Notifiers:**
- Timing of exchange lifecycle events. Camel fires events at each stage
- of an exchange's life (created, sending, sent, completed, failed).
- The timers here show how long these lifecycle hooks take — useful for
- detecting slow event listeners or interceptors.
-
- **JVM Metrics:**
- - **Memory**: Heap used/max/committed, non-heap, buffer pools
- - **CPU**: Process CPU usage and system CPU usage as percentages
- - **Threads**: Current thread count, peak threads, daemon threads
- - **GC**: Per-cause collection count and total pause time
-
- ## Example Dashboard
-
- ```
- ── Camel Exchanges ─────────────────────
- Total: 1,250 Succeeded: 1,247
- Failed: 3 Inflight: 1
- Ext Reloaded: 2
-
- ── Route Timers ────────────────────────
- timer-to-log mean: 0.5ms max: 12ms
- seda-consumer mean: 0.1ms max: 2ms
-
- ── JVM ─────────────────────────────────
- Heap: 55/80 MB CPU: 2.1% Threads: 12
- ```
-
- ## Table Mode
-
- Press `t` to switch to a table showing every individual meter:
-
- - **TYPE** — Meter type:
- - `counter` — Cumulative count that only goes up (e.g., total exchanges)
- - `gauge` — Current value that goes up and down (e.g., memory used)
- - `timer` — Tracks both count and duration (e.g., processing time)
- - `dist` — Distribution summary with percentiles
- - **NAME** — Metric name following Micrometer conventions (e.g., `camel.exchanges.total`, `jvm.memory.used`)
- - **VALUE** — Current metric value with appropriate formatting
- - **TAGS** — Key-value dimensions that identify the metric (e.g., `routeId=myRoute`, `area=heap`). Tags let you filter and group metrics in monitoring dashboards
-
- ## Raw Mode
-
- Press `r` to see the Prometheus exposition format — the same text output
- you would get from the `/observe/metrics` HTTP endpoint. This is the
- exact format Prometheus scrapes, useful for:
-
- - Debugging why a metric does not appear in Grafana
- - Verifying metric names and labels match your PromQL queries
- - Copying metric definitions for alerting rules
-
- ## Common Camel Metrics
-
- - `camel.exchanges.total` — Total exchanges (tagged by routeId)
- - `camel.exchanges.failed` — Failed exchanges
- - `camel.exchanges.inflight` — Currently processing
- - `camel.exchange.processing.time` — Processing duration timer
- - `jvm.memory.used` — JVM memory (tagged by area: heap/nonheap)
- - `jvm.gc.pause` — GC pause durations
-
- ## Keys
-
- - `d` — toggle table mode
- - `r` — toggle raw Prometheus mode
- - `Up/Down` — navigate (in table or raw mode)
- - `s` — cycle sort column (in table mode)
- - `S` — reverse sort order
- """;
+ return DocHelper.loadHelpText("metrics");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/NetworkTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/NetworkTab.java
index 7e23b8cdd4a7..604ead1b54b6 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/NetworkTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/NetworkTab.java
@@ -435,39 +435,7 @@ class NetworkTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Network Services
-
- Network Services shows all **network-facing endpoints** — HTTP listeners,
- Kafka connections, database links, messaging brokers — with direction, protocol,
- and hit counts. Unlike the Endpoints tab which includes internal plumbing
- (`direct:`, `seda:`, `log:`), this tab focuses on real network traffic.
-
- ## Table Columns
-
- - **COMPONENT** — The Camel component (e.g., `platform-http`, `kafka`, `sql`)
- - **ROUTE** — The route this service belongs to
- - **DIR** — Direction: `in` (consuming/listening) or `out` (producing/calling)
- - **PROTOCOL** — Network protocol: `http`, `https`, `tcp`, `amqp`, etc.
- - **HOSTED** — Whether this is a locally hosted service (e.g., HTTP server) vs a remote client connection
- - **HITS** — Total number of messages processed through this service endpoint
- - **BODY** — Average message body size (shown when payload sizing is active)
- - **HDR** — Average message headers size (shown when payload sizing is active)
- - **SERVICE URL** — The network address or connection URL
-
- ## Flow Diagram
-
- The bottom panel shows the same in/out flow diagram and throughput sparkline
- as the Endpoints tab, but scoped to network services only. This gives a
- clearer picture of actual external traffic without internal routing noise.
-
- ## Keys
-
- - `Up/Down` — select service
- - `s` — cycle sort column
- - `S` — reverse sort order
- - `a` — toggle chart on/off
- """;
+ return DocHelper.loadHelpText("network");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OverviewTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OverviewTab.java
index 42ac8e812db3..bb7828f7caf8 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OverviewTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OverviewTab.java
@@ -311,274 +311,15 @@ class OverviewTab extends AbstractTab {
vSplit.clearBorderPos();
}
- List<Row> rows = new ArrayList<>();
- Row header;
- Constraint[] widths;
- int rowIndex = 0;
-
- if (topMode) {
- for (IntegrationInfo info : infos) {
- boolean isEven = (rowIndex++ % 2 == 0);
- Style rowBg = isEven ? Style.EMPTY.bg(Theme.zebra()) : Style.EMPTY;
-
- if (info.vanishing) {
- long elapsed = System.currentTimeMillis() - info.vanishStart;
- float fade = 1.0f - Math.min(1.0f, (float) elapsed / VANISH_DURATION_MS);
- int gray = (int) (100 * fade);
- Style dimStyle = Style.EMPTY.fg(Color.indexed(232 + Math.min(gray / 4, 23)));
- String vanishName = TuiIcons.labeled(TuiIcons.CAMEL, info.name != null ? info.name : "");
- rows.add(Row.from(
- Cell.from(Span.styled(vanishName, dimStyle)),
- Cell.from(Span.styled("", dimStyle)),
- Cell.from(Span.styled("", dimStyle)),
- Cell.from(Span.styled("", dimStyle)),
- Cell.from(Span.styled("", dimStyle)),
- Cell.from(Span.styled("", dimStyle)),
- Cell.from(Span.styled("", dimStyle)),
- Cell.from(Span.styled("", dimStyle)),
- Cell.from(Span.styled("", dimStyle)),
- Cell.from(Span.styled("", dimStyle)),
- Cell.from(Span.styled("", dimStyle)),
- Cell.from(Span.styled("", dimStyle)),
- Cell.from(Span.styled("", dimStyle)),
- Cell.from(Span.styled("", dimStyle))).style(rowBg));
- } else {
- String platformIcon = TuiIcons.runtimeIcon(info.platform != null ? info.platform : "");
- String nameText = platformIcon + " " + (info.name != null ? info.name : "");
- List<Span> nameSpans = new ArrayList<>();
- nameSpans.add(Span.styled(nameText, Theme.info()));
- if (info.devMode) {
- nameSpans.add(Span.styled(" [dev]", Theme.label()));
- }
- Line nameLine = Line.from(nameSpans);
- Style failStyle = info.failed > 0 ? Theme.error().bold() : Style.EMPTY;
- String throughputDisplay = info.throughput;
- if (throughputDisplay == null || "0.00".equals(throughputDisplay)) {
- LinkedList<Long> tpHist = throughputHistory.get(info.pid);
- if (tpHist != null && !tpHist.isEmpty()) {
- long tp = tpHist.getLast();
- if (tp > 0) {
- throughputDisplay = String.format(java.util.Locale.US, "%.2f", (double) tp);
- }
- }
- }
- if (ctx.ratePerMinute) {
- throughputDisplay = TuiHelper.throughputPerMinute(throughputDisplay);
- }
- rows.add(Row.from(
- Cell.from(nameLine),
- rightCell(info.exchangesTotal > 0 ? formatDurationMs(info.meanTime) : "", 8,
- TuiHelper.topTimeStyle(info.meanTime)),
- rightCell(info.exchangesTotal > 0 ? formatDurationMs(info.maxTime) : "", 8,
- TuiHelper.topTimeStyle(info.maxTime)),
- rightCell(info.exchangesTotal > 0 ? formatDurationMs(info.minTime) : "", 8),
- rightCell(info.exchangesTotal > 0 ? formatDurationMs(info.lastTime) : "", 8),
- rightCell(info.deltaTime != 0 ? formatDurationMs(info.deltaTime) : "", 8,
- TuiHelper.topDeltaStyle(info.deltaTime)),
- rightCell(info.p50Time >= 0 ? formatDurationMs(info.p50Time) : "", 8),
- rightCell(info.p95Time >= 0 ? formatDurationMs(info.p95Time) : "", 8),
- rightCell(info.p99Time >= 0 ? formatDurationMs(info.p99Time) : "", 8),
- rightCell(String.valueOf(info.exchangesTotal), 8),
- rightCell(String.valueOf(info.failed), 6, failStyle),
- rightCell(String.valueOf(info.inflight), 8),
- rightCell(throughputDisplay != null ? throughputDisplay : "", 8),
- rightCell(TuiHelper.formatLoad(
- info.inflightLoad01, info.inflightLoad05, info.inflightLoad15), 12))
- .style(rowBg));
- }
- }
-
- header = Row.from(
- Cell.from(Span.styled("NAME", Style.EMPTY.bold())),
- rightCell(topSortLabel("MEAN", "mean"), 8, topSortStyle("mean")),
- rightCell(topSortLabel("MAX", "max"), 8, topSortStyle("max")),
- rightCell(topSortLabel("MIN", "min"), 8, topSortStyle("min")),
- rightCell(topSortLabel("LAST", "last"), 8, topSortStyle("last")),
- rightCell(topSortLabel("DELTA", "delta"), 8, topSortStyle("delta")),
- rightCell(topSortLabel("P50", "p50"), 8, topSortStyle("p50")),
- rightCell(topSortLabel("P95", "p95"), 8, topSortStyle("p95")),
- rightCell(topSortLabel("P99", "p99"), 8, topSortStyle("p99")),
- rightCell("TOTAL", 8, Style.EMPTY.bold()),
- rightCell("FAIL", 6, Style.EMPTY.bold()),
- rightCell("INFLIGHT", 8, Style.EMPTY.bold()),
- rightCell(ctx.ratePerMinute ? "MSG/M" : "MSG/S", 8, Style.EMPTY.bold()),
- rightCell("LOAD", 12, Style.EMPTY.bold()));
-
- widths = new Constraint[] {
- Constraint.fill(),
- Constraint.length(8),
- Constraint.length(8),
- Constraint.length(8),
- Constraint.length(8),
- Constraint.length(8),
- Constraint.length(8),
- Constraint.length(8),
- Constraint.length(8),
- Constraint.length(8),
- Constraint.length(6),
- Constraint.length(8),
- Constraint.length(8),
- Constraint.length(13)
- };
- } else {
- boolean hasPercentiles = infos.stream().anyMatch(i -> i.p50Time >= 0);
- long maxTotal = infos.stream().mapToLong(i -> i.exchangesTotal).max().orElse(0);
- long maxFailed = infos.stream().mapToLong(i -> i.failed).max().orElse(0);
- int tw = Math.max(numWidth(maxTotal), 6);
- int fw = Math.max(numWidth(maxFailed), 6);
- for (IntegrationInfo info : infos) {
- boolean isEven = (rowIndex++ % 2 == 0);
- Style rowBg = isEven ? Style.EMPTY.bg(Theme.zebra()) : Style.EMPTY;
-
- if (info.phantom) {
- String platformIcon = TuiIcons.runtimeIcon(info.platform != null ? info.platform : "");
- String nameText = platformIcon + " " + (info.name != null ? info.name : "");
- rows.add(Row.from(
- Cell.from(Span.styled("-", Theme.muted())),
- Cell.from(Span.styled(nameText, Theme.info())),
- Cell.from(Span.styled("", Theme.muted())),
- Cell.from(Span.styled("", Theme.muted())),
- Cell.from(Span.styled(TuiIcons.STOPPED + " Stopped", Theme.error())),
- Cell.from(Span.styled("", Theme.muted())),
- Cell.from(Span.styled("", Theme.muted())),
- Cell.from(Span.styled("", Theme.muted())),
- Cell.from(Span.styled("", Theme.muted())),
- Cell.from(Span.styled("", Theme.muted())),
- Cell.from(Span.styled("", Theme.muted()))).style(rowBg));
- } else if (info.vanishing) {
- long elapsed = System.currentTimeMillis() - info.vanishStart;
- float fade = 1.0f - Math.min(1.0f, (float) elapsed / VANISH_DURATION_MS);
- int gray = (int) (100 * fade);
- Style dimStyle = Style.EMPTY.fg(Color.indexed(232 + Math.min(gray / 4, 23)));
-
- String vanishName = TuiIcons.labeled(TuiIcons.CAMEL, info.name != null ? info.name : "");
- rows.add(Row.from(
- Cell.from(Span.styled(info.pid, dimStyle)),
- Cell.from(Span.styled(vanishName, dimStyle)),
- Cell.from(Span.styled("", dimStyle)),
- Cell.from(Span.styled("", dimStyle)),
- Cell.from(Span.styled(TuiIcons.STOPPED + " Stopped", Theme.error().dim())),
- Cell.from(Span.styled("", dimStyle)),
- Cell.from(Span.styled("", dimStyle)),
- Cell.from(Span.styled("", dimStyle)),
- Cell.from(Span.styled("", dimStyle)),
- Cell.from(Span.styled("", dimStyle)),
- Cell.from(Span.styled("", dimStyle))).style(rowBg));
- } else {
- String stateText = extractState(info.state);
- if (stoppingPids.contains(info.pid) || "Terminating".equals(stateText)) {
- stateText = "Stopping";
- } else if ("Terminated".equals(stateText)) {
- stateText = "Stopped";
- } else if ("Running".equals(stateText) && info.routeStarted == 0 && info.routeTotal > 0) {
- stateText = "Stopped";
- }
- Style statusStyle = switch (stateText) {
- case "Started", "Running" -> Theme.success();
- case "Stopped" -> Theme.error();
- default -> Theme.warning();
- };
-
- Style failStyle = info.failed > 0 ? Theme.error().bold() : Style.EMPTY;
-
- boolean hasDoc = info.readmeFiles != null && !info.readmeFiles.isEmpty();
- if (!hasDoc) {
- hasDoc = hasReadmeInSourceDir(info);
- }
- String platformIcon = TuiIcons.runtimeIcon(info.platform != null ? info.platform : "");
- String nameText = platformIcon + " " + (info.name != null ? info.name : "");
- List<Span> nameSpans = new ArrayList<>();
- nameSpans.add(Span.styled(nameText, Theme.info()));
- if (info.devMode) {
- nameSpans.add(Span.styled(" [dev]", Theme.label()));
- }
- if (hasDoc) {
- nameSpans.add(Span.styled(" " + TuiIcons.README, Style.EMPTY));
- }
- Line nameLine = Line.from(nameSpans);
- String throughputDisplay = info.throughput;
- if (throughputDisplay == null || "0.00".equals(throughputDisplay)) {
- LinkedList<Long> tpHist = throughputHistory.get(info.pid);
- if (tpHist != null && !tpHist.isEmpty()) {
- long tp = tpHist.getLast();
- if (tp > 0) {
- throughputDisplay = String.format(java.util.Locale.US, "%.2f", (double) tp);
- }
- }
- }
- if (ctx.ratePerMinute) {
- throughputDisplay = TuiHelper.throughputPerMinute(throughputDisplay);
- }
- String timingCol;
- if (hasPercentiles && info.p50Time >= 0) {
- timingCol = formatDurationMs(info.p50Time) + "/" + formatDurationMs(info.p95Time) + "/"
- + formatDurationMs(info.p99Time);
- } else if (info.exchangesTotal > 0) {
- timingCol = formatDurationMs(info.minTime) + "/" + formatDurationMs(info.maxTime) + "/"
- + formatDurationMs(info.meanTime);
- } else {
- timingCol = "";
- }
- Line totalCell = info.sinceLastCompleted != null
- ? Line.from(Span.raw(String.format("%" + tw + "d", info.exchangesTotal)),
- Span.styled(" (" + info.sinceLastCompleted + ")", Theme.muted()))
- : Line.from(Span.raw(String.format("%" + tw + "d", info.exchangesTotal)));
- Line failCell = info.sinceLastFailed != null
- ? Line.from(Span.styled(String.format("%" + fw + "d", info.failed), failStyle),
- Span.styled(" (" + info.sinceLastFailed + ")", Theme.muted()))
- : Line.from(Span.styled(String.format("%" + fw + "d", info.failed), failStyle));
-
- rows.add(Row.from(
- Cell.from(info.pid),
- Cell.from(nameLine),
- Cell.from(info.camelVersion != null ? info.camelVersion : ""),
- centerCell(info.ready != null ? info.ready : "", 7),
- Cell.from(Span.styled(stateText, statusStyle)),
- rightCell(info.routeStarted + "/" + info.routeTotal, 7),
- rightCell(throughputDisplay != null ? throughputDisplay : "", 8),
- Cell.from(totalCell),
- Cell.from(failCell),
- rightCell(timingCol, 20),
- Cell.from(buildPercentileBarLine(info.p50Time, info.p95Time, info.p99Time, 10))).style(rowBg));
- }
- }
-
- String timingHeader = hasPercentiles ? "P50/P95/P99" : "MIN/MAX/MEAN";
- header = Row.from(
- Cell.from(Span.styled(sortLabel("PID", "pid"), sortStyle("pid"))),
- Cell.from(Span.styled(sortLabel("NAME", "name"), sortStyle("name"))),
- Cell.from(Span.styled(sortLabel("VERSION", "version"), sortStyle("version"))),
- centerCell("READY", 7, Style.EMPTY.bold()),
- Cell.from(Span.styled(sortLabel("STATUS", "status"), sortStyle("status"))),
- rightCell("ROUTE", 7, Style.EMPTY.bold()),
- rightCell(ctx.ratePerMinute ? "MSG/M" : "MSG/S", 8, Style.EMPTY.bold()),
- centerCell(sortLabel("TOTAL", "total"), 14, sortStyle("total")),
- centerCell(sortLabel("FAIL", "fail"), 14, sortStyle("fail")),
- rightCell(timingHeader, 20, Style.EMPTY.bold()),
- Cell.from(""));
-
- widths = new Constraint[] {
- Constraint.length(8),
- Constraint.fill(),
- Constraint.length(16),
- Constraint.length(7),
- Constraint.length(10),
- Constraint.length(7),
- Constraint.length(8),
- Constraint.length(14),
- Constraint.length(14),
- Constraint.min(20),
- Constraint.length(0)
- };
- }
+ TableSpec spec = topMode ? buildTopModeTable(infos) : buildOverviewTable(infos);
String integrationTitle = infraCount > 0 ? " Integrations " : " Overview ";
Style intBorderStyle = ctx.paneBorder(!infraFocused);
Style intTitleStyle = infraFocused ? Style.EMPTY.fg(Theme.accent()) : Theme.title();
Table.Builder tableBuilder = Table.builder()
- .rows(rows)
- .header(header)
- .widths(widths)
+ .rows(spec.rows())
+ .header(spec.header())
+ .widths(spec.widths())
.highlightSpacing(Table.HighlightSpacing.ALWAYS)
.block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
.borderStyle(intBorderStyle)
@@ -600,166 +341,449 @@ class OverviewTab extends AbstractTab {
}
if (hasSparkline && chunks.size() > 1) {
- Rect chartTotalArea = chunks.get(chunks.size() - 1);
-
- List<Rect> chartHSplit = Layout.horizontal()
- .constraints(Constraint.fill(), Constraint.length(34))
- .split(chartTotalArea);
- Rect chartArea = chartHSplit.get(0);
- Rect infoArea = chartHSplit.get(1);
-
- Rect chartInner = Block.builder().borders(Borders.ALL).build().inner(chartArea);
-
- List<Rect> vChunks = Layout.vertical()
- .constraints(Constraint.fill(), Constraint.length(1))
- .split(chartInner);
-
- List<Rect> hChunks = Layout.horizontal()
- .constraints(Constraint.length(4), Constraint.fill())
- .split(vChunks.get(0));
-
- Rect barChartArea = hChunks.get(1);
-
- int innerBarCols = Math.max(2, barChartArea.width());
- int renderPoints = Math.min(MAX_SPARKLINE_POINTS, innerBarCols / 2);
-
- long[] mergedTotal = new long[renderPoints];
- long[] mergedFailed = new long[renderPoints];
- final String chartPid = chartMode == CHART_SINGLE
- ? (infraFocused ? lastIntegrationPid : ctx.selectedPid) : null;
- for (int i = 0; i < renderPoints; i++) {
- for (Map.Entry<String, LinkedList<Long>> e : throughputHistory.entrySet()) {
- if (chartPid == null || chartPid.equals(e.getKey())) {
- int idx = e.getValue().size() - renderPoints + i;
- if (idx >= 0) {
- mergedTotal[i] += e.getValue().get(idx);
- }
- }
+ renderThroughputChart(frame, chunks.get(chunks.size() - 1));
+ } else if (showInfraDetail) {
+ renderInfraInfoPanel(frame, chunks.get(chunks.size() - 1), infraSel);
+ }
+ }
+
+ /**
+ * The rows, header and column widths of the integrations table for the current display mode.
+ */
+ private record TableSpec(List<Row> rows, Row header, Constraint[] widths) {
+ }
+
+ /**
+ * Rows, header and column widths for the integrations table in top mode (processing time percentiles).
+ */
+ private TableSpec buildTopModeTable(List<IntegrationInfo> infos) {
+ List<Row> rows = new ArrayList<>();
+ int rowIndex = 0;
+ for (IntegrationInfo info : infos) {
+ boolean isEven = (rowIndex++ % 2 == 0);
+ Style rowBg = isEven ? Style.EMPTY.bg(Theme.zebra()) : Style.EMPTY;
+
+ if (info.vanishing) {
+ long elapsed = System.currentTimeMillis() - info.vanishStart;
+ float fade = 1.0f - Math.min(1.0f, (float) elapsed / VANISH_DURATION_MS);
+ int gray = (int) (100 * fade);
+ Style dimStyle = Style.EMPTY.fg(Color.indexed(232 + Math.min(gray / 4, 23)));
+ String vanishName = TuiIcons.labeled(TuiIcons.CAMEL, info.name != null ? info.name : "");
+ rows.add(Row.from(
+ Cell.from(Span.styled(vanishName, dimStyle)),
+ Cell.from(Span.styled("", dimStyle)),
+ Cell.from(Span.styled("", dimStyle)),
+ Cell.from(Span.styled("", dimStyle)),
+ Cell.from(Span.styled("", dimStyle)),
+ Cell.from(Span.styled("", dimStyle)),
+ Cell.from(Span.styled("", dimStyle)),
+ Cell.from(Span.styled("", dimStyle)),
+ Cell.from(Span.styled("", dimStyle)),
+ Cell.from(Span.styled("", dimStyle)),
+ Cell.from(Span.styled("", dimStyle)),
+ Cell.from(Span.styled("", dimStyle)),
+ Cell.from(Span.styled("", dimStyle)),
+ Cell.from(Span.styled("", dimStyle))).style(rowBg));
+ } else {
+ String platformIcon = TuiIcons.runtimeIcon(info.platform != null ? info.platform : "");
+ String nameText = platformIcon + " " + (info.name != null ? info.name : "");
+ List<Span> nameSpans = new ArrayList<>();
+ nameSpans.add(Span.styled(nameText, Theme.info()));
+ if (info.devMode) {
+ nameSpans.add(Span.styled(" [dev]", Theme.label()));
}
- for (Map.Entry<String, LinkedList<Long>> e : failedHistory.entrySet()) {
- if (chartPid == null || chartPid.equals(e.getKey())) {
- int idx = e.getValue().size() - renderPoints + i;
- if (idx >= 0) {
- mergedFailed[i] += e.getValue().get(idx);
+ Line nameLine = Line.from(nameSpans);
+ Style failStyle = info.failed > 0 ? Theme.error().bold() : Style.EMPTY;
+ String throughputDisplay = info.throughput;
+ if (throughputDisplay == null || "0.00".equals(throughputDisplay)) {
+ LinkedList<Long> tpHist = throughputHistory.get(info.pid);
+ if (tpHist != null && !tpHist.isEmpty()) {
+ long tp = tpHist.getLast();
+ if (tp > 0) {
+ throughputDisplay = String.format(java.util.Locale.US, "%.2f", (double) tp);
}
}
}
+ if (ctx.ratePerMinute) {
+ throughputDisplay = TuiHelper.throughputPerMinute(throughputDisplay);
+ }
+ rows.add(Row.from(
+ Cell.from(nameLine),
+ rightCell(info.exchangesTotal > 0 ? formatDurationMs(info.meanTime) : "", 8,
+ TuiHelper.topTimeStyle(info.meanTime)),
+ rightCell(info.exchangesTotal > 0 ? formatDurationMs(info.maxTime) : "", 8,
+ TuiHelper.topTimeStyle(info.maxTime)),
+ rightCell(info.exchangesTotal > 0 ? formatDurationMs(info.minTime) : "", 8),
+ rightCell(info.exchangesTotal > 0 ? formatDurationMs(info.lastTime) : "", 8),
+ rightCell(info.deltaTime != 0 ? formatDurationMs(info.deltaTime) : "", 8,
+ TuiHelper.topDeltaStyle(info.deltaTime)),
+ rightCell(info.p50Time >= 0 ? formatDurationMs(info.p50Time) : "", 8),
+ rightCell(info.p95Time >= 0 ? formatDurationMs(info.p95Time) : "", 8),
+ rightCell(info.p99Time >= 0 ? formatDurationMs(info.p99Time) : "", 8),
+ rightCell(String.valueOf(info.exchangesTotal), 8),
+ rightCell(String.valueOf(info.failed), 6, failStyle),
+ rightCell(String.valueOf(info.inflight), 8),
+ rightCell(throughputDisplay != null ? throughputDisplay : "", 8),
+ rightCell(TuiHelper.formatLoad(
+ info.inflightLoad01, info.inflightLoad05, info.inflightLoad15), 12))
+ .style(rowBg));
}
+ }
- long rawMax = 0;
- for (long v : mergedTotal) {
- rawMax = Math.max(rawMax, v);
- }
- long maxTp = MetricsCollector.niceMax(rawMax);
- long curTp = mergedTotal[renderPoints - 1];
- // Clamp failed to total so the title matches the chart bars (total comes from
- // EWMA while failed is still delta-based, so failed can momentarily exceed total)
- long curFailed = Math.min(mergedFailed[renderPoints - 1], curTp);
- long curOk = Math.max(0, curTp - curFailed);
-
- // Format throughput values unscaled for display
- String curTpFmt = MetricsCollector.formatThroughput(curTp);
- String curOkFmt = MetricsCollector.formatThroughput(curOk);
- String curFailFmt = MetricsCollector.formatThroughput(curFailed);
-
- Line titleLine;
- if (chartMode == CHART_SINGLE && chartPid != null) {
- IntegrationInfo chartSel = ctx.data.get().stream()
- .filter(ii -> chartPid.equals(ii.pid)).findFirst().orElse(null);
- String chartName = chartSel != null ? TuiHelper.truncate(chartSel.name, 30) : chartPid;
- titleLine = Line.from(
- Span.raw(" ["),
- Span.styled(chartName, Theme.label().bold()),
- Span.raw(String.format("] Rate: %s msg/s ", curTpFmt)),
- Span.styled("■", Theme.success()),
- Span.raw(String.format(" ok:%s ", curOkFmt)),
- Span.styled("■", Theme.error()),
- Span.raw(String.format(" fail:%s ", curFailFmt)));
+ Row header = Row.from(
+ Cell.from(Span.styled("NAME", Style.EMPTY.bold())),
+ rightCell(topSortLabel("MEAN", "mean"), 8, topSortStyle("mean")),
+ rightCell(topSortLabel("MAX", "max"), 8, topSortStyle("max")),
+ rightCell(topSortLabel("MIN", "min"), 8, topSortStyle("min")),
+ rightCell(topSortLabel("LAST", "last"), 8, topSortStyle("last")),
+ rightCell(topSortLabel("DELTA", "delta"), 8, topSortStyle("delta")),
+ rightCell(topSortLabel("P50", "p50"), 8, topSortStyle("p50")),
+ rightCell(topSortLabel("P95", "p95"), 8, topSortStyle("p95")),
+ rightCell(topSortLabel("P99", "p99"), 8, topSortStyle("p99")),
+ rightCell("TOTAL", 8, Style.EMPTY.bold()),
+ rightCell("FAIL", 6, Style.EMPTY.bold()),
+ rightCell("INFLIGHT", 8, Style.EMPTY.bold()),
+ rightCell(ctx.ratePerMinute ? "MSG/M" : "MSG/S", 8, Style.EMPTY.bold()),
+ rightCell("LOAD", 12, Style.EMPTY.bold()));
+
+ Constraint[] widths = new Constraint[] {
+ Constraint.fill(),
+ Constraint.length(8),
+ Constraint.length(8),
+ Constraint.length(8),
+ Constraint.length(8),
+ Constraint.length(8),
+ Constraint.length(8),
+ Constraint.length(8),
+ Constraint.length(8),
+ Constraint.length(8),
+ Constraint.length(6),
+ Constraint.length(8),
+ Constraint.length(8),
+ Constraint.length(13)
+ };
+ return new TableSpec(rows, header, widths);
+ }
+
+ /**
+ * Rows, header and column widths for the integrations table in the default overview mode.
+ */
+ private TableSpec buildOverviewTable(List<IntegrationInfo> infos) {
+ List<Row> rows = new ArrayList<>();
+ int rowIndex = 0;
+ boolean hasPercentiles = infos.stream().anyMatch(i -> i.p50Time >= 0);
+ long maxTotal = infos.stream().mapToLong(i -> i.exchangesTotal).max().orElse(0);
+ long maxFailed = infos.stream().mapToLong(i -> i.failed).max().orElse(0);
+ int tw = Math.max(numWidth(maxTotal), 6);
+ int fw = Math.max(numWidth(maxFailed), 6);
+ for (IntegrationInfo info : infos) {
+ boolean isEven = (rowIndex++ % 2 == 0);
+ Style rowBg = isEven ? Style.EMPTY.bg(Theme.zebra()) : Style.EMPTY;
+
+ if (info.phantom) {
+ String platformIcon = TuiIcons.runtimeIcon(info.platform != null ? info.platform : "");
+ String nameText = platformIcon + " " + (info.name != null ? info.name : "");
+ rows.add(Row.from(
+ Cell.from(Span.styled("-", Theme.muted())),
+ Cell.from(Span.styled(nameText, Theme.info())),
+ Cell.from(Span.styled("", Theme.muted())),
+ Cell.from(Span.styled("", Theme.muted())),
+ Cell.from(Span.styled(TuiIcons.STOPPED + " Stopped", Theme.error())),
+ Cell.from(Span.styled("", Theme.muted())),
+ Cell.from(Span.styled("", Theme.muted())),
+ Cell.from(Span.styled("", Theme.muted())),
+ Cell.from(Span.styled("", Theme.muted())),
+ Cell.from(Span.styled("", Theme.muted())),
+ Cell.from(Span.styled("", Theme.muted()))).style(rowBg));
+ } else if (info.vanishing) {
+ long elapsed = System.currentTimeMillis() - info.vanishStart;
+ float fade = 1.0f - Math.min(1.0f, (float) elapsed / VANISH_DURATION_MS);
+ int gray = (int) (100 * fade);
+ Style dimStyle = Style.EMPTY.fg(Color.indexed(232 + Math.min(gray / 4, 23)));
+
+ String vanishName = TuiIcons.labeled(TuiIcons.CAMEL, info.name != null ? info.name : "");
+ rows.add(Row.from(
+ Cell.from(Span.styled(info.pid, dimStyle)),
+ Cell.from(Span.styled(vanishName, dimStyle)),
+ Cell.from(Span.styled("", dimStyle)),
+ Cell.from(Span.styled("", dimStyle)),
+ Cell.from(Span.styled(TuiIcons.STOPPED + " Stopped", Theme.error().dim())),
+ Cell.from(Span.styled("", dimStyle)),
+ Cell.from(Span.styled("", dimStyle)),
+ Cell.from(Span.styled("", dimStyle)),
+ Cell.from(Span.styled("", dimStyle)),
+ Cell.from(Span.styled("", dimStyle)),
+ Cell.from(Span.styled("", dimStyle))).style(rowBg));
} else {
- titleLine = Line.from(
- Span.raw(String.format(" [All] Rate: %s msg/s ", curTpFmt)),
- Span.styled("■", Theme.success()),
- Span.raw(String.format(" ok:%s ", curOkFmt)),
- Span.styled("■", Theme.error()),
- Span.raw(String.format(" fail:%s ", curFailFmt)));
- }
+ String stateText = extractState(info.state);
+ if (stoppingPids.contains(info.pid) || "Terminating".equals(stateText)) {
+ stateText = "Stopping";
+ } else if ("Terminated".equals(stateText)) {
+ stateText = "Stopped";
+ } else if ("Running".equals(stateText) && info.routeStarted == 0 && info.routeTotal > 0) {
+ stateText = "Stopped";
+ }
+ Style statusStyle = switch (stateText) {
+ case "Started", "Running" -> Theme.success();
+ case "Stopped" -> Theme.error();
+ default -> Theme.warning();
+ };
- Block chartBlock = Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
- .title(Title.from(titleLine)).build();
- frame.renderWidget(chartBlock, chartArea);
-
- List<BarGroup> groups = new ArrayList<>();
- for (int i = 0; i < renderPoints; i++) {
- long failed = Math.min(mergedFailed[i], mergedTotal[i]);
- long ok = Math.max(0, mergedTotal[i] - failed);
- groups.add(BarGroup.of(
- Bar.builder().value(ok).textValue("").style(Theme.success())
- .build(),
- Bar.builder().value(failed).textValue("").style(Theme.error()).build()));
- }
+ Style failStyle = info.failed > 0 ? Theme.error().bold() : Style.EMPTY;
- BarChart barChart = BarChart.builder()
- .data(groups)
- .max(maxTp)
- .barWidth(1)
- .barGap(0)
- .groupGap(0)
- .build();
-
- frame.renderWidget(barChart, barChartArea);
-
- int barRows = vChunks.get(0).height();
- List<Line> yLines = new ArrayList<>();
- Style dimStyle = Style.EMPTY.dim();
- for (int row = 0; row < barRows; row++) {
- if (row == 0) {
- yLines.add(
- Line.from(Span.styled(String.format("%3s", MetricsCollector.formatThroughput(maxTp)), dimStyle)));
- } else if (barRows > 4 && row == barRows / 2) {
- yLines.add(Line
- .from(Span.styled(String.format("%3s", MetricsCollector.formatThroughput(maxTp / 2)), dimStyle)));
- } else if (row == barRows - 1) {
- yLines.add(Line.from(Span.styled(" 0", dimStyle)));
- } else {
- yLines.add(Line.from(""));
+ boolean hasDoc = info.readmeFiles != null && !info.readmeFiles.isEmpty();
+ if (!hasDoc) {
+ hasDoc = hasReadmeInSourceDir(info);
}
- }
- frame.renderWidget(Paragraph.builder().text(Text.from(yLines)).build(), hChunks.get(0));
-
- if (!vChunks.get(1).isEmpty()) {
- int barInnerStartX = barChartArea.x();
- int xAxisY = vChunks.get(1).y();
- int step;
- if (renderPoints <= 20) {
- step = 5;
- } else if (renderPoints <= 80) {
- step = 10;
- } else {
- step = 20;
+ String platformIcon = TuiIcons.runtimeIcon(info.platform != null ? info.platform : "");
+ String nameText = platformIcon + " " + (info.name != null ? info.name : "");
+ List<Span> nameSpans = new ArrayList<>();
+ nameSpans.add(Span.styled(nameText, Theme.info()));
+ if (info.devMode) {
+ nameSpans.add(Span.styled(" [dev]", Theme.label()));
+ }
+ if (hasDoc) {
+ nameSpans.add(Span.styled(" " + TuiIcons.README, Style.EMPTY));
}
- // "now" label at the right edge
- int nowX = barInnerStartX + (renderPoints - 1) * 2;
- if (nowX + 3 <= barChartArea.right()) {
- frame.buffer().setString(nowX, xAxisY, "now", dimStyle);
+ Line nameLine = Line.from(nameSpans);
+ String throughputDisplay = info.throughput;
+ if (throughputDisplay == null || "0.00".equals(throughputDisplay)) {
+ LinkedList<Long> tpHist = throughputHistory.get(info.pid);
+ if (tpHist != null && !tpHist.isEmpty()) {
+ long tp = tpHist.getLast();
+ if (tp > 0) {
+ throughputDisplay = String.format(java.util.Locale.US, "%.2f", (double) tp);
+ }
+ }
+ }
+ if (ctx.ratePerMinute) {
+ throughputDisplay = TuiHelper.throughputPerMinute(throughputDisplay);
+ }
+ String timingCol;
+ if (hasPercentiles && info.p50Time >= 0) {
+ timingCol = formatDurationMs(info.p50Time) + "/" + formatDurationMs(info.p95Time) + "/"
+ + formatDurationMs(info.p99Time);
+ } else if (info.exchangesTotal > 0) {
+ timingCol = formatDurationMs(info.minTime) + "/" + formatDurationMs(info.maxTime) + "/"
+ + formatDurationMs(info.meanTime);
+ } else {
+ timingCol = "";
}
- // round time markers from right to left
- for (int s = step; s <= renderPoints; s += step) {
- int groupIdx = renderPoints - 1 - s;
- if (groupIdx < 0) {
- break;
+ Line totalCell = info.sinceLastCompleted != null
+ ? Line.from(Span.raw(String.format("%" + tw + "d", info.exchangesTotal)),
+ Span.styled(" (" + info.sinceLastCompleted + ")", Theme.muted()))
+ : Line.from(Span.raw(String.format("%" + tw + "d", info.exchangesTotal)));
+ Line failCell = info.sinceLastFailed != null
+ ? Line.from(Span.styled(String.format("%" + fw + "d", info.failed), failStyle),
+ Span.styled(" (" + info.sinceLastFailed + ")", Theme.muted()))
+ : Line.from(Span.styled(String.format("%" + fw + "d", info.failed), failStyle));
+
+ rows.add(Row.from(
+ Cell.from(info.pid),
+ Cell.from(nameLine),
+ Cell.from(info.camelVersion != null ? info.camelVersion : ""),
+ centerCell(info.ready != null ? info.ready : "", 7),
+ Cell.from(Span.styled(stateText, statusStyle)),
+ rightCell(info.routeStarted + "/" + info.routeTotal, 7),
+ rightCell(throughputDisplay != null ? throughputDisplay : "", 8),
+ Cell.from(totalCell),
+ Cell.from(failCell),
+ rightCell(timingCol, 20),
+ Cell.from(buildPercentileBarLine(info.p50Time, info.p95Time, info.p99Time, 10))).style(rowBg));
+ }
+ }
+
+ String timingHeader = hasPercentiles ? "P50/P95/P99" : "MIN/MAX/MEAN";
+ Row header = Row.from(
+ Cell.from(Span.styled(sortLabel("PID", "pid"), sortStyle("pid"))),
+ Cell.from(Span.styled(sortLabel("NAME", "name"), sortStyle("name"))),
+ Cell.from(Span.styled(sortLabel("VERSION", "version"), sortStyle("version"))),
+ centerCell("READY", 7, Style.EMPTY.bold()),
+ Cell.from(Span.styled(sortLabel("STATUS", "status"), sortStyle("status"))),
+ rightCell("ROUTE", 7, Style.EMPTY.bold()),
+ rightCell(ctx.ratePerMinute ? "MSG/M" : "MSG/S", 8, Style.EMPTY.bold()),
+ centerCell(sortLabel("TOTAL", "total"), 14, sortStyle("total")),
+ centerCell(sortLabel("FAIL", "fail"), 14, sortStyle("fail")),
+ rightCell(timingHeader, 20, Style.EMPTY.bold()),
+ Cell.from(""));
+
+ Constraint[] widths = new Constraint[] {
+ Constraint.length(8),
+ Constraint.fill(),
+ Constraint.length(16),
+ Constraint.length(7),
+ Constraint.length(10),
+ Constraint.length(7),
+ Constraint.length(8),
+ Constraint.length(14),
+ Constraint.length(14),
+ Constraint.min(20),
+ Constraint.length(0)
+ };
+ return new TableSpec(rows, header, widths);
+ }
+
+ /**
+ * Renders the throughput bar chart (ok/failed per second over time) with its y axis, time markers and the info
+ * panel to its right.
+ */
+ private void renderThroughputChart(Frame frame, Rect chartTotalArea) {
+
+ List<Rect> chartHSplit = Layout.horizontal()
+ .constraints(Constraint.fill(), Constraint.length(34))
+ .split(chartTotalArea);
+ Rect chartArea = chartHSplit.get(0);
+ Rect infoArea = chartHSplit.get(1);
+
+ Rect chartInner = Block.builder().borders(Borders.ALL).build().inner(chartArea);
+
+ List<Rect> vChunks = Layout.vertical()
+ .constraints(Constraint.fill(), Constraint.length(1))
+ .split(chartInner);
+
+ List<Rect> hChunks = Layout.horizontal()
+ .constraints(Constraint.length(4), Constraint.fill())
+ .split(vChunks.get(0));
+
+ Rect barChartArea = hChunks.get(1);
+
+ int innerBarCols = Math.max(2, barChartArea.width());
+ int renderPoints = Math.min(MAX_SPARKLINE_POINTS, innerBarCols / 2);
+
+ long[] mergedTotal = new long[renderPoints];
+ long[] mergedFailed = new long[renderPoints];
+ final String chartPid = chartMode == CHART_SINGLE
+ ? (infraFocused ? lastIntegrationPid : ctx.selectedPid) : null;
+ for (int i = 0; i < renderPoints; i++) {
+ for (Map.Entry<String, LinkedList<Long>> e : throughputHistory.entrySet()) {
+ if (chartPid == null || chartPid.equals(e.getKey())) {
+ int idx = e.getValue().size() - renderPoints + i;
+ if (idx >= 0) {
+ mergedTotal[i] += e.getValue().get(idx);
}
- String label = "-" + s + "s";
- int markerX = barInnerStartX + groupIdx * 2;
- if (markerX + label.length() <= barChartArea.right()) {
- frame.buffer().setString(markerX, xAxisY, label, dimStyle);
+ }
+ }
+ for (Map.Entry<String, LinkedList<Long>> e : failedHistory.entrySet()) {
+ if (chartPid == null || chartPid.equals(e.getKey())) {
+ int idx = e.getValue().size() - renderPoints + i;
+ if (idx >= 0) {
+ mergedFailed[i] += e.getValue().get(idx);
}
}
}
+ }
- renderInfoPanel(frame, infoArea);
- } else if (showInfraDetail) {
- renderInfraInfoPanel(frame, chunks.get(chunks.size() - 1), infraSel);
+ long rawMax = 0;
+ for (long v : mergedTotal) {
+ rawMax = Math.max(rawMax, v);
+ }
+ long maxTp = MetricsCollector.niceMax(rawMax);
+ long curTp = mergedTotal[renderPoints - 1];
+ // Clamp failed to total so the title matches the chart bars (total comes from
+ // EWMA while failed is still delta-based, so failed can momentarily exceed total)
+ long curFailed = Math.min(mergedFailed[renderPoints - 1], curTp);
+ long curOk = Math.max(0, curTp - curFailed);
+
+ // Format throughput values unscaled for display
+ String curTpFmt = MetricsCollector.formatThroughput(curTp);
+ String curOkFmt = MetricsCollector.formatThroughput(curOk);
+ String curFailFmt = MetricsCollector.formatThroughput(curFailed);
+
+ Line titleLine;
+ if (chartMode == CHART_SINGLE && chartPid != null) {
+ IntegrationInfo chartSel = ctx.data.get().stream()
+ .filter(ii -> chartPid.equals(ii.pid)).findFirst().orElse(null);
+ String chartName = chartSel != null ? TuiHelper.truncate(chartSel.name, 30) : chartPid;
+ titleLine = Line.from(
+ Span.raw(" ["),
+ Span.styled(chartName, Theme.label().bold()),
+ Span.raw(String.format("] Rate: %s msg/s ", curTpFmt)),
+ Span.styled("■", Theme.success()),
+ Span.raw(String.format(" ok:%s ", curOkFmt)),
+ Span.styled("■", Theme.error()),
+ Span.raw(String.format(" fail:%s ", curFailFmt)));
+ } else {
+ titleLine = Line.from(
+ Span.raw(String.format(" [All] Rate: %s msg/s ", curTpFmt)),
+ Span.styled("■", Theme.success()),
+ Span.raw(String.format(" ok:%s ", curOkFmt)),
+ Span.styled("■", Theme.error()),
+ Span.raw(String.format(" fail:%s ", curFailFmt)));
+ }
+
+ Block chartBlock = Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
+ .title(Title.from(titleLine)).build();
+ frame.renderWidget(chartBlock, chartArea);
+
+ List<BarGroup> groups = new ArrayList<>();
+ for (int i = 0; i < renderPoints; i++) {
+ long failed = Math.min(mergedFailed[i], mergedTotal[i]);
+ long ok = Math.max(0, mergedTotal[i] - failed);
+ groups.add(BarGroup.of(
+ Bar.builder().value(ok).textValue("").style(Theme.success())
+ .build(),
+ Bar.builder().value(failed).textValue("").style(Theme.error()).build()));
+ }
+
+ BarChart barChart = BarChart.builder()
+ .data(groups)
+ .max(maxTp)
+ .barWidth(1)
+ .barGap(0)
+ .groupGap(0)
+ .build();
+
+ frame.renderWidget(barChart, barChartArea);
+
+ int barRows = vChunks.get(0).height();
+ List<Line> yLines = new ArrayList<>();
+ Style dimStyle = Style.EMPTY.dim();
+ for (int row = 0; row < barRows; row++) {
+ if (row == 0) {
+ yLines.add(
+ Line.from(Span.styled(String.format("%3s", MetricsCollector.formatThroughput(maxTp)), dimStyle)));
+ } else if (barRows > 4 && row == barRows / 2) {
+ yLines.add(Line
+ .from(Span.styled(String.format("%3s", MetricsCollector.formatThroughput(maxTp / 2)), dimStyle)));
+ } else if (row == barRows - 1) {
+ yLines.add(Line.from(Span.styled(" 0", dimStyle)));
+ } else {
+ yLines.add(Line.from(""));
+ }
}
+ frame.renderWidget(Paragraph.builder().text(Text.from(yLines)).build(), hChunks.get(0));
+
+ if (!vChunks.get(1).isEmpty()) {
+ int barInnerStartX = barChartArea.x();
+ int xAxisY = vChunks.get(1).y();
+ int step;
+ if (renderPoints <= 20) {
+ step = 5;
+ } else if (renderPoints <= 80) {
+ step = 10;
+ } else {
+ step = 20;
+ }
+ // "now" label at the right edge
+ int nowX = barInnerStartX + (renderPoints - 1) * 2;
+ if (nowX + 3 <= barChartArea.right()) {
+ frame.buffer().setString(nowX, xAxisY, "now", dimStyle);
+ }
+ // round time markers from right to left
+ for (int s = step; s <= renderPoints; s += step) {
+ int groupIdx = renderPoints - 1 - s;
+ if (groupIdx < 0) {
+ break;
+ }
+ String label = "-" + s + "s";
+ int markerX = barInnerStartX + groupIdx * 2;
+ if (markerX + label.length() <= barChartArea.right()) {
+ frame.buffer().setString(markerX, xAxisY, label, dimStyle);
+ }
+ }
+ }
+
+ renderInfoPanel(frame, infoArea);
}
private void renderInfoPanel(Frame frame, Rect area) {
@@ -1186,14 +1210,6 @@ class OverviewTab extends AbstractTab {
return sortStyle(column, topSort);
}
- private static int numWidth(long... values) {
- long max = 0;
- for (long v : values) {
- max = Math.max(max, Math.abs(v));
- }
- return Math.max(String.valueOf(max).length(), 1);
- }
-
private int infraSortCompare(InfraInfo a, InfraInfo b) {
if (a.vanishing != b.vanishing) {
return a.vanishing ? 1 : -1;
@@ -1261,150 +1277,7 @@ class OverviewTab extends AbstractTab {
@Override
public String getHelpText() {
- return """
- # Overview
-
- The Overview tab shows all running Camel integrations at a glance.
- Select an integration to monitor it in detail on the other tabs.
-
- ## Integration List
-
- Each row represents one running Camel integration:
-
- - **PID** — Process ID of the JVM running this integration
- - **NAME** — Name of the integration (from the route file or application configuration). Example: `camel-demo`, `my-app`
- - **VERSION** — Camel version the integration is running on (e.g., `4.21.0`)
- - **STATUS** — Current lifecycle state: `Running` (processing messages), `Started` (ready), or `Stopped`
- - **AGE** — How long the integration has been running (e.g., `2m30s`, `1h15m`)
- - **MSG/S** or **MSG/M** — Messages processed per second or per minute (current throughput). The rate unit can be configured in settings. This is the overall rate across all routes
- - **TOTAL** — Total number of exchanges (messages) processed since the integration started
- - **FAIL** — Number of exchanges that ended with an unhandled error
- - **INFLIGHT** — Exchanges currently being processed right now. A consistently high inflight count may indicate slow downstream services
- - **SINCE-LAST** — Time since the last exchange activity, shown as up to three values separated by `/`: started/completed/failed. For example, `1s/3s/1m14s` means the last exchange started 1s ago, the last completed 3s ago, and the last failure was 1m14s ago. Values are omitted when there is no activity of that type
-
- ## Percentile Latency (P50/P95/P99)
-
- When **Extended** statistics level is enabled, a timing column shows
- percentile latencies instead of MIN/MAX/MEAN:
-
- - **P50** — Median processing time (50th percentile). Half of all exchanges completed faster than this
- - **P95** — 95th percentile. 95% of exchanges completed faster than this. Useful for SLA monitoring
- - **P99** — 99th percentile. Only 1% of exchanges were slower. Highlights worst-case tail latency
-
- Percentiles are computed over a sliding window of recent exchanges, making
- them more meaningful than MIN/MAX for understanding real-world performance.
- With very few messages (e.g., 10), P95 and P99 may equal the MAX value since
- there aren't enough samples to differentiate.
-
- To enable Extended statistics, set `camel.main.load-statistics-enabled = true`
- in your application configuration. Without Extended statistics, the column
- shows MIN/MAX/MEAN instead.
-
- ## Example Screen
-
- ```
- PID NAME VERSION STATUS AGE MSG/S TOTAL FAIL INFLIGHT P50/P95/P99 SINCE-LAST
- 73136 camel-demo 4.21.0 Running 2m30s 1.00 142 0 0 1/10/31 0s
- 64628 my-routes 4.21.0 Running 1h15m 0.50 2850 3 1 2/15/42 2s
- ```
-
- ## Sparkline Chart
-
- The sparkline at the bottom shows message throughput over time.
- Each vertical bar represents one sample interval:
-
- - **Green bars** — successful messages per second
- - **Red bars** — failed messages per second
-
- This helps you spot traffic patterns, load spikes, and error bursts
- at a glance. A sudden drop in throughput may indicate a problem with
- an external system. A spike in red bars means errors are occurring.
-
- ## Info Panel
-
- When an integration is selected, the right panel shows:
-
- - **Runtime** — Camel runtime type (e.g., `Camel`, `Spring Boot`, `Quarkus`)
- - **Profile** — Active profile (`dev` for development, `prod` for production)
- - **Reload** — Number of times routes have been live-reloaded (useful in `dev` mode where file changes trigger automatic reload)
- - **JVM** — Java version and vendor (e.g., `21.0.5 Azul Systems`)
- - **Uptime** — Integration uptime
- - **Heap** — JVM heap memory usage (used / committed). See the Memory tab for details
- - **Meta** — Metaspace usage (where Java class definitions are stored)
- - **Threads** — JVM thread count
- - **Load avg** — Three comma-separated load averages over 1-minute, 5-minute, and 15-minute windows. These measure message throughput, not CPU usage — similar concept to Unix load average but for Camel exchanges
-
- ## Dev/Infra Services
-
- Dev/Infra Services are backing services (databases, message brokers, etc.)
- running in containers via Docker or Podman. This is similar to Quarkus Dev Services
- and Spring Boot Development-time Services.
-
- For example, if your integration uses Kafka, you can start a Kafka broker
- directly from the TUI using `F2` → `Run Dev/Infra Service...` → select `kafka`.
- The service starts in the background and appears in a separate panel below
- the integrations list with its own columns:
-
- - **PID** — Container process ID
- - **SERVICE** — Service alias (e.g., `kafka`, `postgres`)
- - **VERSION** — Service version
- - **PORT** — Primary port number
- - **STATUS** — Running or Stopped
-
- When running an example that requires infra services, they are started
- automatically before the example launches.
-
- Press `Tab` to toggle focus between the integrations and infra panels.
- Each panel remembers its own selection. Press `d` while the infra panel
- is focused to toggle a details panel showing the service's connection
- properties (host, port, etc.).
-
- Sorting applies to whichever panel is focused. Press `s` to cycle through
- the sort columns of the focused panel (integration columns: PID, NAME,
- VERSION, STATUS, TOTAL, FAIL; infra columns: SERVICE, VERSION, PORT, STATUS).
-
- ## Shell and AI Panels
-
- Two panels can be opened on top of any tab. Opening one closes the other.
-
- - `F6` — **Shell**: an embedded Camel JBang shell where you can run any `camel`
- command (`run`, `infra`, `cmd send`, `get`, ...) without leaving the TUI. Press
- `F6` again to close it and `Shift+F6` to cycle its height. `PgUp/PgDn` scrolls
- the output and `Up/Down` recalls earlier commands
- - `F8` — **AI Prompt**: ask questions about the running integrations in plain
- English. The AI answers by calling the same tools an MCP agent uses (status,
- routes, log, errors, traces, infra services). It needs an API key in the
- environment or a local Ollama model; `F2` → `AI & MCP` → `Setup AI` explains
- the options. Press `F8` again to close it and `Shift+F8` to cycle its height.
- Inside the panel `Ctrl+U` toggles the AI usage view, `Ctrl+P` switches
- provider or model, `Ctrl+Y` copies the last answer and `Ctrl+E` exports the
- conversation. Type `/help` for the slash commands
-
- Where the panels open (bottom or top) is configured in Settings
- (`F2` → `Settings...` → `Panel Position`). The tool calls and answers of the AI panel
- are recorded in `F2` → `AI & MCP` → `AI Log`.
-
- ## Keys
-
- - `Up/Down` — select within the focused panel
- - `Tab` — switch between integrations and infra panels (when infra services are running)
- - `d` — toggle infra service details panel (when infra panel is focused)
- - `Enter` — view routes for selected integration
- - `s` — cycle sort column (for the focused panel)
- - `S` — reverse sort order
- - `F2` — actions menu (includes theme toggle, go to tab, etc.)
- - `F3` — switch integration
- - `F6` — toggle the embedded shell panel
- - `F8` — toggle the AI prompt panel
-
- ## Run
-
- - `F10` — open run popup (run, stop routes, start routes, restart, stop, kill)
- - `q` — quit the TUI
-
- By default, stop/restart actions show a confirmation dialog before executing.
- You can turn this off in Settings (`F2` → `Settings...` → `Confirm`).
- """;
+ return DocHelper.loadHelpText("overview");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ProducersTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ProducersTab.java
index c337ff0fbf72..559eedbf7058 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ProducersTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/ProducersTab.java
@@ -158,29 +158,7 @@ class ProducersTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Producers
-
- Producers are the **output** side of a Camel route. They send data to
- external systems (message brokers, HTTP endpoints, databases, files, etc.).
-
- Unlike consumers (one per route), a route can have multiple producers
- — each `.to()` or `.toD()` call in the route creates a producer.
-
- ## Table Columns
-
- - **ROUTE** — The route this producer belongs to
- - **STATUS** — Producer state: `Started` (running normally) or `Stopped`
- - **TYPE** — The Camel component type (e.g., `Kafka`, `Http`, `Log`, `Seda`)
- - **REMOTE** — Whether this producer sends to a remote system (`Yes`) or is in-process (`No`)
- - **URI** — The full endpoint URI (e.g., `kafka://my-topic`, `log://mylogger`)
-
- ## Keys
-
- - `Up/Down` — select producer
- - `s` — cycle sort column
- - `S` — reverse sort order
- """;
+ return DocHelper.loadHelpText("producers");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/RouteControllerTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/RouteControllerTab.java
index 492cfdb34ccf..cef2806a1813 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/RouteControllerTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/RouteControllerTab.java
@@ -213,40 +213,7 @@ class RouteControllerTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Route Controller
-
- Shows the status of the Camel route controller. The route controller manages
- route startup and can automatically restart routes that fail to start.
-
- There are two types of route controllers:
-
- - **Default** — Routes are started in order and a failure stops the context.
- This tab shows "Route controller: Default (not supervised)" in this case.
- - **Supervising** — Routes that fail to start are retried with exponential
- backoff. The controller tracks attempts and manages restart scheduling.
-
- When using the supervised controller and all routes start successfully,
- the tab shows "All routes started successfully".
-
- ## Table Columns
-
- - **ROUTE** — The route ID
- - **STATUS** — Route state: `Started`, `Stopped`, or other lifecycle states
- - **SUPERVISING** — Supervision status (e.g., `Active` when the route is being
- restarted by the controller)
- - **ATTEMPTS** — Number of restart attempts so far
- - **LAST** — Time since the last restart attempt
- - **NEXT** — Time until the next scheduled restart attempt
- - **URI** — The route's consumer endpoint URI. If the route has a startup error,
- the error message is shown here instead (in red)
-
- ## Keys
-
- - `Up/Down` — select route
- - `s` — cycle sort column
- - `S` — reverse sort order
- """;
+ return DocHelper.loadHelpText("route-controller");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/RoutesTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/RoutesTab.java
index 0d25a4927d81..9b200d9d57f7 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/RoutesTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/RoutesTab.java
@@ -16,25 +16,16 @@
*/
package org.apache.camel.dsl.jbang.core.commands.tui;
-import java.net.URISyntaxException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedHashMap;
import java.util.List;
-import java.util.Map;
-import java.util.Set;
import dev.tamboui.layout.Constraint;
import dev.tamboui.layout.Layout;
import dev.tamboui.layout.Rect;
-import dev.tamboui.markdown.MarkdownView;
-import dev.tamboui.style.Color;
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;
@@ -51,12 +42,6 @@ import dev.tamboui.widgets.table.Cell;
import dev.tamboui.widgets.table.Row;
import dev.tamboui.widgets.table.Table;
import dev.tamboui.widgets.table.TableState;
-import org.apache.camel.catalog.CamelCatalog;
-import org.apache.camel.dsl.jbang.core.common.CatalogLoader;
-import org.apache.camel.tooling.model.BaseOptionModel;
-import org.apache.camel.tooling.model.ComponentModel;
-import org.apache.camel.tooling.model.EipModel;
-import org.apache.camel.util.TimeUtils;
import org.apache.camel.util.json.JsonArray;
import org.apache.camel.util.json.JsonObject;
@@ -100,14 +85,7 @@ class RoutesTab extends AbstractTab {
// Detail panel (d toggle in drill-down mode)
private boolean detailMode;
- private int detailScroll;
- private String lastDetailNodeId;
- private volatile JsonObject cachedRouteDetail;
- private volatile String cachedRouteDetailId;
- private volatile String detailLoadingRouteId;
- private volatile boolean detailLoading;
- private final Map<String, CamelCatalog> catalogCache = new HashMap<>();
- private final Set<String> catalogLoadFailed = new HashSet<>();
+ private final DiagramDetailSupport detail = new DiagramDetailSupport(ctx, diagram);
// Go-to node popup (g in drill-down mode)
private final GotoNodePopup gotoNodePopup = new GotoNodePopup();
@@ -162,6 +140,18 @@ class RoutesTab extends AbstractTab {
return true;
}
+ if (handleDiagramKeys(ke)) {
+ return true;
+ }
+ return handleTableKeys(ke);
+ }
+
+ /**
+ * Keys while the topology or route diagram is shown: node navigation, jump back to topology, detail panel
+ * scrolling, diagram scrolling, metrics/external/description toggles, and Enter to jump into a linked route or
+ * drill down.
+ */
+ private boolean handleDiagramKeys(KeyEvent ke) {
// Topology node navigation
if (diagram.isShowDiagram() && topologyMode && diagram.hasDiagramData()
&& !diagram.getNodeBoxes().isEmpty()) {
@@ -251,11 +241,11 @@ class RoutesTab extends AbstractTab {
// Detail panel scrolling (PgUp/PgDn when detail mode is active)
if (detailMode && diagram.isShowDiagram() && !topologyMode) {
if (ke.isPageUp() || ke.isKey(KeyCode.PAGE_UP)) {
- detailScroll = Math.max(0, detailScroll - 5);
+ detail.scrollBy(-5);
return true;
}
if (ke.isPageDown() || ke.isKey(KeyCode.PAGE_DOWN)) {
- detailScroll += 5;
+ detail.scrollBy(5);
return true;
}
}
@@ -333,7 +323,14 @@ class RoutesTab extends AbstractTab {
}
return true;
}
+ return false;
+ }
+ /**
+ * Keys in the route table view (sort, top mode, description, open diagram, source, start/stop, suspend/resume) plus
+ * the detail and go-to-node toggles in drill-down mode.
+ */
+ private boolean handleTableKeys(KeyEvent ke) {
// Sort (only when not in diagram)
if (!diagram.isShowDiagram() && ke.isChar('s')) {
if (routeTopMode) {
@@ -378,11 +375,7 @@ class RoutesTab extends AbstractTab {
if (diagram.isShowDiagram() && !topologyMode && !diagram.getEipNodeBoxes().isEmpty()
&& ke.isCharIgnoreCase('d')) {
detailMode = !detailMode;
- detailScroll = 0;
- cachedRouteDetail = null;
- cachedRouteDetailId = null;
- detailLoadingRouteId = null;
- detailLoading = false;
+ detail.reset();
return true;
}
@@ -414,7 +407,6 @@ class RoutesTab extends AbstractTab {
toggleRouteSuspendResume();
return true;
}
-
return false;
}
@@ -555,76 +547,7 @@ class RoutesTab extends AbstractTab {
// Fullscreen diagram mode
if (diagram.isShowDiagram() && diagram.hasDiagramData()) {
- if (topologyMode && diagram.hasNativeLayout()) {
- String selectedRouteId = diagram.getSelectedRouteId();
- Line title;
- if (info.name != null) {
- title = Line.from(
- Span.raw(" Topology ["),
- Span.styled(info.name, Theme.label().bold()),
- Span.raw("] "));
- } else {
- title = Line.from(Span.raw(" Topology "));
- }
- if (selectedRouteId != null && area.width() > 60) {
- infoPanelWidth = Math.max(10, Math.min(infoPanelWidth, area.width() - 20));
- List<Rect> hChunks = Layout.horizontal()
- .constraints(Constraint.length(infoPanelWidth), Constraint.fill())
- .split(area);
- hSplit.setBorderPos(hChunks.get(1).x());
- renderInfoPanel(frame, hChunks.get(0), info, selectedRouteId);
- diagram.renderNativeDiagram(frame, hChunks.get(1), title, diagramMetrics);
- } else {
- diagram.renderNativeDiagram(frame, area, title, diagramMetrics);
- }
- return;
- } else if (!topologyMode && drillDownRouteId != null
- && diagram.getRouteLayout(drillDownRouteId) != null) {
- Line title = buildBreadcrumbTitle();
- var routeLayout = diagram.getRouteLayout(drillDownRouteId);
-
- // Split for detail panel when active
- Rect diagramArea = area;
- if (detailMode) {
- int detailH = Math.max(5, area.height() * 60 / 100);
- List<Rect> vChunks = Layout.vertical()
- .constraints(Constraint.fill(), Constraint.length(detailH))
- .split(area);
- diagramArea = vChunks.get(0);
- renderDetail(frame, vChunks.get(1), info);
- }
-
- if (diagramArea.width() > 60) {
- infoPanelWidth = Math.max(10, Math.min(infoPanelWidth, diagramArea.width() - 20));
- List<Rect> hChunks = Layout.horizontal()
- .constraints(Constraint.length(infoPanelWidth), Constraint.fill())
- .split(diagramArea);
- hSplit.setBorderPos(hChunks.get(1).x());
- renderEipInfoPanel(frame, hChunks.get(0));
- diagram.renderNativeRouteDiagram(
- frame, hChunks.get(1), title, diagramMetrics, drillDownRouteId, routeLayout);
- } else {
- diagram.renderNativeRouteDiagram(frame, diagramArea, title, diagramMetrics, drillDownRouteId,
- routeLayout);
- }
-
- // Render go-to popup overlay
- if (gotoNodePopup.isVisible()) {
- gotoNodePopup.render(frame, area);
- }
- return;
- }
-
- // Fallback: loading or no native layout yet
- frame.renderWidget(
- Paragraph.builder()
- .text(Text.from(Line.from(Span.styled(
- "Loading diagram...",
- Style.EMPTY.dim()))))
- .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
- .title(" Diagram ").build())
- .build(),
- area);
+ renderDiagramView(frame, area, info);
return;
}
@@ -640,197 +563,7 @@ class RoutesTab extends AbstractTab {
.split(area);
// Routes table
- Table routeTable;
- if (routeTopMode) {
- List<Row> routeRows = new ArrayList<>();
- for (RouteInfo route : sortedRoutes) {
- Style failStyle = route.failed > 0
- ? Theme.error().bold()
- : Style.EMPTY;
-
- routeRows.add(Row.from(
- Cell.from(Span.styled(route.routeId != null ? route.routeId : "", Style.EMPTY.fg(Theme.accent()))),
- Cell.from(routeFromLabel(route)),
- rightCell(route.total > 0 ? formatDurationMs(route.meanTime) : "", 8,
- topTimeStyle(route.meanTime)),
- rightCell(route.total > 0 ? formatDurationMs(route.maxTime) : "", 8,
- topTimeStyle(route.maxTime)),
- rightCell(route.total > 0 ? formatDurationMs(route.minTime) : "", 8),
- rightCell(route.total > 0 ? formatDurationMs(route.lastTime) : "", 8),
- rightCell(route.deltaTime != 0 ? formatDurationMs(route.deltaTime) : "", 8,
- topDeltaStyle(route.deltaTime)),
- rightCell(route.p50Time >= 0 ? formatDurationMs(route.p50Time) : "", 8),
- rightCell(route.p95Time >= 0 ? formatDurationMs(route.p95Time) : "", 8),
- rightCell(route.p99Time >= 0 ? formatDurationMs(route.p99Time) : "", 8),
- rightCell(String.valueOf(route.total), 8),
- rightCell(String.valueOf(route.failed), 6, failStyle),
- rightCell(String.valueOf(route.inflight), 8),
- rightCell(formatThroughput(route.throughput), 8),
- rightCell(formatLoad(route.load01, route.load05, route.load15), 12)));
- }
-
- IntegrationInfo selTop = ctx.findSelectedIntegration();
- if (selTop != null && selTop.exchangesTotal > 0) {
- Style ts = Theme.label();
- routeRows.add(Row.from(
- Cell.from(Span.styled("GLOBAL", ts)),
- Cell.from(""),
- rightCell(formatDurationMs(selTop.meanTime), 8, ts),
- rightCell(formatDurationMs(selTop.maxTime), 8, ts),
- rightCell(formatDurationMs(selTop.minTime), 8, ts),
- rightCell(formatDurationMs(selTop.lastTime), 8, ts),
- rightCell(selTop.deltaTime != 0 ? formatDurationMs(selTop.deltaTime) : "", 8, ts),
- rightCell(selTop.p50Time >= 0 ? formatDurationMs(selTop.p50Time) : "", 8, ts),
- rightCell(selTop.p95Time >= 0 ? formatDurationMs(selTop.p95Time) : "", 8, ts),
- rightCell(selTop.p99Time >= 0 ? formatDurationMs(selTop.p99Time) : "", 8, ts),
- rightCell(String.valueOf(selTop.exchangesTotal), 8, ts),
- rightCell(String.valueOf(selTop.failed), 6,
- selTop.failed > 0 ? Theme.error().bold() : ts),
- rightCell(String.valueOf(selTop.inflight), 8, ts),
- rightCell(formatThroughput(selTop.throughput), 8, ts),
- rightCell(TuiHelper.formatLoad(
- selTop.inflightLoad01, selTop.inflightLoad05, selTop.inflightLoad15), 12, ts)));
- }
-
- routeTable = Table.builder()
- .rows(routeRows)
- .header(Row.from(
- Cell.from(Span.styled("ROUTE", Style.EMPTY.bold())),
- Cell.from(Span.styled("FROM", Style.EMPTY.bold())),
- rightCell(routeTopSortLabel("MEAN", "mean"), 8, routeTopSortStyle("mean")),
- rightCell(routeTopSortLabel("MAX", "max"), 8, routeTopSortStyle("max")),
- rightCell(routeTopSortLabel("MIN", "min"), 8, routeTopSortStyle("min")),
- rightCell(routeTopSortLabel("LAST", "last"), 8, routeTopSortStyle("last")),
- rightCell(routeTopSortLabel("DELTA", "delta"), 8, routeTopSortStyle("delta")),
- rightCell(routeTopSortLabel("P50", "p50"), 8, routeTopSortStyle("p50")),
- rightCell(routeTopSortLabel("P95", "p95"), 8, routeTopSortStyle("p95")),
- rightCell(routeTopSortLabel("P99", "p99"), 8, routeTopSortStyle("p99")),
- rightCell("TOTAL", 8, Style.EMPTY.bold()),
- rightCell("FAIL", 6, Style.EMPTY.bold()),
- rightCell("INFLIGHT", 8, Style.EMPTY.bold()),
- rightCell(ctx.ratePerMinute ? "MSG/M" : "MSG/S", 8, Style.EMPTY.bold()),
- rightCell("LOAD", 12, Style.EMPTY.bold())))
- .widths(
- Constraint.length(24),
- Constraint.fill(),
- Constraint.length(8),
- Constraint.length(8),
- Constraint.length(8),
- Constraint.length(8),
- Constraint.length(8),
- Constraint.length(8),
- Constraint.length(8),
- Constraint.length(8),
- Constraint.length(8),
- Constraint.length(6),
- Constraint.length(8),
- Constraint.length(8),
- Constraint.length(13))
- .highlightStyle(Theme.selectionBg())
- .highlightSpacing(Table.HighlightSpacing.ALWAYS)
- .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
- .title(" Routes ").build())
- .build();
- } else {
- boolean hasPercentiles = sortedRoutes.stream().anyMatch(r -> r.p50Time >= 0);
-
- long maxTotal = sortedRoutes.stream().mapToLong(r -> r.total).max().orElse(0);
- long maxFailed = sortedRoutes.stream().mapToLong(r -> r.failed).max().orElse(0);
- int tw = Math.max(numWidth(maxTotal), 6);
- int fw = Math.max(numWidth(maxFailed), 6);
-
- List<Row> routeRows = new ArrayList<>();
- for (RouteInfo route : sortedRoutes) {
- Style stateStyle = "Started".equals(route.state)
- ? Theme.success()
- : Theme.error();
-
- Style failStyle = route.failed > 0
- ? Theme.error().bold()
- : Style.EMPTY;
-
- String timingCol;
- if (hasPercentiles && route.p50Time >= 0) {
- timingCol = formatDurationMs(route.p50Time) + "/" + formatDurationMs(route.p95Time) + "/"
- + formatDurationMs(route.p99Time);
- } else if (route.total > 0) {
- timingCol = formatDurationMs(route.minTime) + "/" + formatDurationMs(route.maxTime) + "/"
- + formatDurationMs(route.meanTime);
- } else {
- timingCol = "";
- }
-
- Line totalCell = route.sinceLastCompleted != null
- ? Line.from(Span.raw(String.format("%" + tw + "d", route.total)),
- Span.styled(" (" + route.sinceLastCompleted + ")", Theme.muted()))
- : Line.from(Span.raw(String.format("%" + tw + "d", route.total)));
- Line failCell = route.sinceLastFailed != null
- ? Line.from(Span.styled(String.format("%" + fw + "d", route.failed), failStyle),
- Span.styled(" (" + route.sinceLastFailed + ")", Theme.muted()))
- : Line.from(Span.styled(String.format("%" + fw + "d", route.failed), failStyle));
-
- routeRows.add(Row.from(
- Cell.from(Span.styled(route.routeId != null ? route.routeId : "", Style.EMPTY.fg(Theme.accent()))),
- Cell.from(routeFromLabel(route)),
- Cell.from(Span.styled(route.state != null ? route.state : "", stateStyle)),
- rightCell(formatThroughput(route.throughput), 8),
- Cell.from(totalCell),
- Cell.from(failCell),
- rightCell(timingCol, 20),
- Cell.from(buildPercentileBarLine(route.p50Time, route.p95Time, route.p99Time, 10))));
- }
-
- IntegrationInfo selDef = ctx.findSelectedIntegration();
- if (selDef != null && selDef.exchangesTotal > 0) {
- Style ts = Theme.label();
- String totalTimingCol;
- if (hasPercentiles && selDef.p50Time >= 0) {
- totalTimingCol = formatDurationMs(selDef.p50Time) + "/" + formatDurationMs(selDef.p95Time) + "/"
- + formatDurationMs(selDef.p99Time);
- } else {
- totalTimingCol = formatDurationMs(selDef.minTime) + "/" + formatDurationMs(selDef.maxTime) + "/"
- + formatDurationMs(selDef.meanTime);
- }
- routeRows.add(Row.from(
- Cell.from(Span.styled("GLOBAL", ts)),
- Cell.from(""),
- Cell.from(""),
- rightCell(formatThroughput(selDef.throughput), 8, ts),
- Cell.from(Span.styled(String.format("%" + tw + "d", selDef.exchangesTotal), ts)),
- Cell.from(Span.styled(String.format("%" + fw + "d", selDef.failed),
- selDef.failed > 0 ? Theme.error().bold() : ts)),
- rightCell(totalTimingCol, 20, ts),
- Cell.from(buildPercentileBarLine(selDef.p50Time, selDef.p95Time, selDef.p99Time, 10))));
- }
-
- String timingHeader = hasPercentiles ? "P50/P95/P99" : "MIN/MAX/MEAN";
-
- routeTable = Table.builder()
- .rows(routeRows)
- .header(Row.from(
- Cell.from(Span.styled(routeSortLabel("ROUTE", "name"), routeSortStyle("name"))),
- Cell.from(Span.styled(routeSortLabel("FROM", "from"), routeSortStyle("from"))),
- Cell.from(Span.styled(routeSortLabel("STATUS", "status"), routeSortStyle("status"))),
- rightCell(ctx.ratePerMinute ? "MSG/M" : "MSG/S", 8, Style.EMPTY.bold()),
- centerCell(routeSortLabel("TOTAL", "total"), 14, routeSortStyle("total")),
- centerCell(routeSortLabel("FAIL", "failed"), 14, routeSortStyle("failed")),
- rightCell(timingHeader, 20, Style.EMPTY.bold()),
- Cell.from("")))
- .widths(
- Constraint.length(24),
- Constraint.fill(),
- Constraint.length(10),
- Constraint.length(10),
- Constraint.length(14),
- Constraint.length(14),
- Constraint.min(20),
- Constraint.length(12))
- .highlightStyle(Theme.selectionBg())
- .highlightSpacing(Table.HighlightSpacing.ALWAYS)
- .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
- .title(" Routes ").build())
- .build();
- }
+ Table routeTable = routeTopMode ? buildRouteTopTable(sortedRoutes) : buildRouteTable(sortedRoutes);
lastRouteTableArea = chunks.get(0);
vSplit.setBorderPos(chunks.get(1).y());
@@ -856,6 +589,281 @@ class RoutesTab extends AbstractTab {
}
}
+ /**
+ * Fullscreen topology or route diagram with its info/detail side panels and breadcrumb title.
+ */
+ private void renderDiagramView(Frame frame, Rect area, IntegrationInfo info) {
+ if (topologyMode && diagram.hasNativeLayout()) {
+ String selectedRouteId = diagram.getSelectedRouteId();
+ Line title;
+ if (info.name != null) {
+ title = Line.from(
+ Span.raw(" Topology ["),
+ Span.styled(info.name, Theme.label().bold()),
+ Span.raw("] "));
+ } else {
+ title = Line.from(Span.raw(" Topology "));
+ }
+ if (selectedRouteId != null && area.width() > 60) {
+ infoPanelWidth = Math.max(10, Math.min(infoPanelWidth, area.width() - 20));
+ List<Rect> hChunks = Layout.horizontal()
+ .constraints(Constraint.length(infoPanelWidth), Constraint.fill())
+ .split(area);
+ hSplit.setBorderPos(hChunks.get(1).x());
+ detail.renderRouteInfoPanel(frame, hChunks.get(0), info, selectedRouteId);
+ diagram.renderNativeDiagram(frame, hChunks.get(1), title, diagramMetrics);
+ } else {
+ diagram.renderNativeDiagram(frame, area, title, diagramMetrics);
+ }
+ return;
+ } else if (!topologyMode && drillDownRouteId != null
+ && diagram.getRouteLayout(drillDownRouteId) != null) {
+ Line title = DiagramDetailSupport.buildBreadcrumbTitle(routeNavigationStack, drillDownRouteId);
+ var routeLayout = diagram.getRouteLayout(drillDownRouteId);
+
+ // Split for detail panel when active
+ Rect diagramArea = area;
+ if (detailMode) {
+ int detailH = Math.max(5, area.height() * 60 / 100);
+ List<Rect> vChunks = Layout.vertical()
+ .constraints(Constraint.fill(), Constraint.length(detailH))
+ .split(area);
+ diagramArea = vChunks.get(0);
+ detail.renderDetail(frame, vChunks.get(1), info, drillDownRouteId);
+ }
+
+ if (diagramArea.width() > 60) {
+ infoPanelWidth = Math.max(10, Math.min(infoPanelWidth, diagramArea.width() - 20));
+ List<Rect> hChunks = Layout.horizontal()
+ .constraints(Constraint.length(infoPanelWidth), Constraint.fill())
+ .split(diagramArea);
+ hSplit.setBorderPos(hChunks.get(1).x());
+ detail.renderEipInfoPanel(frame, hChunks.get(0), drillDownRouteId);
+ diagram.renderNativeRouteDiagram(
+ frame, hChunks.get(1), title, diagramMetrics, drillDownRouteId, routeLayout);
+ } else {
+ diagram.renderNativeRouteDiagram(frame, diagramArea, title, diagramMetrics, drillDownRouteId,
+ routeLayout);
+ }
+
+ // Render go-to popup overlay
+ if (gotoNodePopup.isVisible()) {
+ gotoNodePopup.render(frame, area);
+ }
+ return;
+ }
+
+ // Fallback: loading or no native layout yet
+ frame.renderWidget(
+ Paragraph.builder()
+ .text(Text.from(Line.from(Span.styled(
+ "Loading diagram...",
+ Style.EMPTY.dim()))))
+ .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
+ .title(" Diagram ").build())
+ .build(),
+ area);
+ }
+
+ /**
+ * The routes table in top mode (processing time columns).
+ */
+ private Table buildRouteTopTable(List<RouteInfo> sortedRoutes) {
+ List<Row> routeRows = new ArrayList<>();
+ for (RouteInfo route : sortedRoutes) {
+ Style failStyle = route.failed > 0
+ ? Theme.error().bold()
+ : Style.EMPTY;
+
+ routeRows.add(Row.from(
+ Cell.from(Span.styled(route.routeId != null ? route.routeId : "", Style.EMPTY.fg(Theme.accent()))),
+ Cell.from(routeFromLabel(route)),
+ rightCell(route.total > 0 ? formatDurationMs(route.meanTime) : "", 8,
+ topTimeStyle(route.meanTime)),
+ rightCell(route.total > 0 ? formatDurationMs(route.maxTime) : "", 8,
+ topTimeStyle(route.maxTime)),
+ rightCell(route.total > 0 ? formatDurationMs(route.minTime) : "", 8),
+ rightCell(route.total > 0 ? formatDurationMs(route.lastTime) : "", 8),
+ rightCell(route.deltaTime != 0 ? formatDurationMs(route.deltaTime) : "", 8,
+ topDeltaStyle(route.deltaTime)),
+ rightCell(route.p50Time >= 0 ? formatDurationMs(route.p50Time) : "", 8),
+ rightCell(route.p95Time >= 0 ? formatDurationMs(route.p95Time) : "", 8),
+ rightCell(route.p99Time >= 0 ? formatDurationMs(route.p99Time) : "", 8),
+ rightCell(String.valueOf(route.total), 8),
+ rightCell(String.valueOf(route.failed), 6, failStyle),
+ rightCell(String.valueOf(route.inflight), 8),
+ rightCell(formatThroughput(route.throughput), 8),
+ rightCell(formatLoad(route.load01, route.load05, route.load15), 12)));
+ }
+
+ IntegrationInfo selTop = ctx.findSelectedIntegration();
+ if (selTop != null && selTop.exchangesTotal > 0) {
+ Style ts = Theme.label();
+ routeRows.add(Row.from(
+ Cell.from(Span.styled("GLOBAL", ts)),
+ Cell.from(""),
+ rightCell(formatDurationMs(selTop.meanTime), 8, ts),
+ rightCell(formatDurationMs(selTop.maxTime), 8, ts),
+ rightCell(formatDurationMs(selTop.minTime), 8, ts),
+ rightCell(formatDurationMs(selTop.lastTime), 8, ts),
+ rightCell(selTop.deltaTime != 0 ? formatDurationMs(selTop.deltaTime) : "", 8, ts),
+ rightCell(selTop.p50Time >= 0 ? formatDurationMs(selTop.p50Time) : "", 8, ts),
+ rightCell(selTop.p95Time >= 0 ? formatDurationMs(selTop.p95Time) : "", 8, ts),
+ rightCell(selTop.p99Time >= 0 ? formatDurationMs(selTop.p99Time) : "", 8, ts),
+ rightCell(String.valueOf(selTop.exchangesTotal), 8, ts),
+ rightCell(String.valueOf(selTop.failed), 6,
+ selTop.failed > 0 ? Theme.error().bold() : ts),
+ rightCell(String.valueOf(selTop.inflight), 8, ts),
+ rightCell(formatThroughput(selTop.throughput), 8, ts),
+ rightCell(TuiHelper.formatLoad(
+ selTop.inflightLoad01, selTop.inflightLoad05, selTop.inflightLoad15), 12, ts)));
+ }
+
+ return Table.builder()
+ .rows(routeRows)
+ .header(Row.from(
+ Cell.from(Span.styled("ROUTE", Style.EMPTY.bold())),
+ Cell.from(Span.styled("FROM", Style.EMPTY.bold())),
+ rightCell(routeTopSortLabel("MEAN", "mean"), 8, routeTopSortStyle("mean")),
+ rightCell(routeTopSortLabel("MAX", "max"), 8, routeTopSortStyle("max")),
+ rightCell(routeTopSortLabel("MIN", "min"), 8, routeTopSortStyle("min")),
+ rightCell(routeTopSortLabel("LAST", "last"), 8, routeTopSortStyle("last")),
+ rightCell(routeTopSortLabel("DELTA", "delta"), 8, routeTopSortStyle("delta")),
+ rightCell(routeTopSortLabel("P50", "p50"), 8, routeTopSortStyle("p50")),
+ rightCell(routeTopSortLabel("P95", "p95"), 8, routeTopSortStyle("p95")),
+ rightCell(routeTopSortLabel("P99", "p99"), 8, routeTopSortStyle("p99")),
+ rightCell("TOTAL", 8, Style.EMPTY.bold()),
+ rightCell("FAIL", 6, Style.EMPTY.bold()),
+ rightCell("INFLIGHT", 8, Style.EMPTY.bold()),
+ rightCell(ctx.ratePerMinute ? "MSG/M" : "MSG/S", 8, Style.EMPTY.bold()),
+ rightCell("LOAD", 12, Style.EMPTY.bold())))
+ .widths(
+ Constraint.length(24),
+ Constraint.fill(),
+ Constraint.length(8),
+ Constraint.length(8),
+ Constraint.length(8),
+ Constraint.length(8),
+ Constraint.length(8),
+ Constraint.length(8),
+ Constraint.length(8),
+ Constraint.length(8),
+ Constraint.length(8),
+ Constraint.length(6),
+ Constraint.length(8),
+ Constraint.length(8),
+ Constraint.length(13))
+ .highlightStyle(Theme.selectionBg())
+ .highlightSpacing(Table.HighlightSpacing.ALWAYS)
+ .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
+ .title(" Routes ").build())
+ .build();
+ }
+
+ /**
+ * The routes table in the default mode (status, counters, timing).
+ */
+ private Table buildRouteTable(List<RouteInfo> sortedRoutes) {
+ boolean hasPercentiles = sortedRoutes.stream().anyMatch(r -> r.p50Time >= 0);
+
+ long maxTotal = sortedRoutes.stream().mapToLong(r -> r.total).max().orElse(0);
+ long maxFailed = sortedRoutes.stream().mapToLong(r -> r.failed).max().orElse(0);
+ int tw = Math.max(numWidth(maxTotal), 6);
+ int fw = Math.max(numWidth(maxFailed), 6);
+
+ List<Row> routeRows = new ArrayList<>();
+ for (RouteInfo route : sortedRoutes) {
+ Style stateStyle = "Started".equals(route.state)
+ ? Theme.success()
+ : Theme.error();
+
+ Style failStyle = route.failed > 0
+ ? Theme.error().bold()
+ : Style.EMPTY;
+
+ String timingCol;
+ if (hasPercentiles && route.p50Time >= 0) {
+ timingCol = formatDurationMs(route.p50Time) + "/" + formatDurationMs(route.p95Time) + "/"
+ + formatDurationMs(route.p99Time);
+ } else if (route.total > 0) {
+ timingCol = formatDurationMs(route.minTime) + "/" + formatDurationMs(route.maxTime) + "/"
+ + formatDurationMs(route.meanTime);
+ } else {
+ timingCol = "";
+ }
+
+ Line totalCell = route.sinceLastCompleted != null
+ ? Line.from(Span.raw(String.format("%" + tw + "d", route.total)),
+ Span.styled(" (" + route.sinceLastCompleted + ")", Theme.muted()))
+ : Line.from(Span.raw(String.format("%" + tw + "d", route.total)));
+ Line failCell = route.sinceLastFailed != null
+ ? Line.from(Span.styled(String.format("%" + fw + "d", route.failed), failStyle),
+ Span.styled(" (" + route.sinceLastFailed + ")", Theme.muted()))
+ : Line.from(Span.styled(String.format("%" + fw + "d", route.failed), failStyle));
+
+ routeRows.add(Row.from(
+ Cell.from(Span.styled(route.routeId != null ? route.routeId : "", Style.EMPTY.fg(Theme.accent()))),
+ Cell.from(routeFromLabel(route)),
+ Cell.from(Span.styled(route.state != null ? route.state : "", stateStyle)),
+ rightCell(formatThroughput(route.throughput), 8),
+ Cell.from(totalCell),
+ Cell.from(failCell),
+ rightCell(timingCol, 20),
+ Cell.from(buildPercentileBarLine(route.p50Time, route.p95Time, route.p99Time, 10))));
+ }
+
+ IntegrationInfo selDef = ctx.findSelectedIntegration();
+ if (selDef != null && selDef.exchangesTotal > 0) {
+ Style ts = Theme.label();
+ String totalTimingCol;
+ if (hasPercentiles && selDef.p50Time >= 0) {
+ totalTimingCol = formatDurationMs(selDef.p50Time) + "/" + formatDurationMs(selDef.p95Time) + "/"
+ + formatDurationMs(selDef.p99Time);
+ } else {
+ totalTimingCol = formatDurationMs(selDef.minTime) + "/" + formatDurationMs(selDef.maxTime) + "/"
+ + formatDurationMs(selDef.meanTime);
+ }
+ routeRows.add(Row.from(
+ Cell.from(Span.styled("GLOBAL", ts)),
+ Cell.from(""),
+ Cell.from(""),
+ rightCell(formatThroughput(selDef.throughput), 8, ts),
+ Cell.from(Span.styled(String.format("%" + tw + "d", selDef.exchangesTotal), ts)),
+ Cell.from(Span.styled(String.format("%" + fw + "d", selDef.failed),
+ selDef.failed > 0 ? Theme.error().bold() : ts)),
+ rightCell(totalTimingCol, 20, ts),
+ Cell.from(buildPercentileBarLine(selDef.p50Time, selDef.p95Time, selDef.p99Time, 10))));
+ }
+
+ String timingHeader = hasPercentiles ? "P50/P95/P99" : "MIN/MAX/MEAN";
+
+ return Table.builder()
+ .rows(routeRows)
+ .header(Row.from(
+ Cell.from(Span.styled(routeSortLabel("ROUTE", "name"), routeSortStyle("name"))),
+ Cell.from(Span.styled(routeSortLabel("FROM", "from"), routeSortStyle("from"))),
+ Cell.from(Span.styled(routeSortLabel("STATUS", "status"), routeSortStyle("status"))),
+ rightCell(ctx.ratePerMinute ? "MSG/M" : "MSG/S", 8, Style.EMPTY.bold()),
+ centerCell(routeSortLabel("TOTAL", "total"), 14, routeSortStyle("total")),
+ centerCell(routeSortLabel("FAIL", "failed"), 14, routeSortStyle("failed")),
+ rightCell(timingHeader, 20, Style.EMPTY.bold()),
+ Cell.from("")))
+ .widths(
+ Constraint.length(24),
+ Constraint.fill(),
+ Constraint.length(10),
+ Constraint.length(10),
+ Constraint.length(14),
+ Constraint.length(14),
+ Constraint.min(20),
+ Constraint.length(12))
+ .highlightStyle(Theme.selectionBg())
+ .highlightSpacing(Table.HighlightSpacing.ALWAYS)
+ .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
+ .title(" Routes ").build())
+ .build();
+ }
+
@Override
public void renderFooter(List<Span> spans) {
if (sourceViewer.isVisible()) {
@@ -977,295 +985,6 @@ class RoutesTab extends AbstractTab {
// ---- Info panels (mirrored from DiagramTab) ----
- private void renderInfoPanel(Frame frame, Rect area, IntegrationInfo info, String routeId) {
- RouteInfo route = null;
- for (RouteInfo r : info.routes) {
- if (routeId.equals(r.routeId)) {
- route = r;
- break;
- }
- }
-
- List<Line> lines = new ArrayList<>();
- if (route != null) {
- lines.add(Line.from(
- Span.styled(" Route: ", Theme.muted()),
- Span.styled(route.routeId, Style.EMPTY.fg(Theme.baseFg()).bold())));
- lines.add(Line.from(
- Span.styled(" From: ", Theme.muted()),
- Span.raw(route.from != null ? route.from : "")));
- String stateLabel = route.state != null ? route.state : "";
- Style stateStyle = "Started".equals(route.state) ? Theme.success() : Theme.error();
- lines.add(Line.from(
- Span.styled(" State: ", Theme.muted()),
- Span.styled(stateLabel, stateStyle)));
-
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(" Uptime: ", Theme.muted()),
- Span.raw(route.uptime != null ? route.uptime : "")));
- String tpUnit = ctx.ratePerMinute ? " msg/m" : " msg/s";
- lines.add(Line.from(
- Span.styled(" Rate: ", Theme.muted()),
- Span.raw(formatThroughput(route.throughput)),
- Span.styled(tpUnit, Theme.muted())));
- if (route.coverage != null) {
- lines.add(Line.from(
- Span.styled(" Coverage: ", Theme.muted()),
- Span.raw(route.coverage)));
- }
-
- lines.add(Line.from(Span.raw("")));
- int w = numWidth(route.total, route.failed, route.inflight);
- lines.add(Line.from(
- Span.styled(" Total: ", Theme.muted()),
- Span.raw(String.format("%" + w + "d", route.total))));
- Style failStyle = route.failed > 0 ? Theme.error().bold() : Style.EMPTY;
- lines.add(Line.from(
- Span.styled(" Failed: ", Theme.muted()),
- Span.styled(String.format("%" + w + "d", route.failed), failStyle)));
- lines.add(Line.from(
- Span.styled(" Inflight: ", Theme.muted()),
- Span.raw(String.format("%" + w + "d", route.inflight))));
-
- lines.add(Line.from(Span.raw("")));
- if (route.total > 0) {
- lines.add(Line.from(
- Span.styled(" Mean: ", Theme.muted()),
- Span.raw(formatDurationMs(route.meanTime))));
- lines.add(Line.from(
- Span.styled(" Max: ", Theme.muted()),
- Span.raw(formatDurationMs(route.maxTime))));
- lines.add(Line.from(
- Span.styled(" Min: ", Theme.muted()),
- Span.raw(formatDurationMs(route.minTime))));
- if (route.p50Time >= 0) {
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(" p50: ", Theme.muted()),
- Span.raw(formatDurationMs(route.p50Time))));
- lines.add(Line.from(
- Span.styled(" p95: ", Theme.muted()),
- Span.raw(formatDurationMs(route.p95Time))));
- lines.add(Line.from(
- Span.styled(" p99: ", Theme.muted()),
- Span.raw(formatDurationMs(route.p99Time))));
- lines.add(buildPercentileBarLine(
- route.p50Time, route.p95Time, route.p99Time, area.width() - 3));
- }
- }
-
- if (route.sinceLastCompleted != null || route.sinceLastFailed != null) {
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(" Since last:", Theme.muted())));
- if (route.sinceLastCompleted != null) {
- lines.add(Line.from(
- Span.styled(" ok: ", Theme.muted()),
- Span.raw(route.sinceLastCompleted)));
- }
- if (route.sinceLastFailed != null) {
- lines.add(Line.from(
- Span.styled(" fail: ", Theme.muted()),
- Span.styled(route.sinceLastFailed,
- Theme.error())));
- }
- }
-
- } else {
- var topoNode = diagram.getSelectedTopologyNode();
- if (topoNode != null) {
- boolean isInbound = "external-in".equals(topoNode.nodeType);
- lines.add(Line.from(
- Span.styled(isInbound ? " Inbound" : " Outbound",
- Style.EMPTY.fg(Theme.accent()).bold())));
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(" URI: ", Theme.muted()),
- Span.raw(topoNode.from != null ? topoNode.from : "")));
- if (topoNode.description != null && !topoNode.description.isBlank()) {
- lines.add(Line.from(
- Span.styled(" Path: ", Theme.muted()),
- Span.raw(topoNode.description)));
- }
- String connectedRoute = diagram.getConnectedRouteId(routeId);
- if (connectedRoute != null) {
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(isInbound ? " To route: " : " From route: ", Theme.muted()),
- Span.styled(connectedRoute, Style.EMPTY.fg(Theme.baseFg()))));
- }
- if (topoNode.exchangesTotal > 0 || topoNode.exchangesFailed > 0) {
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(" Total: ", Theme.muted()),
- Span.raw(String.valueOf(topoNode.exchangesTotal))));
- if (topoNode.exchangesFailed > 0) {
- lines.add(Line.from(
- Span.styled(" Failed: ", Theme.muted()),
- Span.styled(String.valueOf(topoNode.exchangesFailed),
- Theme.error().bold())));
- }
- }
- } else {
- lines.add(Line.from(
- Span.styled(" " + routeId, Style.EMPTY.fg(Theme.accent()).bold())));
- lines.add(Line.from(
- Span.styled(" (external endpoint)", Style.EMPTY.dim())));
- }
- }
-
- Paragraph paragraph = Paragraph.builder()
- .text(Text.from(lines))
- .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
- .title(" Info ").build())
- .build();
- frame.renderWidget(paragraph, area);
- }
-
- private void renderEipInfoPanel(Frame frame, Rect area) {
- List<Line> lines = new ArrayList<>();
- var selected = diagram.getSelectedEipNodeBox();
- if (selected != null && selected.layoutNode() != null) {
- var ln = selected.layoutNode();
-
- String typeLabel = ln.type != null ? ln.type : "unknown";
- Color eipColor = org.apache.camel.dsl.jbang.core.commands.tui.diagram.DiagramColors.getEipColor(typeLabel);
- lines.add(Line.from(
- Span.styled(" [" + typeLabel + "]", Style.EMPTY.fg(eipColor).bold())));
-
- String label = String.join("", ln.wrappedLines);
- if (!label.isBlank()) {
- lines.add(Line.from(
- Span.styled(" ", Style.EMPTY.dim()),
- Span.raw(label)));
- }
-
- if (ln.id != null) {
- lines.add(Line.from(
- Span.styled(" ID: ", Style.EMPTY.dim()),
- Span.raw(ln.id)));
- }
-
- String linkedRoute = diagram.findLinkedRouteId(drillDownRouteId);
- if (linkedRoute != null && diagram.getRouteLayout(linkedRoute) != null) {
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(" ↵ ", Theme.label().bold()),
- Span.styled(linkedRoute, Style.EMPTY.fg(Theme.baseFg()))));
- } else if (ln.treeNode != null && ln.treeNode.info.remote) {
- lines.add(Line.from(Span.raw("")));
- String arrow = "from".equals(ln.type) ? " external → " : " → external";
- lines.add(Line.from(
- Span.styled(arrow, Theme.muted())));
- }
-
- if (ln.treeNode != null && ln.treeNode.info.stat != null) {
- var stat = ln.treeNode.info.stat;
- lines.add(Line.from(Span.raw("")));
- int w = numWidth(stat.exchangesTotal, stat.exchangesFailed, stat.exchangesInflight);
- lines.add(Line.from(
- Span.styled(" Total: ", Style.EMPTY.dim()),
- Span.raw(String.format("%" + w + "d", stat.exchangesTotal))));
- Style failStyle = stat.exchangesFailed > 0
- ? Theme.error().bold() : Style.EMPTY;
- lines.add(Line.from(
- Span.styled(" Failed: ", Style.EMPTY.dim()),
- Span.styled(String.format("%" + w + "d", stat.exchangesFailed), failStyle)));
- lines.add(Line.from(
- Span.styled(" Inflight: ", Style.EMPTY.dim()),
- Span.raw(String.format("%" + w + "d", stat.exchangesInflight))));
- if (stat.exchangesThroughput != null && !stat.exchangesThroughput.isEmpty()) {
- String tpUnit = ctx.ratePerMinute ? " msg/m" : " msg/s";
- String tpValue = ctx.ratePerMinute
- ? TuiHelper.throughputPerMinute(stat.exchangesThroughput)
- : stat.exchangesThroughput;
- lines.add(Line.from(
- Span.styled(" Rate: ", Style.EMPTY.dim()),
- Span.raw(tpValue),
- Span.styled(tpUnit, Style.EMPTY.dim())));
- }
-
- if (stat.exchangesTotal > 0) {
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(" Mean: ", Style.EMPTY.dim()),
- Span.raw(formatDurationMs(stat.meanProcessingTime))));
- lines.add(Line.from(
- Span.styled(" Max: ", Style.EMPTY.dim()),
- Span.raw(formatDurationMs(stat.maxProcessingTime))));
- lines.add(Line.from(
- Span.styled(" Min: ", Style.EMPTY.dim()),
- Span.raw(formatDurationMs(stat.minProcessingTime))));
- lines.add(Line.from(
- Span.styled(" Last: ", Style.EMPTY.dim()),
- Span.raw(formatDurationMs(stat.lastProcessingTime))));
- if (stat.p50ProcessingTime >= 0) {
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(" p50: ", Style.EMPTY.dim()),
- Span.raw(formatDurationMs(stat.p50ProcessingTime))));
- lines.add(Line.from(
- Span.styled(" p95: ", Style.EMPTY.dim()),
- Span.raw(formatDurationMs(stat.p95ProcessingTime))));
- lines.add(Line.from(
- Span.styled(" p99: ", Style.EMPTY.dim()),
- Span.raw(formatDurationMs(stat.p99ProcessingTime))));
- lines.add(buildPercentileBarLine(
- stat.p50ProcessingTime, stat.p95ProcessingTime,
- stat.p99ProcessingTime, area.width() - 3));
- }
-
- if (stat.lastCompletedExchangeTimestamp > 0 || stat.lastFailedExchangeTimestamp > 0) {
- long now = System.currentTimeMillis();
- lines.add(Line.from(Span.raw("")));
- lines.add(Line.from(
- Span.styled(" Since last:", Style.EMPTY.dim())));
- if (stat.lastCompletedExchangeTimestamp > 0) {
- long ago = now - stat.lastCompletedExchangeTimestamp;
- lines.add(Line.from(
- Span.styled(" ok: ", Style.EMPTY.dim()),
- Span.raw(TimeUtils.printDuration(ago, false))));
- }
- if (stat.lastFailedExchangeTimestamp > 0) {
- long ago = now - stat.lastFailedExchangeTimestamp;
- lines.add(Line.from(
- Span.styled(" fail: ", Style.EMPTY.dim()),
- Span.styled(TimeUtils.printDuration(ago, false),
- Theme.error())));
- }
- }
- }
- }
- } else {
- lines.add(Line.from(Span.styled(" (no node selected)", Style.EMPTY.dim())));
- }
-
- Paragraph paragraph = Paragraph.builder()
- .text(Text.from(lines))
- .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
- .title(" Info ").build())
- .build();
- frame.renderWidget(paragraph, area);
- }
-
- private Line buildBreadcrumbTitle() {
- Style nameStyle = Theme.label().bold();
- List<Span> spans = new ArrayList<>();
- spans.add(Span.raw(" Route ["));
- if (routeNavigationStack.isEmpty()) {
- spans.add(Span.styled(drillDownRouteId, nameStyle));
- } else {
- for (var it = routeNavigationStack.descendingIterator(); it.hasNext();) {
- spans.add(Span.styled(it.next(), nameStyle));
- spans.add(Span.raw(" → "));
- }
- spans.add(Span.styled(drillDownRouteId, nameStyle));
- }
- spans.add(Span.raw("] "));
- return Line.from(spans);
- }
-
// ---- Rendering helpers ----
private void renderProcessors(Frame frame, Rect area, RouteInfo route) {
@@ -1663,14 +1382,14 @@ class RoutesTab extends AbstractTab {
loadDiagram(true);
}
// Select the closest EIP node after diagram is available
- int bestIdx = findClosestEipNode(sourceLine);
+ int bestIdx = diagram.findClosestEipNode(sourceLine);
if (bestIdx >= 0) {
diagram.setSelectedEipNodeIndex(bestIdx);
diagram.scrollToSelectedEipNode();
}
});
- sourceViewer.setQuickDocProvider(this::provideAllQuickDocs);
- ensureProcessorDetailLoaded(routeId);
+ sourceViewer.setQuickDocProvider(detail::provideAllQuickDocs);
+ detail.ensureProcessorDetailLoaded(routeId);
var rl = diagram.getRouteLayout(routeId);
sourceViewer.loadSource(ctx, routeId, 0, rl != null ? rl.source : null);
}
@@ -1697,14 +1416,14 @@ class RoutesTab extends AbstractTab {
if (diagram.getRouteLayout(routeId) == null) {
reloadDiagram();
}
- int bestIdx = findClosestEipNode(sourceLine);
+ int bestIdx = diagram.findClosestEipNode(sourceLine);
if (bestIdx >= 0) {
diagram.setSelectedEipNodeIndex(bestIdx);
diagram.scrollToSelectedEipNode();
}
});
- sourceViewer.setQuickDocProvider(this::provideAllQuickDocs);
- ensureProcessorDetailLoaded(routeId);
+ sourceViewer.setQuickDocProvider(detail::provideAllQuickDocs);
+ detail.ensureProcessorDetailLoaded(routeId);
var rl2 = diagram.getRouteLayout(routeId);
sourceViewer.loadSource(ctx, routeId, 0, rl2 != null ? rl2.source : null);
}
@@ -1720,58 +1439,19 @@ class RoutesTab extends AbstractTab {
targetLine = selected.layoutNode().treeNode.info.line;
}
sourceViewer.setOnLineSelected(sourceLine -> {
- int bestIdx = findClosestEipNode(sourceLine);
+ int bestIdx = diagram.findClosestEipNode(sourceLine);
if (bestIdx >= 0) {
diagram.setSelectedEipNodeIndex(bestIdx);
diagram.scrollToSelectedEipNode();
sourceViewer.hide();
}
});
- sourceViewer.setQuickDocProvider(this::provideAllQuickDocs);
- ensureProcessorDetailLoaded(drillDownRouteId);
+ sourceViewer.setQuickDocProvider(detail::provideAllQuickDocs);
+ detail.ensureProcessorDetailLoaded(drillDownRouteId);
var rl3 = diagram.getRouteLayout(drillDownRouteId);
sourceViewer.loadSource(ctx, drillDownRouteId, targetLine, rl3 != null ? rl3.source : null);
}
- private int findClosestEipNode(int sourceLine) {
- var boxes = diagram.getEipNodeBoxes();
- if (boxes.isEmpty()) {
- return -1;
- }
- // Prefer the closest node at or before the cursor line
- int bestBeforeIdx = -1;
- int bestBeforeDist = Integer.MAX_VALUE;
- int bestAfterIdx = -1;
- int bestAfterDist = Integer.MAX_VALUE;
- for (int i = 0; i < boxes.size(); i++) {
- var box = boxes.get(i);
- if (box.layoutNode() == null || box.layoutNode().treeNode == null) {
- continue;
- }
- int nodeLine = box.layoutNode().treeNode.info.line;
- if (nodeLine <= 0) {
- continue;
- }
- if (nodeLine == sourceLine) {
- return i;
- }
- if (nodeLine < sourceLine) {
- int dist = sourceLine - nodeLine;
- if (dist < bestBeforeDist) {
- bestBeforeDist = dist;
- bestBeforeIdx = i;
- }
- } else {
- int dist = nodeLine - sourceLine;
- if (dist < bestAfterDist) {
- bestAfterDist = dist;
- bestAfterIdx = i;
- }
- }
- }
- return bestBeforeIdx >= 0 ? bestBeforeIdx : bestAfterIdx;
- }
-
@Override
public SelectionContext getSelectionContext() {
IntegrationInfo info = ctx.findSelectedIntegration();
@@ -1786,663 +1466,8 @@ class RoutesTab extends AbstractTab {
// ---- Detail panel ----
- private void renderDetail(Frame frame, Rect area, IntegrationInfo info) {
- var selected = diagram.getSelectedEipNodeBox();
- if (selected == null || selected.layoutNode() == null) {
- frame.renderWidget(
- MarkdownView.builder()
- .source("*Select an EIP node*")
- .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
- .title(" EIP Detail ").build())
- .styles(Theme.markdownStyles())
- .build(),
- area);
- return;
- }
-
- String nodeId = selected.layoutNode().id;
- String eipType = selected.layoutNode().type;
- if (nodeId == null || eipType == null) {
- frame.renderWidget(
- MarkdownView.builder()
- .source("*No detail available*")
- .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
- .title(" EIP Detail ").build())
- .styles(Theme.markdownStyles())
- .build(),
- area);
- return;
- }
-
- if (!nodeId.equals(lastDetailNodeId)) {
- lastDetailNodeId = nodeId;
- detailScroll = 0;
- }
-
- if (drillDownRouteId != null && cachedRouteDetail == null
- && !"*".equals(detailLoadingRouteId)) {
- detailLoadingRouteId = "*";
- detailLoading = true;
- if (ctx.runner != null) {
- ctx.backgroundExecutor.execute(() -> {
- JsonObject result = requestRouteProcessorDetail("*");
- cachedRouteDetail = result;
- cachedRouteDetailId = "*";
- detailLoading = false;
- });
- }
- }
-
- JsonObject processorEntry = findProcessorEntry(nodeId);
-
- StringBuilder md = new StringBuilder();
- CamelCatalog catalog = getCatalog(info);
-
- if (processorEntry != null) {
- String type = processorEntry.getString("type");
- String endpointUri = processorEntry.getString("endpointUri");
-
- if ("from".equals(type) && endpointUri != null && catalog != null) {
- renderEndpointDetail(md, catalog, endpointUri);
- } else if (type != null) {
- renderEipDetail(md, catalog, type, processorEntry.getMap("options"));
- } else {
- md.append("*No detail available*\n");
- }
- } else if (detailLoading) {
- md.append("*Loading...*\n");
- } else {
- md.append("*No detail available*\n");
- }
-
- String title = " " + eipType + " [" + nodeId + "] ";
- if (CharWidth.of(title) > area.width() - 4) {
- title = " " + CharWidth.truncateWithEllipsis(
- eipType + " [" + nodeId + "]", area.width() - 6, CharWidth.TruncatePosition.MIDDLE) + " ";
- }
-
- frame.renderWidget(
- MarkdownView.builder()
- .source(md.toString())
- .scroll(detailScroll)
- .block(Block.builder().borderType(BorderType.ROUNDED).borders(Borders.ALL)
- .title(title).build())
- .styles(Theme.markdownStyles())
- .build(),
- area);
- }
-
- private void renderEipDetail(StringBuilder md, CamelCatalog catalog, String type, JsonObject opts) {
- EipModel model = catalog != null ? catalog.eipModel(type) : null;
-
- if (model != null && model.getTitle() != null) {
- md.append("## ").append(model.getTitle()).append("\n\n");
- if (model.getDescription() != null && !model.getDescription().isEmpty()) {
- md.append(model.getDescription()).append("\n\n");
- }
- } else {
- md.append("## ").append(type).append("\n\n");
- }
-
- if (opts != null && !opts.isEmpty()) {
- Map<String, BaseOptionModel> optionDocs = new LinkedHashMap<>();
- if (model != null) {
- for (BaseOptionModel opt : model.getOptions()) {
- if (opt.getName() != null) {
- optionDocs.put(opt.getName(), opt);
- }
- }
- }
-
- for (Map.Entry<String, Object> entry : opts.entrySet()) {
- String optName = entry.getKey();
- String optValue = String.valueOf(entry.getValue());
- appendOptionDetail(md, optName, optValue, optionDocs.get(optName));
- }
- } else {
- md.append("*No configured options*\n");
- }
- }
-
- private void renderEndpointDetail(StringBuilder md, CamelCatalog catalog, String uri) {
- String component = uri.contains(":") ? uri.substring(0, uri.indexOf(':')) : uri;
- ComponentModel model = catalog.componentModel(component);
-
- if (model != null) {
- String compTitle = model.getTitle() != null ? model.getTitle() : component;
- md.append("## ").append(compTitle).append("\n\n");
- if (model.getDescription() != null && !model.getDescription().isEmpty()) {
- md.append(model.getDescription()).append("\n\n");
- }
-
- Map<String, String> parsedOptions;
- try {
- parsedOptions = catalog.endpointProperties(uri);
- } catch (URISyntaxException e) {
- parsedOptions = Map.of();
- }
-
- if (parsedOptions.isEmpty()) {
- md.append("*No configured options*\n");
- } else {
- Map<String, BaseOptionModel> optionDocs = new LinkedHashMap<>();
- for (ComponentModel.EndpointOptionModel opt : model.getEndpointOptions()) {
- if (opt.getName() != null) {
- optionDocs.put(opt.getName(), opt);
- }
- }
-
- for (Map.Entry<String, String> entry : parsedOptions.entrySet()) {
- appendOptionDetail(md, entry.getKey(), entry.getValue(), optionDocs.get(entry.getKey()));
- }
- }
- } else {
- md.append("## ").append(component).append("\n\n");
- md.append("*No catalog documentation for: ").append(component).append("*\n");
- }
- }
-
- private static void appendOptionDetail(StringBuilder md, String optName, String optValue, BaseOptionModel doc) {
- md.append("---\n\n");
- md.append("**").append(optName).append("** = **").append(optValue).append("**\n\n");
-
- if (doc != null) {
- if (doc.getDescription() != null && !doc.getDescription().isEmpty()) {
- md.append(doc.getDescription()).append("\n\n");
- }
- List<String> meta = new ArrayList<>();
- if (doc.getType() != null) {
- meta.add("Type: `" + doc.getType() + "`");
- }
- if (doc.getDefaultValue() != null) {
- meta.add("Default: `" + doc.getDefaultValue() + "`");
- }
- if (doc.isRequired()) {
- meta.add("Required: yes");
- }
- if (doc.getEnums() != null && !doc.getEnums().isEmpty()) {
- meta.add("Enum: " + String.join(", ", doc.getEnums()));
- }
- if (doc.getGroup() != null && !doc.getGroup().isEmpty()) {
- meta.add("Group: " + doc.getGroup());
- }
- if (doc.isDeprecated()) {
- String depText = "Deprecated";
- if (doc.getDeprecationNote() != null && !doc.getDeprecationNote().isEmpty()) {
- depText += " — " + doc.getDeprecationNote();
- }
- meta.add(depText);
- }
- if (!meta.isEmpty()) {
- for (String m : meta) {
- md.append("- ").append(m).append("\n");
- }
- md.append("\n");
- }
- }
- }
-
- private CamelCatalog getCatalog(IntegrationInfo info) {
- String version = info.camelVersion;
- if (version == null) {
- return null;
- }
- CamelCatalog cached = catalogCache.get(version);
- if (cached != null) {
- return cached;
- }
- if (catalogLoadFailed.contains(version)) {
- return null;
- }
- try {
- cached = CatalogLoader.loadCatalog(null, version, true);
- if (cached != null) {
- catalogCache.put(version, cached);
- } else {
- catalogLoadFailed.add(version);
- }
- return cached;
- } catch (Exception e) {
- catalogLoadFailed.add(version);
- return null;
- }
- }
-
- private JsonObject requestRouteProcessorDetail(String routeId) {
- if (ctx.selectedPid == null) {
- return null;
- }
- try {
- JsonObject root = new JsonObject();
- root.put("action", "processor-detail");
- root.put("routeId", "*");
- return ctx.executeAction(ctx.selectedPid, root, 5000);
- } catch (Exception e) {
- return null;
- }
- }
-
- private JsonObject findProcessorEntry(String nodeId) {
- if (cachedRouteDetail == null || nodeId == null) {
- return null;
- }
- for (JsonObject p : getAllProcessors(cachedRouteDetail)) {
- if (nodeId.equals(p.getString("id"))) {
- return p;
- }
- }
- return null;
- }
-
- static List<JsonObject> getAllProcessors(JsonObject routeDetail) {
- if (routeDetail == null) {
- return List.of();
- }
- JsonArray routes = (JsonArray) routeDetail.get("routes");
- if (routes != null) {
- List<JsonObject> all = new ArrayList<>();
- for (Object obj : routes) {
- JsonObject route = (JsonObject) obj;
- JsonArray procs = (JsonArray) route.get("processors");
- if (procs != null) {
- for (Object p : procs) {
- all.add((JsonObject) p);
- }
- }
- }
- return all;
- }
- JsonArray procs = (JsonArray) routeDetail.get("processors");
- if (procs != null) {
- List<JsonObject> all = new ArrayList<>();
- for (Object p : procs) {
- all.add((JsonObject) p);
- }
- return all;
- }
- return List.of();
- }
-
// ---- Quick doc (q toggle in source viewer) ----
- private Map<Integer, List<SourceViewer.DocEntry>> provideAllQuickDocs(List<JsonObject> cd) {
- if (cachedRouteDetail == null || cd.isEmpty()) {
- return Map.of();
- }
-
- List<JsonObject> processors = getAllProcessors(cachedRouteDetail);
- if (processors.isEmpty()) {
- return Map.of();
- }
-
- IntegrationInfo info = ctx.findSelectedIntegration();
- CamelCatalog catalog = info != null ? getCatalog(info) : null;
-
- Map<Integer, List<SourceViewer.DocEntry>> result = new LinkedHashMap<>();
- for (JsonObject proc : processors) {
- Integer line = proc.getInteger("line");
- if (line == null || line <= 0) {
- continue;
- }
-
- int eipIdx = findCodeDataIndex(cd, line, -1);
- if (eipIdx < 0 || result.containsKey(eipIdx)) {
- continue;
- }
- String endpointUri = proc.getString("endpointUri");
- String type = proc.getString("type");
-
- if (endpointUri != null && catalog != null) {
- buildEndpointInlineDoc(result, cd, catalog, endpointUri, eipIdx);
- } else if (type != null) {
- buildEipInlineDoc(result, cd, catalog, type, proc.getMap("options"), eipIdx);
- }
- }
- return result;
- }
-
- private void ensureProcessorDetailLoaded(String routeId) {
- if (routeId != null && cachedRouteDetail == null
- && !"*".equals(detailLoadingRouteId)) {
- detailLoadingRouteId = "*";
- detailLoading = true;
- if (ctx.runner != null) {
- ctx.backgroundExecutor.execute(() -> {
- JsonObject result = requestRouteProcessorDetail("*");
- cachedRouteDetail = result;
- cachedRouteDetailId = "*";
- detailLoading = false;
- });
- }
- }
- }
-
- static void buildEndpointInlineDoc(
- Map<Integer, List<SourceViewer.DocEntry>> result, List<JsonObject> cd,
- CamelCatalog catalog, String endpointUri, int eipIdx) {
-
- String component = endpointUri.contains(":") ? endpointUri.substring(0, endpointUri.indexOf(':')) : endpointUri;
- ComponentModel model = catalog.componentModel(component);
- if (model == null) {
- return;
- }
-
- String compTitle = model.getTitle() != null ? model.getTitle() : component;
- String desc = model.getDescription() != null ? truncateText(model.getDescription(), 80) : "";
-
- Map<String, BaseOptionModel> optionDocs = new LinkedHashMap<>();
- for (ComponentModel.EndpointOptionModel opt : model.getEndpointOptions()) {
- if (opt.getName() != null) {
- optionDocs.put(opt.getName(), opt);
- }
- }
-
- int beforeSize = result.size();
- List<SourceViewer.DocEntry> titleLines = new ArrayList<>();
- titleLines.add(SourceViewer.DocEntry.of(compTitle + " — " + desc));
- result.put(eipIdx, titleLines);
-
- inlineParameterDocs(result, cd, eipIdx, optionDocs);
-
- // For Java/XML where params are in the URI (not on separate source lines),
- // cluster the option docs under the title
- if (result.size() == beforeSize + 1) {
- clusterEndpointOptions(titleLines, catalog, endpointUri, optionDocs);
- }
- }
-
- private static void clusterEndpointOptions(
- List<SourceViewer.DocEntry> docLines, CamelCatalog catalog,
- String endpointUri, Map<String, BaseOptionModel> optionDocs) {
- try {
- Map<String, String> props = catalog.endpointProperties(endpointUri);
- if (props != null) {
- for (Map.Entry<String, String> entry : props.entrySet()) {
- BaseOptionModel optModel = optionDocs.get(entry.getKey());
- if (optModel != null) {
- String optDoc = formatOptionDoc(optModel);
- if (optDoc != null) {
- String text = entry.getKey() + ": " + entry.getValue() + " — " + optDoc;
- docLines.add(optModel.isDeprecated()
- ? SourceViewer.DocEntry.deprecated(text)
- : SourceViewer.DocEntry.of(text));
- }
- }
- }
- }
- } catch (Exception e) {
- // ignore URI parse errors
- }
- }
-
- static void buildEipInlineDoc(
- Map<Integer, List<SourceViewer.DocEntry>> result, List<JsonObject> cd,
- CamelCatalog catalog, String type, JsonObject opts, int eipIdx) {
-
- EipModel model = catalog != null ? catalog.eipModel(type) : null;
-
- // For endpoint-bearing EIPs, resolve the component from the uri option
- ComponentModel compModel = null;
- if (opts != null && catalog != null) {
- Object uriObj = opts.get("uri");
- if (uriObj != null) {
- String uri = uriObj.toString();
- String comp = uri.contains(":") ? uri.substring(0, uri.indexOf(':')) : uri;
- compModel = catalog.componentModel(comp);
- }
- }
-
- List<SourceViewer.DocEntry> titleLines = new ArrayList<>();
- if (model != null && model.getTitle() != null) {
- String eipTitle = model.getTitle();
- if (compModel != null && compModel.getTitle() != null) {
- eipTitle += " (" + compModel.getTitle() + ")";
- }
- String desc;
- if (compModel != null && compModel.getDescription() != null) {
- desc = truncateText(compModel.getDescription(), 80);
- } else {
- desc = model.getDescription() != null ? truncateText(model.getDescription(), 80) : "";
- }
- titleLines.add(SourceViewer.DocEntry.of(eipTitle + " — " + desc));
- } else {
- titleLines.add(SourceViewer.DocEntry.of(type));
- }
-
- int beforeSize = result.size();
- result.put(eipIdx, titleLines);
-
- if (model != null) {
- Map<String, BaseOptionModel> optionDocs = new LinkedHashMap<>();
- for (BaseOptionModel opt : model.getOptions()) {
- if (opt.getName() != null) {
- optionDocs.put(opt.getName(), opt);
- }
- }
- if (compModel != null) {
- for (ComponentModel.EndpointOptionModel opt : compModel.getEndpointOptions()) {
- if (opt.getName() != null && !optionDocs.containsKey(opt.getName())) {
- optionDocs.put(opt.getName(), opt);
- }
- }
- }
- inlineParameterDocs(result, cd, eipIdx, optionDocs);
-
- // For Java/XML where options are on the same line,
- // cluster the option docs under the title
- if (result.size() == beforeSize + 1 && opts != null) {
- boolean hasParams = hasParametersChild(cd, eipIdx);
- clusterEipOptions(titleLines, opts, optionDocs, hasParams);
- }
- }
- }
-
- private static void clusterEipOptions(
- List<SourceViewer.DocEntry> docLines, JsonObject opts,
- Map<String, BaseOptionModel> optionDocs, boolean skipUri) {
- for (Map.Entry<String, Object> entry : opts.entrySet()) {
- if (skipUri && "uri".equals(entry.getKey())) {
- continue;
- }
- BaseOptionModel optModel = optionDocs.get(entry.getKey());
- if (optModel != null) {
- String optDoc = formatOptionDoc(optModel);
- if (optDoc != null) {
- String text = entry.getKey() + ": " + entry.getValue() + " — " + optDoc;
- docLines.add(optModel.isDeprecated()
- ? SourceViewer.DocEntry.deprecated(text)
- : SourceViewer.DocEntry.of(text));
- }
- }
- }
- }
-
- static boolean hasParametersChild(List<JsonObject> cd, int eipIdx) {
- int eipIndent = lineIndent(cd, eipIdx);
- for (int i = eipIdx + 1; i < cd.size(); i++) {
- String code = cd.get(i).get("code") != null ? cd.get(i).get("code").toString() : "";
- int indent = leadingSpaces(code);
- if (indent < eipIndent && !code.isBlank()) {
- break;
- }
- String trimmed = code.stripLeading();
- if (trimmed.startsWith("parameters:")) {
- return true;
- }
- }
- return false;
- }
-
- static void inlineParameterDocs(
- Map<Integer, List<SourceViewer.DocEntry>> result, List<JsonObject> cd,
- int eipIdx, Map<String, BaseOptionModel> optionDocs) {
-
- if (optionDocs.isEmpty()) {
- return;
- }
-
- int eipIndent = lineIndent(cd, eipIdx);
- int childIndent = -1;
- boolean inParameters = false;
- int paramIndent = -1;
- int parametersLineIndent = -1;
-
- for (int i = eipIdx + 1; i < cd.size(); i++) {
- String code = cd.get(i).get("code") != null ? cd.get(i).get("code").toString() : "";
- int indent = leadingSpaces(code);
- if (indent < eipIndent && !code.isBlank()) {
- break;
- }
- if (childIndent < 0 && indent > eipIndent) {
- childIndent = indent;
- }
-
- if (inParameters) {
- if (paramIndent < 0 && indent > parametersLineIndent && !code.isBlank()) {
- paramIndent = indent;
- }
- if (paramIndent > 0 && indent <= parametersLineIndent && !code.isBlank()) {
- inParameters = false;
- paramIndent = -1;
- parametersLineIndent = -1;
- } else if (paramIndent > 0 && indent == paramIndent) {
- String trimmed = code.stripLeading();
- int colon = trimmed.indexOf(':');
- if (colon > 0) {
- String key = trimmed.substring(0, colon).strip();
- BaseOptionModel doc = optionDocs.get(key);
- if (doc != null) {
- String docLine = formatOptionDoc(doc);
- if (docLine != null) {
- int docIdx = lastContinuationLine(cd, i, indent);
- result.put(docIdx, List.of(doc.isDeprecated()
- ? SourceViewer.DocEntry.deprecated(docLine)
- : SourceViewer.DocEntry.of(docLine)));
- }
- }
- }
- continue;
- } else {
- continue;
- }
- }
-
- if (childIndent > 0 && indent != childIndent) {
- continue;
- }
- String trimmed = code.stripLeading();
- int colon = trimmed.indexOf(':');
- if (colon <= 0) {
- continue;
- }
- String key = trimmed.substring(0, colon).strip();
- if ("parameters".equals(key)) {
- inParameters = true;
- parametersLineIndent = indent;
- continue;
- }
- if ("uri".equals(key) || "steps".equals(key)
- || "id".equals(key) || "description".equals(key)) {
- continue;
- }
-
- BaseOptionModel doc = optionDocs.get(key);
- if (doc != null) {
- String docLine = formatOptionDoc(doc);
- if (docLine != null) {
- int docIdx = lastContinuationLine(cd, i, indent);
- result.put(docIdx, List.of(doc.isDeprecated()
- ? SourceViewer.DocEntry.deprecated(docLine)
- : SourceViewer.DocEntry.of(docLine)));
- }
- }
- }
- }
-
- static int lastContinuationLine(List<JsonObject> cd, int keyIdx, int keyIndent) {
- int last = keyIdx;
- for (int j = keyIdx + 1; j < cd.size(); j++) {
- String c = cd.get(j).get("code") != null ? cd.get(j).get("code").toString() : "";
- if (c.isBlank()) {
- continue;
- }
- if (leadingSpaces(c) > keyIndent) {
- last = j;
- } else {
- break;
- }
- }
- return last;
- }
-
- static String formatOptionDoc(BaseOptionModel doc) {
- StringBuilder sb = new StringBuilder();
- if (doc.getDescription() != null && !doc.getDescription().isEmpty()) {
- sb.append(truncateText(doc.getDescription(), 80));
- }
- List<String> meta = new ArrayList<>();
- if (doc.getType() != null) {
- meta.add(doc.getType());
- }
- if (doc.isRequired()) {
- meta.add("required");
- }
- if (doc.getDefaultValue() != null) {
- meta.add("default: " + doc.getDefaultValue());
- }
- if (!meta.isEmpty()) {
- if (!sb.isEmpty()) {
- sb.append(" ");
- }
- sb.append("(").append(String.join(", ", meta)).append(")");
- }
- return !sb.isEmpty() ? sb.toString() : null;
- }
-
- static int lineIndent(List<JsonObject> cd, int idx) {
- if (idx < 0 || idx >= cd.size()) {
- return 0;
- }
- String code = cd.get(idx).get("code") != null ? cd.get(idx).get("code").toString() : "";
- return leadingSpaces(code);
- }
-
- static int leadingSpaces(String s) {
- int count = 0;
- for (int i = 0; i < s.length(); i++) {
- if (s.charAt(i) == ' ') {
- count++;
- } else {
- break;
- }
- }
- return count;
- }
-
- static int findCodeDataIndex(List<JsonObject> cd, int targetLine, int fallback) {
- for (int i = 0; i < cd.size(); i++) {
- Integer lineNum = cd.get(i).getInteger("line");
- if (lineNum != null && lineNum == targetLine) {
- return i;
- }
- }
- return Math.max(0, fallback);
- }
-
- static String truncateText(String text, int maxLen) {
- if (text == null) {
- return "";
- }
- int dot = text.indexOf('.');
- if (dot > 0 && dot < maxLen) {
- return text.substring(0, dot + 1);
- }
- if (text.length() <= maxLen) {
- return text;
- }
- return text.substring(0, maxLen - 3) + "...";
- }
-
@Override
public String description() {
return "Route list with state, message counts, throughput, and failure statistics";
@@ -2450,162 +1475,7 @@ class RoutesTab extends AbstractTab {
@Override
public String getHelpText() {
- return """
- # Routes
-
- Routes are the building blocks of a Camel integration. Each route defines
- a message flow: where messages come from, how they are processed, and where
- they are sent to. A typical integration has multiple routes working together.
-
- ## Route Table Columns
-
- - **ROUTE** — Unique route identifier (e.g., `timer-to-log`, `seda-consumer`)
- - **FROM** — The endpoint that triggers this route (e.g., `timer`, `kafka`, `file`). This is the source of messages
- - **STATUS** — Route state: `Started` (running), `Stopped` (not running), or `Suspended` (paused, can be resumed)
- - **MSG/S** or **MSG/M** — Current message throughput (per second or per minute) for this route. Configure in Settings (F2)
- - **TOTAL** — Total exchanges processed by this route since startup
- - **FAIL** — Exchanges that ended with an unhandled error in this route
- - **MIN** — Fastest exchange processing time in milliseconds. This is the time from when the exchange entered the route until it completed
- - **MEAN** — Average exchange processing time in milliseconds. A rising MEAN may indicate a downstream service getting slower
- - **MAX** — Slowest exchange processing time in milliseconds. A very high MAX compared to MEAN suggests occasional slow outliers
- - **SINCE-LAST** — Time since the last exchange activity on this route, shown as up to three values separated by `/`: started/completed/failed (e.g., `1s/3s/1m14s`). Values are omitted when there is no activity of that type
-
- ## Percentile Latency (P50/P95/P99)
-
- When **Extended** statistics level is enabled, the timing columns show
- percentile latencies instead of MIN/MEAN/MAX — both for routes and processors:
-
- - **P50** — Median processing time (50th percentile). Half of all exchanges completed faster than this
- - **P95** — 95th percentile. 95% of exchanges completed faster than this. Useful for SLA monitoring
- - **P99** — 99th percentile. Only 1% of exchanges were slower. Highlights worst-case tail latency
-
- Percentiles are computed over a sliding window of recent exchanges, making
- them more meaningful than MIN/MAX for understanding real-world performance.
- With very few messages (e.g., 10), P95 and P99 may equal the MAX value since
- there aren't enough samples to differentiate.
-
- To enable Extended statistics, set `camel.main.load-statistics-enabled = true`
- in your application configuration. Without Extended statistics, the columns
- show MIN/MEAN/MAX instead.
-
- The TOTAL summary row shows the overall percentiles across all routes.
-
- ## Example Screen
-
- ```
- ROUTE FROM STATUS MSG/S TOTAL FAIL P50/P95/P99 SINCE-LAST
- timer-to-log timer://hello?p=2000 Started 0.50 142 0 1/10/31 ███▒▒▒▒▒░ 1s
- timer-to-seda timer://pump?p=3000 Started 0.33 95 0 0/1/2 ▒░░░░░░░░ 2s
- seda-consumer seda://queue Started 0.33 95 0 0/0/1 2s
- ```
-
- ## Top Mode
-
- Press `t` to switch to **Top mode** — a performance-focused view that
- includes processor-level breakdown and load averages. This shows every
- processor (step) inside a route, not just the route totals.
-
- - **LOAD** — Three throughput averages over 1m/5m/15m windows, similar to Unix load average but measuring message throughput instead of CPU. Higher values mean more messages flowing through. The three windows help you see if traffic is increasing or decreasing
-
- ## Route Diagram
-
- Press `d` to see a topology diagram showing how all routes connect to each
- other. This is the same view as the Diagram tab. Use arrow keys to navigate
- between route boxes and press `Enter` to drill down into a route's internal
- EIP structure.
-
- ## Navigation
-
- In the topology view, use arrow keys to select route boxes:
- - `↑↓` moves between layers (upstream/downstream routes)
- - `←→` moves between routes in the same layer
-
- When a route is selected, an **Info panel** appears on the left
- showing key metrics: state, uptime, throughput, exchange counts,
- and processing times.
-
- Press `Enter` on a selected route to **drill down** into its
- internal EIP structure (the route diagram). Press `Esc` to
- return to the topology view.
-
- ## Route Diagram (drill-down)
-
- In the route diagram, each EIP node shows its type tag (colored)
- and endpoint URI or description. Nodes that connect to other routes
- display a `↵` indicator — press `Enter` to jump directly to the
- linked route's diagram.
-
- Navigation history is maintained as a stack: pressing `Esc` goes
- back to the previous route, and eventually back to the topology view.
-
- ## Route Structure Preview
-
- A compact tree structure preview appears in the bottom-right corner
- of the diagram area — like a minimap of the route's EIP structure.
-
- In **topology mode**, the preview shows the structure of the currently
- selected route and updates as you navigate between route boxes.
-
- In **drill-down mode**, the preview highlights the currently selected
- EIP node (shown in yellow) as you navigate with arrow keys, giving
- you an at-a-glance view of where you are in the route.
-
- ## Source View
-
- Press `c` to see the original route source code (YAML, XML, or Java).
- A `>>` cursor highlights the current line. When opened from a diagram
- node, the matching source line is positioned at 2/3 of the viewport.
-
- Use `↑↓` to move the cursor, `Ctrl+↑↓` to scroll the viewport without
- moving the cursor. Press `Enter` to select the closest diagram node at
- the cursor line — this closes the source view and highlights that node
- in the diagram.
-
- ## Keys
-
- **Route table:**
- - `Up/Down` — select route
- - `Enter` — open route diagram
- - `p` — start/stop selected route
- - `P` — suspend/resume selected route
- - `c` — show route source code
- - `n` — toggle description labels
- - `s` — cycle sort column
- - `S` — reverse sort order
- - `t` — toggle Top mode
-
- **Topology view:**
- - `↑↓←→` — navigate between route boxes
- - `Enter` — drill down into selected route
- - `c` — show route source code
- - `Esc` — close diagram (back to route table)
- - `m` — toggle metrics on/off
- - `e` — toggle external systems on/off
- - `n` — toggle description labels
-
- **Route diagram (drill-down):**
- - `↑↓←→` — navigate between EIP nodes
- - `Enter` — jump to linked route (when `↵` indicator shown)
- - `d` — toggle detail panel (EIP/component catalog docs)
- - `g` — go to node (fuzzy search popup)
- - `c` — show source code at selected node
- - `Esc` — go back (previous route or topology)
- - `t` — jump back to topology view
- - `m` — toggle metrics
- - `n` — toggle description labels
- - `PgUp/PgDn` — scroll detail panel (when detail is on)
-
- **Source view:**
- - `↑↓` — move cursor between lines
- - `Ctrl+↑↓` — scroll viewport without moving cursor
- - `←→` — horizontal scroll
- - `PgUp/PgDn` — page jump
- - `Home/End` — go to top/bottom
- - `w` — toggle word wrap
- - `p` — toggle plain mode (hides line numbers and borders for easy copy/paste)
- - `Enter` — select the closest diagram node at cursor line
- - `Esc/c` — close source view
- """;
+ return DocHelper.loadHelpText("routes");
}
@Override
@@ -2648,11 +1518,4 @@ class RoutesTab extends AbstractTab {
return result;
}
- private static int numWidth(long... values) {
- long max = 0;
- for (long v : values) {
- max = Math.max(max, Math.abs(v));
- }
- return Math.max(1, String.valueOf(max).length());
- }
}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SecretsTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SecretsTab.java
index bbb8b9de6604..777ff92e3799 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SecretsTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SecretsTab.java
@@ -164,45 +164,7 @@ class SecretsTab extends AbstractTableTab {
@Override
public String getHelpText() {
- return """
- # Secrets
-
- Shows secrets resolved from cloud vault providers. Camel can load
- configuration values from external secret managers instead of
- hardcoding them in properties files.
-
- Supported providers: AWS Secrets Manager, Azure Key Vault,
- GCP Secret Manager, HashiCorp Vault, IBM Secrets Manager,
- Kubernetes Secrets, and Kubernetes ConfigMaps.
-
- ## Table Columns
-
- - **VAULT** — The cloud provider name (AWS, Azure, GCP, Hashicorp, IBM, Kubernetes, Kubernetes-cm)
- - **REGION** — Cloud region (AWS only, blank for other providers)
- - **SECRET** — The secret name/key as referenced in the route configuration
- - **AGE** — How long ago the secret value was last updated
- - **UPDATE** — How long ago the last automatic reload of secrets occurred
- - **CHECK** — How long ago the last check for secret changes was performed
-
- ## Automatic Refresh
-
- Camel can automatically detect secret changes and reload them:
- - **AWS** — monitors via CloudTrail events
- - **Azure** — monitors via Event Hubs
- - **GCP** — monitors via Pub/Sub
- - **IBM** — monitors via Event Streams (Kafka)
- - **Kubernetes** — watches the Kubernetes API
-
- When refresh is enabled, the UPDATE and CHECK columns show the
- timing of these automatic operations.
-
- ## Keys
-
- - `Up/Down` — select secret
- - `f` — force reload secrets from vault providers
- - `s` — cycle sort column
- - `S` — reverse sort order
- """;
+ return DocHelper.loadHelpText("secrets");
}
@Override
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SourceTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SourceEditAssist.java
similarity index 56%
copy from dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SourceTab.java
copy to dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SourceEditAssist.java
index 3270877fa6e4..68287c4d283e 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SourceTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SourceEditAssist.java
@@ -20,12 +20,8 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.attribute.BasicFileAttributes;
-import java.time.ZoneId;
-import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
@@ -33,37 +29,14 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import dev.tamboui.layout.Constraint;
-import dev.tamboui.layout.Layout;
-import dev.tamboui.layout.Rect;
-import dev.tamboui.style.Style;
-import dev.tamboui.terminal.Frame;
-import dev.tamboui.text.Line;
-import dev.tamboui.text.Span;
-import dev.tamboui.text.Text;
-import dev.tamboui.tui.event.KeyCode;
-import dev.tamboui.tui.event.KeyEvent;
-import dev.tamboui.tui.event.MouseEvent;
-import dev.tamboui.tui.event.MouseEventKind;
-import dev.tamboui.widgets.block.Block;
-import dev.tamboui.widgets.block.BorderType;
-import dev.tamboui.widgets.block.Borders;
-import dev.tamboui.widgets.block.Title;
-import dev.tamboui.widgets.list.ListItem;
-import dev.tamboui.widgets.list.ListState;
-import dev.tamboui.widgets.list.ListWidget;
-import dev.tamboui.widgets.list.ScrollMode;
-import dev.tamboui.widgets.paragraph.Paragraph;
-import dev.tamboui.widgets.scrollbar.Scrollbar;
-import dev.tamboui.widgets.scrollbar.ScrollbarState;
import org.apache.camel.catalog.CamelCatalog;
import org.apache.camel.catalog.ConfigurationPropertiesValidationResult;
import org.apache.camel.catalog.EndpointValidationResult;
import org.apache.camel.catalog.LanguageValidationResult;
-import org.apache.camel.dsl.jbang.core.common.CatalogLoader;
import org.apache.camel.tooling.model.BaseOptionModel;
import org.apache.camel.tooling.model.ComponentModel;
import org.apache.camel.tooling.model.DataFormatModel;
@@ -74,26 +47,31 @@ import org.apache.camel.util.json.JsonArray;
import org.apache.camel.util.json.JsonObject;
/**
- * Source tab showing a file browser in the top panel and a source code viewer in the bottom panel. Replaces the HTTP
- * tab as primary tab 7.
+ * Editor assistance for the Source tab: autocomplete, quick-doc, validation and deprecation providers for Camel YAML
+ * DSL files and application properties, backed by the Camel catalog, the YAML DSL completion tree and Spring Boot
+ * configuration metadata. {@link SourceTab} wires the provider methods into {@link SourceViewer}.
*/
-class SourceTab extends AbstractTab {
+final class SourceEditAssist {
- private String lastSeenPid;
+ private final MonitorContext ctx;
+ private final CatalogCache catalogCache = new CatalogCache();
private Path rootDir;
- private Path currentDir;
- private final ListState listState = new ListState();
- private final ScrollbarState listScrollState = new ScrollbarState();
- private List<FilesBrowser.FileEntry> entries = Collections.emptyList();
- private final SourceViewer sourceViewer = new SourceViewer();
- private boolean focusOnViewer;
- private int leftPanelWidth = -1;
- private final DragSplit hSplit = new DragSplit();
- private Rect leftArea;
- private Rect rightArea;
+ // ---- YAML DSL completion ----
+
+ private static final Set<String> TREE_BOILERPLATE = Set.of("id", "note", "description", "disabled");
+
+ // ---- Property placeholder loading ----
+
+ private List<AutocompletePopup.CompletionItem> placeholderCache;
+ private long placeholderCacheTime;
+ private Path placeholderCacheDir;
- private final Map<String, CamelCatalog> catalogCache = new HashMap<>();
+ private static final Set<String> PREDICATE_EIPS = Set.of(
+ "filter", "when", "validate", "onWhen", "on-when",
+ "handled", "continued", "retryWhile", "retry-while",
+ "completionPredicate", "completion-predicate",
+ "completion", "loopDoWhile", "loop-do-while");
// Properties quick-doc caches (invalidated when catalog version changes)
private String propsCatalogVersion;
@@ -125,840 +103,30 @@ class SourceTab extends AbstractTab {
private static final Pattern YAML_KEY_PATTERN = Pattern.compile(
"^\\s*-?\\s*([a-zA-Z][a-zA-Z0-9]*)\\s*:");
- private static final Set<String> LINKABLE_KEYWORDS = Set.of(
- "to", "toD", "wireTap", "enrich", "pollEnrich", "deadLetterChannel");
-
- record RouteEntry(String routeId, String fromUri, String filePath, int fromLine) {
- }
-
- record ToEntry(String routeId, String toUri, String filePath, int toLine) {
- }
-
- private List<RouteEntry> routeIndex = Collections.emptyList();
- private List<ToEntry> toIndex = Collections.emptyList();
- private final GotoRoutePopup gotoRoutePopup = new GotoRoutePopup();
- private final GotoSourceNodePopup gotoSourceNodePopup = new GotoSourceNodePopup();
- private final FileActionsPopup fileActionsPopup = new FileActionsPopup();
-
- SourceTab(MonitorContext ctx) {
- super(ctx);
- sourceViewer.setNotificationCallback((msg, error) -> {
- if (ctx.notificationCallback != null) {
- ctx.notificationCallback.accept(msg, error);
- }
- });
- sourceViewer.setOnFileCreated(this::refreshFiles);
- sourceViewer.setOnFileLoaded(p -> {
- if (isCamelSourceFile(p)) {
- sourceViewer.setJumpLinks(computeJumpLinks(p));
- }
- });
- sourceViewer.setValidateOnSave(ctx.validateOnSave);
- sourceViewer.setOnJumpLink(this::handleJumpLink);
- }
-
- boolean isSourceViewerEditMode() {
- return sourceViewer.isEditMode();
- }
-
- boolean isSourceViewerTextInputActive() {
- // also treat the file-actions menu as active input so global single-key shortcuts (q, ?, ...)
- // do not fire while the menu, its name prompt, or delete confirmation is open
- return sourceViewer.isTextInputActive() || fileActionsPopup.isVisible();
- }
-
- void handlePaste(String text) {
- sourceViewer.handlePaste(text);
- }
-
- // ---- MonitorTab ----
-
- @Override
... 13076 lines suppressed ...