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/17 14:52:30 UTC

(camel) branch main updated: CAMEL-24796: camel-jbang - AI panel with Ollama sizes the context for the machine, compacts on measured tokens, and shows what a question cost (#26550)

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 ce1bad858804 CAMEL-24796: camel-jbang - AI panel with Ollama sizes the context for the machine, compacts on measured tokens, and shows what a question cost (#26550)
ce1bad858804 is described below

commit ce1bad8588047678bf875c18f1eb54aaaf2e8c37
Author: Claus Ibsen <cl...@gmail.com>
AuthorDate: Thu Sep 17 16:52:21 2026 +0200

    CAMEL-24796: camel-jbang - AI panel with Ollama sizes the context for the machine, compacts on measured tokens, and shows what a question cost (#26550)
    
    * CAMEL-24796: camel-jbang - AI panel with Ollama compacts on measured tokens, compacts harder, and asks for a 32k to 64k context
    
    Measured with the Ollama tab: the panel compacted its history when a
    character estimate passed 16k tokens while Ollama had measured 24.8k, freed
    3.8k tokens because the previous turn was kept intact, and the next request
    prefilled all 21k tokens again (40 s) since rewriting history resets the
    prompt cache.
    
    LlmClient (camel-jbang-core) now chooses the num_ctx it asks Ollama for
    once per model: OLLAMA_CONTEXT_LENGTH when set; else the window of the
    model when Ollama already has it loaded, raised to 32k when smaller, so the
    TUI never forces a reload against another client; else 64k when the model's
    weights plus the KV cache of that window fit the machine's memory, computed
    from /api/tags and /api/show (layers, KV heads, key and value length, and
    the full-attention interval of hybrid models), else 32k. The resolved window
    is public for the panel and the Ollama tab.
    
    The AI panel decides compaction on the prompt size Ollama measured for the
    last request against half of min(window, 64k), with the character estimate
    only as fallback. A local compaction now also shrinks the previous turn's
    tool results and drops the oldest turns until the history is about a
    quarter of the window, so one compaction buys several quiet turns, and it
    prints one line with the sizes before and after and how long the next reply
    will take to start at the prefill speed measured on a cold request. /compact
    prints the same line; /context shows window, compaction point and last
    prompt; the panel title shows the fill as "ctx 34%". Hosted providers keep
    their per-turn compaction.
    
    The Ollama tab header shows what the panel asks for and where it compacts
    next to what Ollama allocated and the model maximum, and the turns line
    colours against the compaction point. Documented in the user manual, the
    F1 help and the 4.23 upgrade guide.
    
    Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
    Signed-off-by: Claus Ibsen <cl...@gmail.com>
    
    * CAMEL-24796: camel-jbang - AI commands doc explains the Ollama context window and keep-alive
    
    The camel ask, explain and harden commands share the LLM client with the
    TUI, so the window policy and the 30 minute keep-alive apply to them too;
    the AI commands page now says so and points at the TUI manual for how the
    panel manages its history inside the window.
    
    Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
    Signed-off-by: Claus Ibsen <cl...@gmail.com>
    
    * CAMEL-24796: camel-jbang - context windows read 64k of 256k, and a question's wall time starts at its first request
    
    Context windows are powers of two and known by their binary names, so both
    token formatters print 32k, 64k and 256k for them instead of 32.8k, 65.5k
    and 262,144. The per-question wall time on the Ollama tab counted from the
    first reply instead of the first request, which made a cold question look
    shorter than its own time to first token.
    
    Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
    Signed-off-by: Claus Ibsen <cl...@gmail.com>
    
    * CAMEL-24796: camel-jbang - Ollama tab header separates the model's maximum context from the loaded window
    
    "ctx 64k of 256k" read like a range. The model's maximum is now a property
    on the model line ("max ctx 256k"); the loaded line says only what is in
    effect ("ctx 64k") and where the AI panel compacts, naming the panel's own
    request only when it differs from the loaded window.
    
    Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
    Signed-off-by: Claus Ibsen <cl...@gmail.com>
    
    * CAMEL-24796: camel-jbang - Ollama tab reads the runner's slot twice a second while generating and every two seconds when idle
    
    The slot was read on every refresh cycle while the tab showed, which
    llama-server logs at the verbosity Ollama starts it with. The live view only
    needs that rate during generation; an idle runner is read every two seconds.
    The F1 help states every polling interval.
    
    Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
    Signed-off-by: Claus Ibsen <cl...@gmail.com>
    
    * CAMEL-24796: camel-jbang - AI answers end with a byline naming tool calls, requests, tokens and the limit; the wrap-up keeps the cached prefix
    
    Every AI panel answer now carries a byline such as
    "61.1s · 25 tool calls, limit reached (2.5s in tools) · 26 requests · 231.3k tokens · ctx 18%",
    so the cost of a question is visible without the Ollama tab.
    
    When the 25 tool-call limit is reached the wrap-up request keeps the tool
    definitions in the prompt so Ollama's prompt cache holds; a model that calls a
    tool regardless is asked once more without tools. Both are recorded with the
    reason "limit", which the Ollama tab shows in yellow on the question row and
    its last step. A smaller prompt inside one question is no longer counted as a
    compaction; only a smaller first prompt of the next question is.
    
    Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
    Signed-off-by: Claus Ibsen <cl...@gmail.com>
    
    * CAMEL-24796: camel-jbang - Ollama tab colours a costly question: request count yellow from 10 and red at the tool-call limit, total time yellow from 30s and orange from a minute
    
    Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
    Signed-off-by: Claus Ibsen <cl...@gmail.com>
    
    * CAMEL-24796: camel-jbang - Ollama tab lists the question the AI panel is working on as "working" with a running clock, from the moment it is asked until the turn ends
    
    Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
    Signed-off-by: Claus Ibsen <cl...@gmail.com>
    
    * CAMEL-24796: camel-jbang - AI Usage says the average per question and per request, and the model table's column is AVG/REQ
    
    Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
    Signed-off-by: Claus Ibsen <cl...@gmail.com>
    
    * CAMEL-24796: camel-jbang - Ollama tab's requests table gets a footer with the session's average per question, and the JSON a questionSummary
    
    Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
    Signed-off-by: Claus Ibsen <cl...@gmail.com>
    
    * CAMEL-24796: camel-jbang - Ollama context window is resolved in the background when the panel connects and after a model switch, and read without a lock once known
    
    Review feedback on #26550.
    
    Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
    Signed-off-by: Claus Ibsen <cl...@gmail.com>
    
    ---------
    
    Signed-off-by: Claus Ibsen <cl...@gmail.com>
    Co-authored-by: Claude Fable 5.1 <no...@anthropic.com>
---
 .../ROOT/pages/camel-4x-upgrade-guide-4_23.adoc    |  10 +-
 .../modules/ROOT/pages/camel-jbang-ai.adoc         |  21 ++
 .../modules/ROOT/pages/camel-jbang-tui.adoc        |  62 ++--
 .../camel/dsl/jbang/core/commands/LlmClient.java   | 256 +++++++++++++-
 .../core/commands/LlmClientOllamaContextTest.java  | 212 ++++++++++++
 .../camel/dsl/jbang/core/commands/tui/AiPanel.java | 366 ++++++++++++++++++---
 .../dsl/jbang/core/commands/tui/OllamaMonitor.java | 203 +++++++++++-
 .../dsl/jbang/core/commands/tui/OllamaTab.java     | 155 ++++++++-
 .../src/main/resources/tui/help/ollama.md          |  49 ++-
 .../commands/tui/AiPanelHistoryCompactionTest.java |  71 ++++
 .../dsl/jbang/core/commands/tui/AiPanelTest.java   |  91 ++++-
 .../jbang/core/commands/tui/OllamaMonitorTest.java | 108 +++++-
 .../core/commands/tui/OllamaTabRenderTest.java     | 110 ++++++-
 13 files changed, 1588 insertions(+), 126 deletions(-)

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 02b2d8e8f67f..943072cffb7d 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
@@ -790,9 +790,13 @@ The F8 AI panel now sends only a core subset of its `tui_*` tools to local provi
 provider on `localhost`); the drawing, animation and automation tools are left out to keep the
 prompt small for local models. Hosted providers are unaffected. Use `/tools full` in the panel, or
 set `camel.tui.ai.tools=full`, to restore the previous behaviour. Requests to Ollama now also set
-`keep_alive` to 30 minutes and `num_ctx` to 32768 (or `OLLAMA_CONTEXT_LENGTH` when that is set in the
-environment), which can cause a one-time model reload if the model was loaded with a different
-context size.
+`keep_alive` to 30 minutes and a `num_ctx` chosen once per model: `OLLAMA_CONTEXT_LENGTH` when set in the
+environment, else the window of the model when Ollama already has it loaded (raised to 32768 when
+smaller), else 65536 when the model's weights plus the KV cache of that window fit the machine's memory
+and 32768 otherwise. The same rule applies to `camel ask` and the other CLI commands that use Ollama.
+Asking for a window Ollama does not have loaded causes a one-time model reload. The AI panel compacts
+its conversation history for a local provider once the prompt Ollama measured passes half that window
+(at most half of 65536) and prints a line saying so, instead of the earlier estimate-based threshold.
 
 `camel tui --record` is now rejected when combined with `--web`. The recording configuration applies
 to the whole process, so a browser session served by `--web` would be recorded into the same `.cast`
diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-ai.adoc b/docs/user-manual/modules/ROOT/pages/camel-jbang-ai.adoc
index 8c63c22e731f..47a36e82fbcd 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-ai.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-ai.adoc
@@ -178,6 +178,27 @@ On Apple Silicon, all RAM is unified — a 64 GB M-series Mac can run `llama3.3:
 Use the default (GGUF) tags rather than the `-mlx` tags: the Ollama MLX engine cannot yet reuse the
 cached prompt for Qwen 3.x models, so every question re-processes the whole prompt.
 
+==== Context window and keep-alive
+
+Every Ollama request from the CLI (`camel ask`, `camel explain`, `camel harden`) and from the TUI asks
+Ollama to keep the model loaded for 30 minutes, so a follow-up question reuses the cached prompt instead
+of reloading the model, and for a context window (`num_ctx`) chosen once per model:
+
+1. `OLLAMA_CONTEXT_LENGTH` in the environment wins when set.
+2. If Ollama already has the model loaded, its window is adopted (raised to 32k when smaller), so the CLI
+   never makes Ollama reload a model that another client is using. A request with a different `num_ctx`
+   makes Ollama reload the model, which costs a cold start of tens of seconds and throws away the prompt
+   cache of every client.
+3. Otherwise 64k when the model's weights plus the KV cache of a 64k window fit the machine's memory,
+   judged from what `ollama show` reports about the model, else 32k. A window that does not fit makes
+   Ollama move layers to the CPU, which slows generation far more than a smaller window costs.
+
+The tool-calling prompt alone is about 4.5k tokens, which is why 32k is the floor: Ollama's own default
+on machines with less than 24 GB is 4k and would truncate it. Keep all your Ollama clients on the same
+value; if you set `OLLAMA_CONTEXT_LENGTH` for the CLI, set it for `ollama serve` too. The TUI's Ollama
+tab shows the window in use, and xref:camel-jbang-tui.adoc#_working_with_a_local_ollama_model[Working
+with a local Ollama model] explains how the AI panel manages its history inside it.
+
 === Using an OpenAI-compatible local server
 
 Many local LLM servers expose an OpenAI-compatible API. Use `LLM_API_KEY` and `LLM_BASE_URL`
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 79460dcccf96..eabd716fb5f2 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
@@ -902,8 +902,9 @@ and to any provider on `localhost`, which roughly halves the prompt. Hosted prov
 tool, including the drawing, animation and automation tools. Use `/tools full` in the panel to send
 all tools to a local model too, `/tools core` to trim the set for a hosted one, pick *AI Tools* in
 *F2 -> Settings*, or set `camel.tui.ai.tools` in `.camel-cli.properties`. Ollama requests also ask the server to keep the
-model loaded for 30 minutes and use a 32k context window (`OLLAMA_CONTEXT_LENGTH` overrides it),
-so follow-up questions reuse the cached prompt instead of reloading the model.
+model loaded for 30 minutes and for a context window of 32k or 64k (see <<_working_with_a_local_ollama_model>>;
+`OLLAMA_CONTEXT_LENGTH` overrides it), so follow-up questions reuse the cached prompt instead of reloading
+the model.
 
 ==== Working with a local Ollama model
 
@@ -933,20 +934,27 @@ Ollama tab shows the request count per question as `×N` and the cache hit per q
 with a high count and a short answer is the model exploring, which a smaller, sharper tool set reduces
 (see <<_tool_set_for_local_models>>).
 
-*The context window.* The TUI asks Ollama for a 32k context window; `OLLAMA_CONTEXT_LENGTH` overrides
-it. The static prefix of system prompt and core tools is about 4.5k tokens, 14% of the window, and each
-question with tool calls adds another 2k to 4k of history. The panel compacts the history once it
-grows past roughly 16k tokens (see `/compact` under <<_ai_panel_slash_commands>>). Compacting rewrites
-the history, which invalidates Ollama's prompt cache, so the request after a compaction prefills the
-whole prompt again: about 40 seconds for a 21k-token prompt. That is why the panel compacts local
-history late and rarely rather than a little on every turn. Two practical rules follow:
-
-* Keep every Ollama client on the same context size. A request with a different `num_ctx` makes
-  Ollama reload the model, which costs a cold start. The TUI's AI panel, `camel ask` and your own routes
-  should agree on the value.
-* A bigger window is cheap in memory for mixture-of-experts models with hybrid attention (this model
-  grows from 22.5 GB at 32k to 23.6 GB at 262k) but every token in it is prefill time after a
-  compaction or a reload, so raise it with a purpose.
+*The context window.* The TUI decides the window it asks Ollama for (`num_ctx`) once per model:
+
+1. `OLLAMA_CONTEXT_LENGTH` in the environment wins when set.
+2. If the model is already loaded, its window is adopted (raised to 32k when smaller), so the TUI never
+   makes Ollama reload a model another client is using. A request with a different `num_ctx` costs a
+   cold start and throws away everyone's prompt cache.
+3. Otherwise 64k when the model's weights plus the KV cache of a 64k window fit the machine's memory,
+   computed from what `ollama show` reports (layers, KV heads, head size), else 32k. Overshooting is
+   worse than being conservative: Ollama then moves layers to the CPU and generation slows to a crawl.
+
+The static prefix of system prompt and core tools is about 4.5k tokens, and each question with tool
+calls adds another 2k to 4k of history. The panel compacts the history once the prompt Ollama measured
+for the last request passes half the window, capped at half of 64k even when a larger window was
+adopted: every token of history is prefill time again after a cache loss (an idle unload after 30
+minutes, another client, a restart), and 64k at a few hundred tokens per second is already well over a
+minute. Compacting rewrites the history, which invalidates Ollama's prompt cache, so the request after
+a compaction prefills the whole prompt again: about 40 seconds for a 21k-token prompt. The panel
+therefore compacts local history rarely and then thoroughly, down to about a quarter of the window,
+and prints one line saying what it did and how long the next reply will take to start. `/compact` does
+the same on demand with the same line; `/context` shows the window, the compaction point and the last
+measured prompt; the panel title shows the fill as `ctx 34%`.
 
 *Choosing the model.* With no `camel.tui.ai.model` set the panel takes `llama3.2` when it is installed,
 otherwise the first installed model; run `/model <name>` in the panel or set *AI Model* in
@@ -958,7 +966,8 @@ whether Ollama was found, which models are installed and whether they are large
 *Where to look.* The <<_ollama>> tab is the instrument for all of the above: tokens per second live and
 per request, time to first token with cold starts marked, cache hit, how full the context window is
 and how it grows per question, GPU and process load, and one line per question with the requests it
-took. In the AI panel, `/context` prints what the next request will cost, `/usage` and *Ctrl+U* the
+took, the question being answered right now on top with `working` as its reason and its time counting
+up, and a footer with the average per question. In the AI panel, `/context` prints what the next request will cost, `/usage` and *Ctrl+U* the
 session totals per question.
 
 *Remote and containerised Ollama.* Everything above applies to an Ollama on another host or inside
@@ -1074,10 +1083,10 @@ cycles backward.
 | Show which tool set is sent to the model, or switch it. `auto` (default) sends the core set to local providers and every tool to hosted ones; the choice is saved as `camel.tui.ai.tools`.
 
 | `/context` (`/ctx`)
-| Show what the next request costs: provider and model, tool set, static prefix size, history size and the session total. Useful with local models, where prompt size is time.
+| Show what the next request costs: provider and model, tool set, static prefix size, history size and the session total, and with Ollama the context window, the prompt size above which the history is compacted and the last measured prompt. Useful with local models, where prompt size is time.
 
 | `/compact`
-| Shrink the conversation history sent to the model right away: older tool results are cut to their first lines and the oldest turns are dropped. With a hosted provider the panel does this automatically after each answer for all but the latest turn. With Ollama or another `localhost` provider it waits until the history grows past roughly 16k tokens, because a local server can reuse its cached prompt only while the conversation is appended to, and rewriting the history would make it proce [...]
+| Shrink the conversation history sent to the model right away: older tool results are cut to their first lines and the oldest turns are dropped. With a hosted provider the panel does this automatically after each answer for all but the latest turn. With Ollama or another `localhost` provider it waits until the prompt Ollama measured passes half the context window (see <<_working_with_a_local_ollama_model>>), then compacts thoroughly, because a local server can reuse its cached prompt on [...]
 
 | `/retry`
 | Send the last question again, starting from a clean turn in the model history.
@@ -1113,13 +1122,24 @@ cycles backward.
 Submitted prompts (including slash commands) participate in AI prompt history when
 `camel.tui.ai.promptHistory` is not `0`. Use *↑*/*↓* on the prompt line to recall them.
 
+Every answer ends with a byline saying what the question cost: the time it took, how many tools the
+model called and the time spent in them, the number of requests, the tokens and, with Ollama, how full
+the context window got (for example `61.1s · 25 tool calls, limit reached (2.5s in tools) · 26 requests
+· 231.3k tokens · ctx 18%`). The panel allows 25 tool calls per question. When the model reaches that
+the byline says `limit reached`, the panel asks the model to answer from what it has found so far, and
+the <<_ollama>> tab shows the question's request count in red with `limit` as its reason (the count is
+yellow from 10 requests, and the total time yellow from 30 seconds and orange from a minute). A question
+that runs into the limit is usually a tool that makes the model guess, not a weak model: the AI log
+shows which one.
+
 Press *Ctrl+U* while the AI panel is open to toggle the AI Usage view. It shows token consumption from
 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. 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
+model) and *Tool time* (running the TUI tools the model called, with the number of calls), the summary line gives the
+average time per question (and per request in brackets), the model table has an *AVG/REQ* column with
+the average per request for that model, 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
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/LlmClient.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/LlmClient.java
index 29434e885e6c..359fadd07618 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/LlmClient.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/LlmClient.java
@@ -18,6 +18,7 @@ package org.apache.camel.dsl.jbang.core.commands;
 
 import java.io.BufferedReader;
 import java.io.InputStreamReader;
+import java.lang.management.ManagementFactory;
 import java.net.URI;
 import java.net.http.HttpClient;
 import java.net.http.HttpRequest;
@@ -27,12 +28,15 @@ import java.nio.file.Files;
 import java.nio.file.Path;
 import java.time.Duration;
 import java.util.ArrayList;
+import java.util.Collection;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
 
+import com.sun.management.OperatingSystemMXBean;
 import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
 import org.apache.camel.dsl.jbang.core.common.Printer;
 import org.apache.camel.util.json.JsonArray;
@@ -60,11 +64,18 @@ public class LlmClient {
      */
     private static final String OLLAMA_KEEP_ALIVE = "30m";
     /**
-     * Context window requested from Ollama. The tool-calling system prompt alone is several thousand tokens, and older
-     * Ollama releases default to 4096 which silently truncates it; 32k leaves room for a long conversation with tool
-     * results while keeping the KV cache modest. {@code OLLAMA_CONTEXT_LENGTH} in the environment overrides it.
+     * Smallest context window requested from Ollama. The tool-calling system prompt and the tool schemas alone are
+     * several thousand tokens, and Ollama's memory-based default is 4k on machines with less than 24 GiB, which would
+     * silently truncate the prompt. See {@link #ollamaContextWindow()} for the whole policy;
+     * {@code OLLAMA_CONTEXT_LENGTH} in the environment overrides it.
      */
-    private static final int OLLAMA_NUM_CTX = 32768;
+    public static final int OLLAMA_MIN_CONTEXT = 32_768;
+    /**
+     * Largest context window requested on the client's own initiative. Every token of history is prefill time again
+     * after a cache loss (idle unload, another client with a different window, a restart), and 64k at a few hundred
+     * tokens per second is already well over a minute.
+     */
+    public static final int OLLAMA_MAX_CONTEXT = 65_536;
     private static final String DEFAULT_WATSONX_URL = "https://us-south.ml.cloud.ibm.com";
     private static final String DEFAULT_WATSONX_MODEL = "ibm/granite-4-1-8b-instruct";
     private static final String DEFAULT_AZURE_API_VERSION = "2024-10-21";
@@ -169,6 +180,10 @@ public class LlmClient {
     }
 
     public static String formatTokens(int tokens) {
+        // context windows are powers of two and known by their binary names: 32k, 64k, 256k
+        if (tokens >= 1024 && tokens % 1024 == 0 && tokens < 1_048_576) {
+            return (tokens / 1024) + "k";
+        }
         if (tokens >= 1000) {
             double k = tokens / 1000.0;
             if (k == (int) k) {
@@ -999,11 +1014,91 @@ public class LlmClient {
     private JsonObject ollamaOptions() {
         JsonObject options = new JsonObject();
         options.put("temperature", temperature);
-        options.put("num_ctx", ollamaNumCtx());
+        options.put("num_ctx", ollamaContextWindow());
         return options;
     }
 
-    static int ollamaNumCtx() {
+    // ---- Ollama context window ----
+
+    /** The window resolved for one model at one endpoint; replaced as a whole so readers need no lock. */
+    private record ResolvedOllamaContext(String model, String url, int window) {
+    }
+
+    private volatile ResolvedOllamaContext resolvedOllamaContext;
+
+    /**
+     * The context window ({@code num_ctx}) this client asks Ollama for with the current model, resolved once per model
+     * and endpoint:
+     * <ol>
+     * <li>{@code OLLAMA_CONTEXT_LENGTH} in the environment wins when set.</li>
+     * <li>If Ollama already has the model loaded, its window is adopted (raised to {@link #OLLAMA_MIN_CONTEXT} when
+     * smaller), because a request with a different {@code num_ctx} makes Ollama reload the model, which costs a cold
+     * start and throws away the prompt cache of every other client.</li>
+     * <li>Otherwise {@link #OLLAMA_MAX_CONTEXT} when the model's weights plus the KV cache of that window fit the
+     * machine's memory, else {@link #OLLAMA_MIN_CONTEXT}. Overshooting is worse than being conservative: Ollama then
+     * moves layers to the CPU and generation slows to a crawl.</li>
+     * </ol>
+     * Callers that manage a conversation should budget their history against {@code min(window, OLLAMA_MAX_CONTEXT)}
+     * even when a larger window was adopted, so a cache loss never means minutes of prefill.
+     */
+    public int ollamaContextWindow() {
+        Integer cached = resolvedOllamaContextWindow();
+        if (cached != null) {
+            return cached;
+        }
+        synchronized (this) {
+            cached = resolvedOllamaContextWindow();
+            if (cached != null) {
+                return cached;
+            }
+            int window = resolveOllamaContextWindow(totalPhysicalMemory());
+            resolvedOllamaContext = new ResolvedOllamaContext(model, url, window);
+            return window;
+        }
+    }
+
+    /** The window already resolved for the current model and endpoint, or null when the next request resolves it. */
+    public Integer resolvedOllamaContextWindow() {
+        ResolvedOllamaContext r = resolvedOllamaContext;
+        return r != null && Objects.equals(r.model(), model) && Objects.equals(r.url(), url) ? r.window() : null;
+    }
+
+    /**
+     * Resolves the window on a daemon thread so it is known before the first request needs it. Resolution asks Ollama
+     * three questions ({@code /api/ps}, {@code /api/tags}, {@code /api/show}); against a local server that is
+     * milliseconds, but done lazily it would sit between the user's question and the first request. Call it when the
+     * client is connected and after a model switch; a request arriving earlier resolves synchronously as before.
+     */
+    public void resolveOllamaContextWindowInBackground() {
+        if (apiType != ApiType.ollama || resolvedOllamaContextWindow() != null) {
+            return;
+        }
+        Thread t = new Thread(this::ollamaContextWindow, "llm-ollama-context");
+        t.setDaemon(true);
+        t.start();
+    }
+
+    /** Forgets the resolved window, e.g. after the user switched model; the next request resolves it again. */
+    public void resetOllamaContextWindow() {
+        resolvedOllamaContext = null;
+    }
+
+    int resolveOllamaContextWindow(long totalMemoryBytes) {
+        Integer env = ollamaContextLengthFromEnv();
+        if (env != null) {
+            return env;
+        }
+        if (url == null || model == null) {
+            return OLLAMA_MIN_CONTEXT;
+        }
+        long loaded = loadedOllamaContext();
+        if (loaded > 0) {
+            return (int) Math.max(OLLAMA_MIN_CONTEXT, Math.min(loaded, Integer.MAX_VALUE));
+        }
+        return ollamaContextFits(OLLAMA_MAX_CONTEXT, totalMemoryBytes) ? OLLAMA_MAX_CONTEXT : OLLAMA_MIN_CONTEXT;
+    }
+
+    static Integer ollamaContextLengthFromEnv() {
         String env = System.getenv("OLLAMA_CONTEXT_LENGTH");
         if (env != null && !env.isBlank()) {
             try {
@@ -1012,10 +1107,155 @@ public class LlmClient {
                     return value;
                 }
             } catch (NumberFormatException e) {
-                // fall through to the default
+                // fall through to the policy
+            }
+        }
+        return null;
+    }
+
+    /** Context length of the current model if Ollama already has it loaded ({@code /api/ps}), 0 otherwise. */
+    long loadedOllamaContext() {
+        JsonObject ps = sendGetRequest(url + "/api/ps", Map.of());
+        if (ps == null) {
+            return 0;
+        }
+        Collection<?> loaded = ps.getCollection("models");
+        if (loaded == null) {
+            return 0;
+        }
+        for (Object o : loaded) {
+            if (o instanceof JsonObject m && ollamaModelMatches(model, m.getString("name"))) {
+                return getLongValue(m, "context_length");
             }
         }
-        return OLLAMA_NUM_CTX;
+        return 0;
+    }
+
+    /** {@code llama3.2} matches {@code llama3.2:latest}; a name with a tag must match exactly. */
+    static boolean ollamaModelMatches(String wanted, String candidate) {
+        if (wanted == null || candidate == null) {
+            return false;
+        }
+        if (wanted.equals(candidate)) {
+            return true;
+        }
+        return !wanted.contains(":") && candidate.startsWith(wanted + ":");
+    }
+
+    /**
+     * Whether the current model's weights plus the KV cache of a {@code contextTokens} window fit in
+     * {@code totalMemoryBytes}: weights from {@code /api/tags}, the KV cost per token from the architecture facts in
+     * {@code /api/show}. Unknown facts count as "does not fit".
+     */
+    boolean ollamaContextFits(int contextTokens, long totalMemoryBytes) {
+        if (totalMemoryBytes <= 0) {
+            return false;
+        }
+        long weights = ollamaWeightBytes();
+        if (weights <= 0) {
+            return false;
+        }
+        JsonObject body = new JsonObject();
+        body.put("model", model);
+        JsonObject show = postJsonQuietly(url + "/api/show", body);
+        long perToken = ollamaKvBytesPerToken(show);
+        if (perToken <= 0) {
+            return false;
+        }
+        return ollamaContextFits(weights, perToken, contextTokens, totalMemoryBytes);
+    }
+
+    /**
+     * Four fifths of the memory less a gibibyte for compute buffers: roughly what Apple silicon lets the GPU wire and a
+     * fair share of a machine that also runs the integration and the TUI. A heuristic, deliberately on the safe side.
+     */
+    static boolean ollamaContextFits(long weightBytes, long kvBytesPerToken, int contextTokens, long totalMemoryBytes) {
+        long budget = totalMemoryBytes / 5 * 4 - (1L << 30);
+        return weightBytes + kvBytesPerToken * contextTokens <= budget;
+    }
+
+    /**
+     * Bytes of KV cache per context token: 16-bit keys and values for each KV head of each layer that keeps a full
+     * attention cache. Hybrid models (Qwen 3.5/3.6 MoE) report {@code full_attention_interval}; only every n-th layer
+     * holds a cache, the others carry a fixed-size state. Head dimensions come from {@code attention.key_length} and
+     * {@code attention.value_length} when reported, else from the embedding size over the head count.
+     */
+    static long ollamaKvBytesPerToken(JsonObject show) {
+        if (show == null || !(show.get("model_info") instanceof JsonObject info)) {
+            return 0;
+        }
+        String arch = info.getString("general.architecture");
+        if (arch == null) {
+            return 0;
+        }
+        long layers = getLongValue(info, arch + ".block_count");
+        long heads = getLongValue(info, arch + ".attention.head_count");
+        long kvHeads = getLongValue(info, arch + ".attention.head_count_kv");
+        long embedding = getLongValue(info, arch + ".embedding_length");
+        long keyLength = getLongValue(info, arch + ".attention.key_length");
+        long valueLength = getLongValue(info, arch + ".attention.value_length");
+        long interval = getLongValue(info, arch + ".full_attention_interval");
+        if (kvHeads <= 0) {
+            kvHeads = heads;
+        }
+        if (keyLength <= 0) {
+            keyLength = heads > 0 ? embedding / heads : 0;
+        }
+        if (valueLength <= 0) {
+            valueLength = keyLength;
+        }
+        long cacheLayers = interval > 1 ? layers / interval : layers;
+        if (cacheLayers <= 0 || kvHeads <= 0 || keyLength <= 0) {
+            return 0;
+        }
+        return cacheLayers * kvHeads * (keyLength + valueLength) * 2L;
+    }
+
+    /** A short POST with the health-check timeout and no console output, for probes outside a chat request. */
+    private JsonObject postJsonQuietly(String requestUrl, JsonObject body) {
+        try {
+            HttpRequest request = HttpRequest.newBuilder()
+                    .uri(URI.create(requestUrl))
+                    .timeout(Duration.ofSeconds(HEALTH_CHECK_TIMEOUT_SECONDS))
+                    .header("Content-Type", "application/json")
+                    .POST(HttpRequest.BodyPublishers.ofString(body.toJson()))
+                    .build();
+            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
+            if (response.statusCode() == 200) {
+                return (JsonObject) Jsoner.deserialize(response.body());
+            }
+        } catch (Exception e) {
+            // the caller treats an unknown answer as "does not fit"
+        }
+        return null;
+    }
+
+    private long ollamaWeightBytes() {
+        JsonObject tags = sendGetRequest(url + "/api/tags", Map.of());
+        if (tags == null) {
+            return 0;
+        }
+        Collection<?> models = tags.getCollection("models");
+        if (models == null) {
+            return 0;
+        }
+        for (Object o : models) {
+            if (o instanceof JsonObject m && ollamaModelMatches(model, m.getString("name"))) {
+                return getLongValue(m, "size");
+            }
+        }
+        return 0;
+    }
+
+    static long totalPhysicalMemory() {
+        try {
+            if (ManagementFactory.getOperatingSystemMXBean() instanceof OperatingSystemMXBean os) {
+                return os.getTotalMemorySize();
+            }
+        } catch (Throwable e) {
+            // not available on this JVM
+        }
+        return 0;
     }
 
     // ---- Ollama native chat with tools ----
diff --git a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/LlmClientOllamaContextTest.java b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/LlmClientOllamaContextTest.java
new file mode 100644
index 000000000000..e6689939ee73
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/LlmClientOllamaContextTest.java
@@ -0,0 +1,212 @@
+/*
+ * 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;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import com.sun.net.httpserver.HttpServer;
+import org.apache.camel.util.json.JsonObject;
+import org.apache.camel.util.json.Jsoner;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The context window the client asks Ollama for: adopt a loaded model's window, else 64k when it fits, else 32k. A
+ * local {@link HttpServer} plays Ollama's {@code /api/ps}, {@code /api/tags} and {@code /api/show}. The environment
+ * override cannot be tested here (it wins over everything), so the tests are skipped when it is set.
+ */
+@DisabledIfEnvironmentVariable(named = "OLLAMA_CONTEXT_LENGTH", matches = ".+")
+class LlmClientOllamaContextTest {
+
+    private static final long GIB = 1L << 30;
+
+    /**
+     * qwen3.6:35b-a3b as Ollama 0.33 describes it: 41 layers of which every fourth keeps a full attention cache, 2 KV
+     * heads with 256-wide keys and values, 22.6 GB of weights.
+     */
+    private static final String SHOW_MOE = """
+            {"model_info":{"general.architecture":"qwen35moe","qwen35moe.block_count":41,
+            "qwen35moe.attention.head_count":16,"qwen35moe.attention.head_count_kv":2,
+            "qwen35moe.attention.key_length":256,"qwen35moe.attention.value_length":256,
+            "qwen35moe.full_attention_interval":4,"qwen35moe.embedding_length":2048}}
+            """;
+    private static final long MOE_WEIGHTS = 22_621_000_000L;
+    /** 10 cache layers x 2 KV heads x (256 + 256) x 2 bytes. */
+    private static final long MOE_KV_PER_TOKEN = 10L * 2 * 512 * 2;
+    /** A dense 32B: 64 layers, 8 KV heads of 128, 20 GB of weights. */
+    private static final String SHOW_DENSE = """
+            {"model_info":{"general.architecture":"qwen2","qwen2.block_count":64,
+            "qwen2.attention.head_count":40,"qwen2.attention.head_count_kv":8,"qwen2.embedding_length":5120}}
+            """;
+
+    private HttpServer server;
+
+    @AfterEach
+    void stopServer() {
+        if (server != null) {
+            server.stop(0);
+        }
+    }
+
+    @Test
+    void adoptsTheWindowOfAModelThatIsAlreadyLoaded() throws IOException {
+        LlmClient client = client("qwen3.6:35b-a3b", 262144, SHOW_MOE, MOE_WEIGHTS);
+        assertEquals(262144, client.resolveOllamaContextWindow(64 * GIB));
+    }
+
+    @Test
+    void raisesASmallLoadedWindowToTheMinimum() throws IOException {
+        LlmClient client = client("qwen3.6:35b-a3b", 4096, SHOW_MOE, MOE_WEIGHTS);
+        assertEquals(LlmClient.OLLAMA_MIN_CONTEXT, client.resolveOllamaContextWindow(64 * GIB));
+    }
+
+    @Test
+    void asksForTheMaximumWhenTheModelIsNotLoadedAndItsCacheFits() throws IOException {
+        LlmClient client = client("qwen3.6:35b-a3b", 0, SHOW_MOE, MOE_WEIGHTS);
+        // 22.6 GB of weights plus 2.5 GiB of cache for 64k: fits 32 GB and 64 GB machines
+        assertEquals(LlmClient.OLLAMA_MAX_CONTEXT, client.resolveOllamaContextWindow(64 * GIB));
+        assertEquals(LlmClient.OLLAMA_MAX_CONTEXT, client.resolveOllamaContextWindow(32 * GIB));
+        // but not a 16 GB machine, where the weights alone exceed the share the GPU can wire
+        assertEquals(LlmClient.OLLAMA_MIN_CONTEXT, client.resolveOllamaContextWindow(16 * GIB));
+    }
+
+    @Test
+    void staysAtTheMinimumForADenseModelWhoseCacheWouldNotFit() throws IOException {
+        LlmClient client = client("qwen2.5:32b", 0, SHOW_DENSE, 20L * GIB);
+        // 64 layers x 8 KV heads x 128 x 4 bytes = 256 KB per token: 16 GB for 64k on top of 20 GB of weights
+        assertEquals(LlmClient.OLLAMA_MIN_CONTEXT, client.resolveOllamaContextWindow(32 * GIB));
+        assertEquals(LlmClient.OLLAMA_MAX_CONTEXT, client.resolveOllamaContextWindow(64 * GIB));
+    }
+
+    @Test
+    void fallsBackToTheMinimumWhenOllamaDoesNotAnswer() {
+        LlmClient client = LlmClient.create().withApiType(LlmClient.ApiType.ollama)
+                .withUrl("http://127.0.0.1:1").withModel("qwen3.6:35b-a3b");
+        assertEquals(LlmClient.OLLAMA_MIN_CONTEXT, client.resolveOllamaContextWindow(64 * GIB));
+    }
+
+    @Test
+    void resolvedWindowIsCachedPerModelAndForgottenOnReset() throws IOException {
+        LlmClient client = client("qwen3.6:35b-a3b", 262144, SHOW_MOE, MOE_WEIGHTS);
+        assertEquals(262144, client.ollamaContextWindow());
+        server.stop(0);
+        server = null;
+        // still the cached value although the server is gone
+        assertEquals(262144, client.ollamaContextWindow());
+        client.resetOllamaContextWindow();
+        assertEquals(LlmClient.OLLAMA_MIN_CONTEXT, client.ollamaContextWindow());
+    }
+
+    @Test
+    void theWindowCanBeResolvedAheadOfTheFirstRequest() throws IOException {
+        LlmClient client = client("qwen3.6:35b-a3b", 65536, SHOW_MOE, MOE_WEIGHTS);
+        assertNull(client.resolvedOllamaContextWindow(), "nothing resolved until asked");
+
+        client.resolveOllamaContextWindowInBackground();
+        await().atMost(10, TimeUnit.SECONDS).until(() -> client.resolvedOllamaContextWindow() != null);
+
+        // the server can go: the first request finds the window without asking
+        server.stop(0);
+        server = null;
+        assertEquals(65536, client.ollamaContextWindow());
+
+        // a model switch invalidates it, and a later warm-up resolves for the new model (no server: the minimum)
+        client.withModel("other:latest");
+        assertNull(client.resolvedOllamaContextWindow());
+        client.resolveOllamaContextWindowInBackground();
+        await().atMost(20, TimeUnit.SECONDS).until(() -> client.resolvedOllamaContextWindow() != null);
+        assertEquals(LlmClient.OLLAMA_MIN_CONTEXT, client.ollamaContextWindow());
+    }
+
+    @Test
+    void kvBytesPerTokenFromTheArchitectureFacts() {
+        assertEquals(MOE_KV_PER_TOKEN, LlmClient.ollamaKvBytesPerToken(json(SHOW_MOE)));
+        assertEquals(64L * 8 * (128 + 128) * 2, LlmClient.ollamaKvBytesPerToken(json(SHOW_DENSE)));
+        // key_length wins over embedding / heads when present, value_length defaults to it, and missing KV heads fall
+        // back to the head count
+        assertEquals(32L * 32 * (96 + 96) * 2, LlmClient.ollamaKvBytesPerToken(json(
+                "{\"model_info\":{\"general.architecture\":\"llama\",\"llama.block_count\":32,"
+                                                                                    + "\"llama.attention.head_count\":32,\"llama.attention.key_length\":96,\"llama.embedding_length\":4096}}")));
+        assertEquals(0, LlmClient.ollamaKvBytesPerToken(json("{\"details\":{}}")));
+        assertEquals(0, LlmClient.ollamaKvBytesPerToken(null));
+    }
+
+    @Test
+    void fitRuleLeavesRoomForComputeBuffersAndTheSystem() {
+        long perToken = MOE_KV_PER_TOKEN;
+        assertTrue(LlmClient.ollamaContextFits(21 * GIB, perToken, 65_536, 32 * GIB));
+        assertFalse(LlmClient.ollamaContextFits(21 * GIB, perToken, 65_536, 16 * GIB));
+        assertFalse(LlmClient.ollamaContextFits(20 * GIB, 256 * 1024, 65_536, 32 * GIB));
+        // even 32k is 28 GiB for that model; the minimum is requested regardless, this rule only decides 64k
+        assertFalse(LlmClient.ollamaContextFits(20 * GIB, 256 * 1024, 32_768, 32 * GIB));
+        assertTrue(LlmClient.ollamaContextFits(20 * GIB, 256 * 1024, 32_768, 64 * GIB));
+    }
+
+    @Test
+    void modelNamesMatchWithOrWithoutTag() {
+        assertTrue(LlmClient.ollamaModelMatches("qwen3.6:35b-a3b", "qwen3.6:35b-a3b"));
+        assertTrue(LlmClient.ollamaModelMatches("llama3.2", "llama3.2:latest"));
+        assertFalse(LlmClient.ollamaModelMatches("llama3.2:1b", "llama3.2:latest"));
+        assertFalse(LlmClient.ollamaModelMatches("llama3", "llama3.2:latest"));
+        assertFalse(LlmClient.ollamaModelMatches(null, "x"));
+    }
+
+    private LlmClient client(String model, long loadedContext, String showBody, long sizeBytes) throws IOException {
+        String ps = loadedContext > 0
+                ? "{\"models\":[{\"name\":\"" + model + "\",\"model\":\"" + model + "\",\"size\":" + sizeBytes
+                  + ",\"size_vram\":" + sizeBytes + ",\"context_length\":" + loadedContext + "}]}"
+                : "{\"models\":[]}";
+        String tags = "{\"models\":[{\"name\":\"other:latest\",\"size\":1000},{\"name\":\"" + model + "\",\"size\":"
+                      + sizeBytes + "}]}";
+        Map<String, String> routes = Map.of("/api/ps", ps, "/api/tags", tags, "/api/show", showBody);
+        server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+        server.createContext("/", exchange -> {
+            String path = exchange.getRequestURI().getPath();
+            String body = routes.getOrDefault(path, "/".equals(path) ? "Ollama is running" : null);
+            int status = body != null ? 200 : 404;
+            byte[] bytes = (body != null ? body : "not found").getBytes(StandardCharsets.UTF_8);
+            exchange.getResponseHeaders().add("Content-Type", "application/json");
+            exchange.sendResponseHeaders(status, bytes.length);
+            try (OutputStream out = exchange.getResponseBody()) {
+                out.write(bytes);
+            }
+        });
+        server.start();
+        String base = "http://127.0.0.1:" + server.getAddress().getPort();
+        return LlmClient.create().withApiType(LlmClient.ApiType.ollama).withUrl(base).withModel(model);
+    }
+
+    private static JsonObject json(String text) {
+        try {
+            return (JsonObject) Jsoner.deserialize(text);
+        } catch (Exception e) {
+            throw new IllegalArgumentException(e);
+        }
+    }
+}
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 bb046a7e18b0..8a07a06a90c6 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
@@ -112,15 +112,24 @@ class AiPanel {
      */
     static final int MAX_HISTORY_TURNS = 20;
     /**
-     * With a local endpoint the history is left untouched until it is estimated to exceed this many tokens. A local
-     * server (Ollama) keeps the KV cache of the previous request, so a request that merely extends the conversation
-     * only pays for its new tokens, whereas rewriting an earlier message forces the whole tail from that point to be
-     * processed again (measured at one to two seconds per question with a 35B MoE model on Apple silicon, against 0.2s
-     * when the history is untouched). Compacting saves counted tokens, which is what a hosted API bills for, but costs
-     * time locally, so it is deferred until the context actually needs the room: half of the 32k window the client
-     * requests from Ollama, leaving space for the static prefix and the current turn's tool results.
+     * With a local endpoint the history is left untouched until the prompt exceeds a budget. A local server (Ollama)
+     * keeps the KV cache of the previous request, so a request that merely extends the conversation only pays for its
+     * new tokens, whereas rewriting an earlier message forces the whole prompt to be processed again: measured at 40
+     * seconds for a 21k-token prompt with a 35B MoE model on Apple silicon, against half a second for a cached step.
+     * Compacting saves counted tokens, which is what a hosted API bills for, but costs time locally, so it happens
+     * rarely and then thoroughly (see {@link #compactLocalHistory}). The budget is half the context window Ollama
+     * serves, capped at {@link #LOCAL_HISTORY_MAX_WINDOW_TOKENS}, and is compared with the prompt size Ollama measured
+     * for the last request; this constant is the fallback when the window is unknown (another local server) and the
+     * decision must rest on the character estimate.
      */
     static final int LOCAL_HISTORY_BUDGET_TOKENS = 16_000;
+    /**
+     * The panel budgets its history as if the window were at most this large, even when Ollama serves a larger one:
+     * every token of history is prefill time again after a cache loss (idle unload, another client, a restart).
+     */
+    static final int LOCAL_HISTORY_MAX_WINDOW_TOKENS = 65_536;
+    /** Prefill speed assumed for the compaction notice until a cold request has been measured. */
+    static final double ASSUMED_COLD_PREFILL_TOKENS_PER_SECOND = 600;
     private static final int MAX_LOG_ENTRIES = 200;
     private static final DateTimeFormatter TIME_FMT
             = DateTimeFormatter.ofPattern("HH:mm:ss").withZone(ZoneId.systemDefault());
@@ -195,6 +204,12 @@ class AiPanel {
     private long thinkingStartTime;
     private volatile String thinkingVerb;
     private volatile int sessionTotalTokens;
+    /** Prompt size Ollama reported for the most recent request, 0 when unknown or after a compaction. */
+    private volatile int lastMeasuredPromptTokens;
+    /** Context window the current local provider serves, as the client resolved it; 0 when not Ollama. */
+    private volatile int knownContextWindow;
+    /** Prefill speed measured on requests that hit no cache, for the compaction notice. */
+    private volatile double coldPrefillTokensPerSecond;
     /** What the ACP agent last reported in its context window, and how big that window is (0 = not reported). */
     private volatile long acpContextUsed;
     private volatile long acpContextSize;
@@ -319,9 +334,14 @@ class AiPanel {
      * {@code toolCalls} TUI tool calls the model made.
      */
     record ConversationEntry(AiRole role, String text, long elapsedMs, long aiMs, long toolMs, int toolCalls,
-            int totalTokens) {
+            int totalTokens, int requests, boolean limitReached, int contextPercent) {
         ConversationEntry(AiRole role, String text) {
-            this(role, text, -1, 0, 0, 0, 0);
+            this(role, text, -1, 0, 0, 0, 0, 0, false, 0);
+        }
+
+        ConversationEntry(AiRole role, String text, long elapsedMs, long aiMs, long toolMs, int toolCalls,
+                          int totalTokens) {
+            this(role, text, elapsedMs, aiMs, toolMs, toolCalls, totalTokens, 0, false, 0);
         }
 
         /** "5.2s" or, when tools were called, "5.2s, ai 4.1s, tools 1.1s/3". */
@@ -332,6 +352,36 @@ class AiPanel {
             }
             return t;
         }
+
+        /**
+         * The line under an answer: what the question cost in plain words. "61.1s · 25 tool calls, limit reached · 26
+         * requests · 231.3k tokens · ctx 18%". The requests are the model round trips, which is what a local model pays
+         * for and what the Ollama tab counts per question; the tool time is named only when it mattered.
+         */
+        String byline() {
+            StringBuilder sb = new StringBuilder(formatSeconds(elapsedMs));
+            if (toolCalls > 0) {
+                sb.append(" · ").append(toolCalls).append(toolCalls == 1 ? " tool call" : " tool calls");
+                if (limitReached) {
+                    sb.append(", limit reached");
+                }
+                if (toolMs >= 1000) {
+                    sb.append(" (").append(formatSeconds(toolMs)).append(" in tools)");
+                }
+            } else if (limitReached) {
+                sb.append(" · limit reached");
+            }
+            if (requests > 1) {
+                sb.append(" · ").append(requests).append(" requests");
+            }
+            if (totalTokens > 0) {
+                sb.append(" · ").append(LlmClient.formatTokens(totalTokens)).append(" tokens");
+            }
+            if (contextPercent > 0) {
+                sb.append(" · ctx ").append(contextPercent).append('%');
+            }
+            return sb.toString();
+        }
     }
 
     /**
@@ -339,6 +389,25 @@ class AiPanel {
      * question takes several round trips when the model calls tools), so usage can be grouped per question; it is 0 for
      * route requests, which belong to no question.
      */
+    /**
+     * How many questions the panel's own requests were made for: a question takes one request per model round trip, and
+     * consecutive requests with the same question number belong to one question. Route calls do not count.
+     */
+    static int countQuestions(List<AiUsageEntry> entries) {
+        int questions = 0;
+        int lastQuestion = -1;
+        for (AiUsageEntry e : entries) {
+            if (e.source() == AiUsageSource.ROUTE) {
+                continue;
+            }
+            if (questions == 0 || e.question() != lastQuestion) {
+                questions++;
+                lastQuestion = e.question();
+            }
+        }
+        return questions;
+    }
+
     record AiUsageEntry(String model, String provider, int inputTokens, int outputTokens,
             int totalTokens, long latencyMs, String stopReason, Instant timestamp,
             AiUsageSource source, String routeId, int question) {
@@ -528,6 +597,8 @@ class AiPanel {
                 return;
             }
             initError = null;
+            // know the Ollama window before the first question instead of resolving it in front of the first request
+            client.resolveOllamaContextWindowInBackground();
             messages = new ArrayList<>();
             tools = buildTuiToolDefinitions();
         } catch (Exception e) {
@@ -1173,6 +1244,7 @@ class AiPanel {
                 conversation.add(new ConversationEntry(AiRole.USER, input));
                 questionCounter++;
                 currentQuestion = input;
+                noteQuestionStarted(input);
                 log(LogLevel.QUESTION, "Question about the edit", input);
                 return;
             }
@@ -1358,6 +1430,7 @@ class AiPanel {
         conversation.add(new ConversationEntry(AiRole.USER, question));
         questionCounter++;
         currentQuestion = question;
+        noteQuestionStarted(question);
         log(LogLevel.QUESTION, "Question", question);
         thinkingVerb = THINKING_VERBS.get(ThreadLocalRandom.current().nextInt(THINKING_VERBS.size()));
         thinkingStartTime = System.currentTimeMillis();
@@ -1382,6 +1455,7 @@ class AiPanel {
                 if (agentThread == Thread.currentThread()) {
                     thinking.set(false);
                     agentThread = null;
+                    noteQuestionFinished();
                 }
             }
         }, "tui-ai-agent");
@@ -1389,6 +1463,23 @@ class AiPanel {
         agentThread.start();
     }
 
+    /**
+     * Tells the Ollama tab which question the panel is working on, so it lists it as in progress from the moment it was
+     * asked until the turn ends: answered, failed or cancelled. Only for Ollama; the tab is about that server.
+     */
+    private void noteQuestionStarted(String question) {
+        if (ctx != null && ctx.ollamaMonitor != null && client != null
+                && client.apiType() == LlmClient.ApiType.ollama) {
+            ctx.ollamaMonitor.questionStarted(questionCounter, question);
+        }
+    }
+
+    private void noteQuestionFinished() {
+        if (ctx != null && ctx.ollamaMonitor != null) {
+            ctx.ollamaMonitor.questionFinished();
+        }
+    }
+
     private void runAgentLoop(String systemPrompt, String question) throws InterruptedException {
         if (messages == null) {
             messages = new ArrayList<>();
@@ -1403,6 +1494,7 @@ class AiPanel {
         long turnAiMs = 0;
         long turnToolMs = 0;
         int turnToolCalls = 0;
+        int turnRequests = 0;
         for (int i = 0; i < MAX_ITERATIONS; i++) {
             if (Thread.interrupted()) {
                 throw new InterruptedException();
@@ -1419,8 +1511,9 @@ class AiPanel {
                 log(LogLevel.ERROR, "Error", err);
                 return;
             }
+            turnRequests++;
             totalUsage = totalUsage.add(response.usage());
-            recordUsage(response, callLatency);
+            recordUsage(response, callLatency, null);
 
             // check for error response (null text, no tool calls, error stop reason)
             if ("error".equals(response.stopReason())
@@ -1472,28 +1565,47 @@ class AiPanel {
                 }
                 messages.add(LlmClient.Message.toolResults(results));
             } else {
-                completeTurn(response.text(), false, totalUsage, turnAiMs, turnToolMs, turnToolCalls, messages);
+                completeTurn(response.text(), false, totalUsage, turnAiMs, turnToolMs, turnToolCalls, turnRequests,
+                        messages);
                 return;
             }
         }
 
-        // out of round trips: ask the model once more, without tools, so the user gets an answer rather than an error
+        // out of round trips: ask the model once more to answer with what it has. The tool definitions stay in the
+        // request so the prompt prefix is unchanged and a local server serves it from its cache; dropping them
+        // changed the prefix and cost a full re-prefill (13 s for 8k tokens measured). A tool call in the reply is
+        // ignored.
         messages.add(LlmClient.Message.user(
                 "You have used all " + MAX_ITERATIONS + " tool calls available for this question and cannot call any"
-                                            + " more. Answer now: summarize what you did, what you found, what"
-                                            + " failed, and what the user could try next."));
+                                            + " more; do not call a tool. Answer now: summarize what you did, what"
+                                            + " you found, what failed, and what the user could try next."));
         long wrapUpStart = System.currentTimeMillis();
         drainClientOutput();
-        LlmClient.ChatResponse wrapUp = client.chatWithTools(systemPrompt, messages, List.of());
+        LlmClient.ChatResponse wrapUp = client.chatWithTools(systemPrompt, messages, tools);
         long wrapUpLatency = System.currentTimeMillis() - wrapUpStart;
         turnAiMs += wrapUpLatency;
         if (wrapUp != null) {
+            turnRequests++;
             totalUsage = totalUsage.add(wrapUp.usage());
-            recordUsage(wrapUp, wrapUpLatency);
-            if (wrapUp.text() != null && !wrapUp.text().isBlank()) {
-                completeTurn(wrapUp.text(), true, totalUsage, turnAiMs, turnToolMs, turnToolCalls, messages);
-                return;
-            }
+            recordUsage(wrapUp, wrapUpLatency, "limit");
+        }
+        if (wrapUp == null || wrapUp.text() == null || wrapUp.text().isBlank()) {
+            // the model called a tool regardless: once more without any tool to call, at the price of the prefix
+            wrapUpStart = System.currentTimeMillis();
+            drainClientOutput();
+            wrapUp = client.chatWithTools(systemPrompt, messages, List.of());
+            wrapUpLatency = System.currentTimeMillis() - wrapUpStart;
+            turnAiMs += wrapUpLatency;
+            if (wrapUp != null) {
+                turnRequests++;
+                totalUsage = totalUsage.add(wrapUp.usage());
+                recordUsage(wrapUp, wrapUpLatency, "limit");
+            }
+        }
+        if (wrapUp != null && wrapUp.text() != null && !wrapUp.text().isBlank()) {
+            completeTurn(wrapUp.text(), true, totalUsage, turnAiMs, turnToolMs, turnToolCalls, turnRequests,
+                    messages);
+            return;
         }
 
         StringBuilder sb = new StringBuilder();
@@ -1520,20 +1632,17 @@ class AiPanel {
      */
     private void completeTurn(
             String text, boolean wrapUp, LlmClient.TokenUsage totalUsage, long turnAiMs, long turnToolMs,
-            int turnToolCalls, List<LlmClient.Message> messages) {
+            int turnToolCalls, int turnRequests, List<LlmClient.Message> messages) {
         sessionTotalTokens += totalUsage.totalTokens();
         if (text != null && !text.isBlank()) {
             long elapsed = System.currentTimeMillis() - thinkingStartTime;
             ConversationEntry entry = new ConversationEntry(
                     AiRole.ASSISTANT, text, elapsed, turnAiMs, turnToolMs, turnToolCalls,
-                    totalUsage.totalTokens());
+                    totalUsage.totalTokens(), turnRequests, wrapUp, contextFillPercent());
             conversation.add(entry);
             turnTimings.add(new long[] { turnAiMs, turnToolMs, turnToolCalls });
-            String tokenInfo = totalUsage.totalTokens() > 0
-                    ? ", " + LlmClient.formatTokens(totalUsage.totalTokens()) + " tokens"
-                    : "";
             String label = wrapUp ? "Response after reaching the tool call limit (" : "Response (";
-            log(LogLevel.RESPONSE, label + entry.timing() + tokenInfo + describeCacheSignal(totalUsage) + ")", text);
+            log(LogLevel.RESPONSE, label + entry.byline() + describeCacheSignal(totalUsage) + ")", text);
         } else {
             String err = "Empty response from LLM.";
             conversation.add(new ConversationEntry(AiRole.ERROR, err));
@@ -1545,19 +1654,123 @@ class AiPanel {
     }
 
     /**
-     * Compacts the history after a turn unless the endpoint is local and the history is still within
-     * {@link #LOCAL_HISTORY_BUDGET_TOKENS}; see there for why rewriting history is the slower choice locally.
-     * {@code /compact} bypasses this and always compacts.
+     * Compacts the history after a turn. Hosted endpoints compact a little every turn (tokens cost money, rewriting is
+     * free). A local endpoint waits until the measured prompt passes the budget, then compacts hard once and tells the
+     * user what it cost; see {@link #LOCAL_HISTORY_BUDGET_TOKENS} for why. {@code /compact} bypasses the wait.
      */
     private void compactHistoryAfterTurn() {
         boolean local = client != null && client.isLocalEndpoint();
-        if (shouldCompactAfterTurn(local, historyChars(messages))) {
+        int budget = compactionBudgetTokens(local, knownContextWindow);
+        if (!shouldCompactAfterTurn(local, historyChars(messages), lastMeasuredPromptTokens, budget)) {
+            return;
+        }
+        if (!local) {
             compactHistory(messages, MAX_HISTORY_TURNS, COMPACT_TOOL_RESULT_CHARS);
+            return;
         }
+        String notice = compactLocalHistoryWithNotice(budget, true);
+        conversation.add(new ConversationEntry(AiRole.SYSTEM, notice));
+        log(LogLevel.RESPONSE, "History compacted", notice);
+    }
+
+    /** Compacts the local history hard and returns the notice describing what it cost; resets the measurement. */
+    private String compactLocalHistoryWithNotice(int budget, boolean automatic) {
+        int before = lastMeasuredPromptTokens > 0 ? lastMeasuredPromptTokens : promptTokensEstimate();
+        compactLocalHistory(messages, budget);
+        int after = promptTokensEstimate();
+        lastMeasuredPromptTokens = 0;
+        return describeCompaction(automatic, before, after, true, coldPrefillTokensPerSecond);
     }
 
     static boolean shouldCompactAfterTurn(boolean localEndpoint, long historyChars) {
-        return !localEndpoint || estimateTokens(historyChars) > LOCAL_HISTORY_BUDGET_TOKENS;
+        return shouldCompactAfterTurn(localEndpoint, historyChars, 0, LOCAL_HISTORY_BUDGET_TOKENS);
+    }
+
+    /**
+     * Hosted endpoints always compact. Local ones compact once the prompt Ollama measured for the last request passes
+     * the budget, or, when nothing was measured, once the character estimate of the history does.
+     */
+    static boolean shouldCompactAfterTurn(
+            boolean localEndpoint, long historyChars, int measuredPromptTokens, int budgetTokens) {
+        if (!localEndpoint) {
+            return true;
+        }
+        if (measuredPromptTokens > 0) {
+            return measuredPromptTokens > budgetTokens;
+        }
+        return estimateTokens(historyChars) > budgetTokens;
+    }
+
+    /** Half of the window the local server serves, capped at {@link #LOCAL_HISTORY_MAX_WINDOW_TOKENS}. */
+    static int compactionBudgetTokens(boolean localEndpoint, int windowTokens) {
+        if (!localEndpoint || windowTokens <= 0) {
+            return LOCAL_HISTORY_BUDGET_TOKENS;
+        }
+        return Math.min(windowTokens, LOCAL_HISTORY_MAX_WINDOW_TOKENS) / 2;
+    }
+
+    /**
+     * Compacts as {@code /compact} does (older tool results cut, the previous turn included) and then drops the oldest
+     * turns until the history is estimated at half the budget, so that with the static prefix the next prompt lands
+     * around a quarter to a third of the window. Every compaction costs a full re-prefill locally, so one compaction
+     * has to buy several quiet turns.
+     */
+    static void compactLocalHistory(List<LlmClient.Message> history, int budgetTokens) {
+        compactHistory(history, MAX_HISTORY_TURNS, COMPACT_TOOL_RESULT_CHARS, false);
+        int target = Math.max(1, budgetTokens / 2);
+        while (countTurns(history) > 1 && estimateTokens(historyChars(history)) > target) {
+            dropOldestTurn(history);
+        }
+    }
+
+    /** Removes the first question with everything up to the next one. */
+    static void dropOldestTurn(List<LlmClient.Message> history) {
+        int firstUser = -1;
+        for (int i = 0; i < history.size(); i++) {
+            LlmClient.Message m = history.get(i);
+            boolean question = "user".equals(m.role()) && m.toolCalls() == null && m.toolResults() == null;
+            if (question) {
+                if (firstUser >= 0) {
+                    history.subList(0, i).clear();
+                    return;
+                }
+                firstUser = i;
+            }
+        }
+    }
+
+    /**
+     * The line shown when the history is compacted. Locally the next request prefills the whole prompt again, so the
+     * user is told how long that takes at the speed measured on a cold request (or an assumed speed until one was).
+     */
+    static String describeCompaction(
+            boolean automatic, int beforeTokens, int afterTokens, boolean localEndpoint,
+            double coldPrefillTokensPerSecond) {
+        StringBuilder sb = new StringBuilder();
+        sb.append(automatic ? "History compacted automatically: ~" : "Compacting history: ~")
+                .append(LlmClient.formatTokens(beforeTokens)).append(" -> ~")
+                .append(LlmClient.formatTokens(afterTokens)).append(" tokens");
+        if (!localEndpoint) {
+            sb.append(", saving ~").append(LlmClient.formatTokens(Math.max(0, beforeTokens - afterTokens)))
+                    .append(" tokens per request.");
+            return sb.toString();
+        }
+        boolean assumed = coldPrefillTokensPerSecond <= 0;
+        double rate = assumed ? ASSUMED_COLD_PREFILL_TOKENS_PER_SECOND : coldPrefillTokensPerSecond;
+        double seconds = afterTokens / rate;
+        sb.append(". The next reply prefills the whole prompt again (about ")
+                .append(seconds < 10
+                        ? String.format(Locale.ROOT, "%.0f", Math.max(1, seconds))
+                        : String.format(Locale.ROOT, "%.0f", seconds))
+                .append("s at ").append(String.format(Locale.ROOT, "%.0f", rate)).append(" tok/s")
+                .append(assumed ? ", assumed" : ", measured").append(") because the local server's cache resets.");
+        return sb.toString();
+    }
+
+    /** Estimate of the next prompt: static prefix plus history, in tokens. */
+    private int promptTokensEstimate() {
+        return estimateTokens(buildSystemPrompt().length()) + estimateTokens(toolSchemaChars())
+               + estimateTokens(historyChars(messages));
     }
 
     /**
@@ -1984,7 +2197,8 @@ class AiPanel {
         return null;
     }
 
-    private void recordUsage(LlmClient.ChatResponse response, long latencyMs) {
+    /** {@code reasonOverride} replaces the provider's stop reason on the Ollama tab, e.g. "limit" for the wrap-up. */
+    private void recordUsage(LlmClient.ChatResponse response, long latencyMs, String reasonOverride) {
         if (client == null || response.usage().totalTokens() == 0) {
             return;
         }
@@ -1996,11 +2210,26 @@ class AiPanel {
                 response.usage().totalTokens(), latencyMs,
                 response.stopReason(), Instant.now(),
                 AiUsageSource.TUI, null, questionCounter));
+        noteMeasuredPrompt(response.usage());
         if (ctx != null && ctx.ollamaMonitor != null && client.apiType() == LlmClient.ApiType.ollama) {
             // the Ollama tab shows this request with the timings Ollama returned
             ctx.ollamaMonitor.adoptEndpoint(client.endpointUrl());
-            ctx.ollamaMonitor.recordRequest(model, response.usage(), latencyMs, response.stopReason(),
-                    questionCounter, currentQuestion);
+            ctx.ollamaMonitor.recordRequest(model, response.usage(), latencyMs,
+                    reasonOverride != null ? reasonOverride : response.stopReason(), questionCounter, currentQuestion);
+            ctx.ollamaMonitor.setPanelContext(knownContextWindow, compactionBudgetTokens(true, knownContextWindow));
+        }
+    }
+
+    /** Keeps what the provider measured: the prompt size, the cold prefill speed and, for Ollama, the window. */
+    private void noteMeasuredPrompt(LlmClient.TokenUsage usage) {
+        if (usage.inputTokens() > 0) {
+            lastMeasuredPromptTokens = usage.inputTokens();
+        }
+        if (usage.cachedTokens() == 0 && usage.inputTokens() >= 1000 && usage.prefillMillis() > 0) {
+            coldPrefillTokensPerSecond = usage.inputTokens() * 1000.0 / usage.prefillMillis();
+        }
+        if (client != null && client.apiType() == LlmClient.ApiType.ollama) {
+            knownContextWindow = client.ollamaContextWindow();
         }
     }
 
@@ -2016,7 +2245,8 @@ class AiPanel {
             String tokenSuffix = titleTokens > 0 ? ", " + LlmClient.formatTokens(titleTokens) + " tokens" : "";
             titleLine = Line.from(
                     Span.styled(" AI ", Style.EMPTY.bold()),
-                    Span.styled("(" + formatSeconds(titleElapsed) + tokenSuffix + ") ", Style.EMPTY.dim()));
+                    Span.styled("(" + formatSeconds(titleElapsed) + tokenSuffix + describeContextFillSuffix() + ") ",
+                            Style.EMPTY.dim()));
         } else if (acpPreset != null) {
             titleLine = Line.from(
                     Span.styled(" AI ", Style.EMPTY.bold()),
@@ -2024,7 +2254,9 @@ class AiPanel {
         } else if (sessionTotalTokens > 0) {
             titleLine = Line.from(
                     Span.styled(" AI ", Style.EMPTY.bold()),
-                    Span.styled("(total: " + LlmClient.formatTokens(sessionTotalTokens) + " tokens) ", Style.EMPTY.dim()));
+                    Span.styled("(total: " + LlmClient.formatTokens(sessionTotalTokens) + " tokens"
+                                + describeContextFillSuffix() + ") ",
+                            Style.EMPTY.dim()));
         } else {
             titleLine = Line.from(Span.styled(" AI ", Style.EMPTY.bold()));
         }
@@ -2167,14 +2399,12 @@ 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;
+        String lastByline = "";
         if (!thinking.get() && !conversation.isEmpty()) {
             ConversationEntry last = conversation.get(conversation.size() - 1);
             if (last.role() == AiRole.ASSISTANT && last.elapsedMs() >= 0) {
                 lastElapsed = last.elapsedMs();
-                lastTiming = last.timing();
-                lastTokens = last.totalTokens();
+                lastByline = last.byline();
             }
         }
 
@@ -2237,10 +2467,9 @@ class AiPanel {
         }
 
         if (elapsedArea != null && lastElapsed >= 0) {
-            String tokenSuffix = lastTokens > 0 ? ", " + LlmClient.formatTokens(lastTokens) + " tokens" : "";
             frame.renderWidget(
                     Paragraph.from(
-                            Line.from(Span.styled("(" + lastTiming + tokenSuffix + ")", Style.EMPTY.dim()))),
+                            Line.from(Span.styled("(" + lastByline + ")", Style.EMPTY.dim()))),
                     elapsedArea);
         }
         if (statusArea != null) {
@@ -2501,6 +2730,7 @@ class AiPanel {
         int totalOutput = 0;
         int totalTokens = 0;
         long totalLatency = 0;
+        long tuiLatency = 0;
         int tuiRequests = 0;
         int routeRequests = 0;
         for (AiUsageEntry e : entries) {
@@ -2512,9 +2742,11 @@ class AiPanel {
                 routeRequests++;
             } else {
                 tuiRequests++;
+                tuiLatency += e.latencyMs();
             }
         }
         int requestCount = entries.size();
+        int questionCount = countQuestions(entries);
 
         // Per-model aggregation
         Map<String, long[]> perModel = new LinkedHashMap<>();
@@ -2578,8 +2810,10 @@ class AiPanel {
                 Span.styled(LlmClient.formatTokens(totalOutput), Theme.label()),
                 Span.styled(")", dimStyle)));
         summaryLines.add(Line.from(
-                Span.styled("Avg latency: ", dimStyle),
-                Span.styled(formatSeconds(totalLatency / requestCount), cyanStyle),
+                Span.styled("Avg per question: ", dimStyle),
+                Span.styled(formatSeconds(questionCount > 0 ? tuiLatency / questionCount : totalLatency / requestCount),
+                        cyanStyle),
+                Span.styled(" (" + formatSeconds(totalLatency / requestCount) + " per request)", dimStyle),
                 Span.styled("   AI time: ", dimStyle),
                 Span.styled(formatSeconds(totalLatency), cyanStyle),
                 Span.styled("   Tool time: ", dimStyle),
@@ -2610,14 +2844,14 @@ class AiPanel {
                         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("AVG", Style.EMPTY.bold()))))
+                        Cell.from(Span.styled("AVG/REQ", Style.EMPTY.bold()))))
                 .widths(
                         Constraint.fill(),
                         Constraint.length(6),
                         Constraint.length(8),
                         Constraint.length(8),
                         Constraint.length(8),
-                        Constraint.length(7))
+                        Constraint.length(8))
                 .build();
         frame.renderStatefulWidget(table, tableArea, statsTableState);
 
@@ -3165,9 +3399,36 @@ class AiPanel {
         sb.append("Next request: ~").append(LlmClient.formatTokens(promptTokens + toolTokens + historyTokens))
                 .append(" tokens before your question; session total so far ")
                 .append(LlmClient.formatTokens(sessionTotalTokens)).append(" tokens");
+        int window = knownContextWindow;
+        if (window > 0) {
+            int budget = compactionBudgetTokens(true, window);
+            sb.append("\nContext window: ").append(LlmClient.formatTokens(window))
+                    .append(" tokens (Ollama); the history is compacted once a prompt passes ~")
+                    .append(LlmClient.formatTokens(budget));
+            if (lastMeasuredPromptTokens > 0) {
+                sb.append("; last prompt ").append(LlmClient.formatTokens(lastMeasuredPromptTokens))
+                        .append(" tokens (").append(lastMeasuredPromptTokens * 100L / window).append("%)");
+            }
+        }
         return sb.toString();
     }
 
+    /** {@code , ctx 34%}: the measured prompt against the window, for the title; empty until both are known. */
+    private String describeContextFillSuffix() {
+        int fill = contextFillPercent();
+        return fill > 0 ? ", ctx " + fill + "%" : "";
+    }
+
+    /** The measured prompt against the window in percent, 0 until both are known. */
+    private int contextFillPercent() {
+        int window = knownContextWindow;
+        int measured = lastMeasuredPromptTokens;
+        if (window <= 0 || measured <= 0) {
+            return 0;
+        }
+        return (int) (measured * 100L / window);
+    }
+
     /** The title's context figure, empty until the agent reports one. */
     private String describeAcpContextSuffix() {
         long used = acpContextUsed;
@@ -3236,6 +3497,9 @@ class AiPanel {
         if (messages == null || messages.isEmpty()) {
             return "History is empty, nothing to compact";
         }
+        if (client != null && client.isLocalEndpoint()) {
+            return compactLocalHistoryWithNotice(compactionBudgetTokens(true, knownContextWindow), false);
+        }
         int before = estimateTokens(historyChars(messages));
         int messagesBefore = messages.size();
         compactHistory(messages, MAX_HISTORY_TURNS, COMPACT_TOOL_RESULT_CHARS, false);
@@ -3290,6 +3554,7 @@ class AiPanel {
         int totalOutput = 0;
         int totalTokens = 0;
         long totalLatency = 0;
+        long tuiLatency = 0;
         int tuiRequests = 0;
         int routeRequests = 0;
         Map<String, long[]> perModel = new LinkedHashMap<>();
@@ -3302,6 +3567,7 @@ class AiPanel {
                 routeRequests++;
             } else {
                 tuiRequests++;
+                tuiLatency += e.latencyMs();
             }
             long[] stats = perModel.computeIfAbsent(modelTableKey(e), k -> new long[5]);
             stats[0]++;
@@ -3320,7 +3586,10 @@ class AiPanel {
         sb.append("- **Tokens:** ").append(LlmClient.formatTokens(totalTokens))
                 .append(" (in ").append(LlmClient.formatTokens(totalInput))
                 .append(", out ").append(LlmClient.formatTokens(totalOutput)).append(")\n");
-        sb.append("- **Avg latency:** ").append(formatSeconds(totalLatency / entries.size())).append("\n");
+        int questionCount = countQuestions(entries);
+        sb.append("- **Avg per question:** ")
+                .append(formatSeconds(questionCount > 0 ? tuiLatency / questionCount : totalLatency / entries.size()))
+                .append(" (").append(formatSeconds(totalLatency / entries.size())).append(" per request)\n");
         if (sessionToolCalls > 0) {
             sb.append("- **AI time:** ").append(formatSeconds(totalLatency))
                     .append(", **Tool time:** ").append(formatSeconds(sessionToolTimeMs))
@@ -3331,7 +3600,7 @@ class AiPanel {
             sb.append("- **Last request:** ").append(LlmClient.formatTokens(last.totalTokens()))
                     .append(" tokens in ").append(formatSeconds(last.latencyMs())).append("\n");
         }
-        sb.append("\n| Model | Reqs | In | Out | Total | Avg |\n|---|---|---|---|---|---|\n");
+        sb.append("\n| Model | Reqs | In | Out | Total | Avg/req |\n|---|---|---|---|---|---|\n");
         for (Map.Entry<String, long[]> entry : perModel.entrySet()) {
             long[] stats = entry.getValue();
             sb.append("| ").append(entry.getKey())
@@ -3635,6 +3904,7 @@ class AiPanel {
                 return false;
             }
             client.withModel(model);
+            client.resolveOllamaContextWindowInBackground();
             persistModelSelection(model);
             return true;
         }
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaMonitor.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaMonitor.java
index 58235373c589..4c42db936cca 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaMonitor.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaMonitor.java
@@ -76,6 +76,9 @@ final class OllamaMonitor {
     private static final long TAGS_INTERVAL_MS = 15_000;
     private static final long RUNNER_SCAN_INTERVAL_MS = 5_000;
     private static final long HOST_INTERVAL_MS = 1_000;
+    /** The runner's slot is read twice a second while it generates, and every two seconds while it sits idle. */
+    private static final long SLOT_BUSY_INTERVAL_MS = 500;
+    private static final long SLOT_IDLE_INTERVAL_MS = 2_000;
     private static final long RATE_WINDOW_MS = 1_500;
     private static final int MAX_SEEN_SPANS = 4_000;
     private static final long SPAN_INTERVAL_MS = 5_000;
@@ -304,10 +307,13 @@ final class OllamaMonitor {
             return false;
         }
 
-        /** From the first request starting to the last one finishing. */
+        /**
+         * From the first request starting to the last one finishing. A request is stamped when its reply arrives, so
+         * its start is that stamp less its own total.
+         */
         long wallMs() {
-            long start = first().timestamp().toEpochMilli();
-            long end = last().timestamp().toEpochMilli() + last().totalMs();
+            long start = first().timestamp().toEpochMilli() - first().totalMs();
+            long end = last().timestamp().toEpochMilli();
             return Math.max(end - start, last().totalMs());
         }
 
@@ -364,11 +370,90 @@ final class OllamaMonitor {
         }
     }
 
+    /**
+     * The AI panel question being answered right now, so the tab can list it from the moment it was asked: before the
+     * first request returns there is no {@link RequestEntry} for it, and while tools run its last step says
+     * {@code tool_calls} like a finished question's would.
+     */
+    record ActiveQuestion(int question, String text, Instant startedAt) {
+
+        long elapsedMs() {
+            return Math.max(0, System.currentTimeMillis() - startedAt.toEpochMilli());
+        }
+
+        boolean matches(QuestionGroup g) {
+            return g.source() == RequestSource.TUI && g.question() == question;
+        }
+    }
+
+    /**
+     * The AI panel's questions of the session in one line, the footer of the requests table: averages per question
+     * where a question row shows a figure per question, pooled rates and cache hit, the peak context fill and how many
+     * questions ended at the tool-call limit. Route calls are not questions and are left out.
+     */
+    record QuestionSummary(int questions, int requests, long totalWallMs, long avgPromptTokens,
+            long avgOutputTokens, int cacheHitPercent, int peakContextPercent, double prefillTokensPerSecond,
+            double decodeTokensPerSecond, long avgTtftMs, long avgWallMs, int limitHits) {
+
+        static final QuestionSummary EMPTY = new QuestionSummary(0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0);
+
+        static QuestionSummary of(List<QuestionGroup> groups) {
+            int questions = 0;
+            int requests = 0;
+            long wall = 0;
+            long prompt = 0;
+            long output = 0;
+            long promptAll = 0;
+            long cachedAll = 0;
+            long evaluated = 0;
+            long prefillMs = 0;
+            long decodeMs = 0;
+            int peak = -1;
+            long ttft = 0;
+            int timed = 0;
+            int limits = 0;
+            for (QuestionGroup g : groups) {
+                if (g.source() != RequestSource.TUI) {
+                    continue;
+                }
+                questions++;
+                requests += g.steps().size();
+                wall += g.wallMs();
+                prompt += g.promptTokens();
+                output += g.outputTokens();
+                peak = Math.max(peak, g.contextPercent());
+                if (g.hasTimings()) {
+                    ttft += g.ttftMs();
+                    timed++;
+                }
+                if ("limit".equals(g.doneReason())) {
+                    limits++;
+                }
+                for (RequestEntry e : g.steps()) {
+                    promptAll += e.inputTokens();
+                    cachedAll += e.cachedTokens();
+                    evaluated += e.evaluatedTokens();
+                    prefillMs += e.prefillMs();
+                    decodeMs += e.decodeMs();
+                }
+            }
+            if (questions == 0) {
+                return EMPTY;
+            }
+            return new QuestionSummary(
+                    questions, requests, wall, prompt / questions, output / questions,
+                    promptAll > 0 ? (int) Math.min(100, cachedAll * 100 / promptAll) : 0, peak,
+                    prefillMs > 0 && evaluated > 0 ? evaluated * 1000.0 / prefillMs : 0,
+                    decodeMs > 0 && output > 0 ? output * 1000.0 / decodeMs : 0,
+                    timed > 0 ? ttft / timed : 0, wall / questions, limits);
+        }
+    }
+
     /** Immutable view for rendering and for the MCP tool. */
     record Snapshot(ServerInfo server, List<LoadedModel> models, List<String> installed, SlotState slot,
             RunnerInfo runner, HostStats host, List<RequestEntry> requests, double liveDecodeRate,
             double livePrefillRate, long[] decodeHistory, SessionTotals totals, String lastError, Instant lastPoll,
-            String probedUrl) {
+            String probedUrl, int panelWindow, int panelBudget, ActiveQuestion activeQuestion) {
 
         boolean connected() {
             return server != null;
@@ -403,11 +488,15 @@ final class OllamaMonitor {
     private final LinkedHashSet<String> seenSpanIds = new LinkedHashSet<>();
     private SessionTotals totals = SessionTotals.EMPTY;
     private long lastTuiPromptTokens;
+    private int lastTuiQuestion;
     private final TokenRateWindow decodeWindow = new TokenRateWindow(RATE_WINDOW_MS);
     private final TokenRateWindow prefillWindow = new TokenRateWindow(RATE_WINDOW_MS);
     private final long[] decodeHistory = new long[HISTORY_POINTS];
     private String lastError;
     private Instant lastPoll;
+    private int panelWindow;
+    private int panelBudget;
+    private ActiveQuestion activeQuestion;
 
     private long lastProbe;
     private long lastVersion;
@@ -415,6 +504,7 @@ final class OllamaMonitor {
     private long lastTags;
     private long lastRunnerScan;
     private long lastHost;
+    private long lastSlotPoll;
     private int psFailures;
     private long lastSpanIngest;
     private Boolean nvidiaSmiAvailable;
@@ -595,12 +685,35 @@ final class OllamaMonitor {
         return false;
     }
 
+    /** What the AI panel asks Ollama for and where it compacts, shown in the header next to what Ollama allocated. */
+    void setPanelContext(int window, int budget) {
+        synchronized (lock) {
+            panelWindow = window;
+            panelBudget = budget;
+        }
+    }
+
+    /** The AI panel started working on a question; it is listed as in progress until {@link #questionFinished()}. */
+    void questionStarted(int question, String text) {
+        synchronized (lock) {
+            activeQuestion = new ActiveQuestion(question, text, Instant.now());
+        }
+    }
+
+    /** The AI panel's turn ended: answered, failed or cancelled. */
+    void questionFinished() {
+        synchronized (lock) {
+            activeQuestion = null;
+        }
+    }
+
     /** Clears the request log, the session totals and the rate history. */
     void reset() {
         synchronized (lock) {
             requests.clear();
             totals = SessionTotals.EMPTY;
             lastTuiPromptTokens = 0;
+            lastTuiQuestion = 0;
             Arrays.fill(decodeHistory, 0);
             decodeWindow.clear();
             prefillWindow.clear();
@@ -616,13 +729,17 @@ final class OllamaMonitor {
     }
 
     private void addRequest(RequestEntry entry) {
-        // an AI panel prompt that shrinks by a fifth or more against the previous turn means the history was
-        // compacted (or a new conversation started); either way the context was freed
+        // the first prompt of a question that is a fifth or more smaller than the last prompt of the previous
+        // question means the history was compacted between the two (or a new conversation started); either way the
+        // context was freed. Within a question prompts only grow, so a smaller step (the wrap-up after the tool call
+        // limit) is not a compaction.
         boolean compaction = false;
         if (entry.source() == RequestSource.TUI) {
-            if (lastTuiPromptTokens > 0 && entry.promptTokens() < lastTuiPromptTokens * 0.8) {
+            boolean newQuestion = entry.question() == 0 || entry.question() != lastTuiQuestion;
+            if (newQuestion && lastTuiPromptTokens > 0 && entry.promptTokens() < lastTuiPromptTokens * 0.8) {
                 compaction = true;
             }
+            lastTuiQuestion = entry.question();
             lastTuiPromptTokens = entry.promptTokens();
         }
         requests.addFirst(entry);
@@ -699,7 +816,8 @@ final class OllamaMonitor {
             return new Snapshot(
                     server, models, installed, slot, runner, host, List.copyOf(requests),
                     decodeWindow.ratePerSecond(now), prefillWindow.ratePerSecond(now),
-                    decodeHistory.clone(), totals, lastError, lastPoll, baseUrl);
+                    decodeHistory.clone(), totals, lastError, lastPoll, baseUrl, panelWindow, panelBudget,
+                    activeQuestion);
         }
     }
 
@@ -816,12 +934,22 @@ final class OllamaMonitor {
             }
         }
         if (current != null) {
-            JsonArray slots = getJsonArray("http://127.0.0.1:" + current.port() + "/slots");
-            if (slots != null) {
-                updateSlot(OllamaParsers.parseSlots(slots, Instant.ofEpochMilli(now)));
-            } else {
-                updateRunner(null);
-                current = null;
+            // llama-server logs every request at the verbosity Ollama starts it with, so the slot is read only as
+            // often as the live view needs: fast while it generates, slowly while idle
+            boolean busy;
+            synchronized (lock) {
+                busy = slot != null && slot.processing();
+            }
+            long slotInterval = busy ? SLOT_BUSY_INTERVAL_MS : SLOT_IDLE_INTERVAL_MS;
+            if (now - lastSlotPoll >= slotInterval) {
+                lastSlotPoll = now;
+                JsonArray slots = getJsonArray("http://127.0.0.1:" + current.port() + "/slots");
+                if (slots != null) {
+                    updateSlot(OllamaParsers.parseSlots(slots, Instant.ofEpochMilli(now)));
+                } else {
+                    updateRunner(null);
+                    current = null;
+                }
             }
         }
         if (now - lastHost >= HOST_INTERVAL_MS) {
@@ -1164,6 +1292,12 @@ final class OllamaMonitor {
         session.put("peakContextPercent", s.totals().peakContextPercent());
         session.put("compactions", s.totals().compactions());
         root.put("session", session);
+        if (s.panelWindow() > 0) {
+            JsonObject panel = new JsonObject();
+            panel.put("contextWindow", s.panelWindow());
+            panel.put("compactsAbove", s.panelBudget());
+            root.put("aiPanel", panel);
+        }
 
         JsonArray reqs = new JsonArray();
         int n = 0;
@@ -1175,12 +1309,37 @@ final class OllamaMonitor {
         }
         root.put("requests", reqs);
         JsonArray questions = new JsonArray();
+        ActiveQuestion active = s.activeQuestion();
+        boolean activeListed = false;
         int q = 0;
-        for (QuestionGroup g : groupByQuestion(s.requests())) {
+        List<QuestionGroup> groups = groupByQuestion(s.requests());
+        QuestionSummary summary = QuestionSummary.of(groups);
+        if (summary.questions() > 0) {
+            JsonObject js = new JsonObject();
+            js.put("questions", summary.questions());
+            js.put("requests", summary.requests());
+            js.put("totalWallMs", summary.totalWallMs());
+            js.put("avgWallMs", summary.avgWallMs());
+            js.put("avgTtftMs", summary.avgTtftMs());
+            js.put("avgPromptTokens", summary.avgPromptTokens());
+            js.put("avgOutputTokens", summary.avgOutputTokens());
+            js.put("cacheHitPercent", summary.cacheHitPercent());
+            js.put("peakContextPercent", summary.peakContextPercent());
+            js.put("prefillTokensPerSecond", round1(summary.prefillTokensPerSecond()));
+            js.put("decodeTokensPerSecond", round1(summary.decodeTokensPerSecond()));
+            js.put("limitHits", summary.limitHits());
+            root.put("questionSummary", js);
+        }
+        for (QuestionGroup g : groups) {
             if (q++ >= requestLimit) {
                 break;
             }
             JsonObject jg = new JsonObject();
+            if (active != null && active.matches(g)) {
+                activeListed = true;
+                jg.put("inProgress", true);
+                jg.put("elapsedMs", active.elapsedMs());
+            }
             jg.put("time", g.first().timestamp().toString());
             jg.put("source", g.source().name().toLowerCase(Locale.ROOT));
             if (g.routeId() != null) {
@@ -1208,6 +1367,20 @@ final class OllamaMonitor {
             }
             questions.add(jg);
         }
+        if (active != null && !activeListed) {
+            // asked, but no request has returned yet
+            JsonObject jq = new JsonObject();
+            jq.put("time", active.startedAt().toString());
+            jq.put("source", "tui");
+            jq.put("question", active.question());
+            if (active.text() != null) {
+                jq.put("questionText", active.text());
+            }
+            jq.put("steps", 0);
+            jq.put("inProgress", true);
+            jq.put("elapsedMs", active.elapsedMs());
+            questions.add(0, jq);
+        }
         root.put("questions", questions);
         if (s.lastPoll() != null) {
             root.put("lastPoll", s.lastPoll().toString());
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaTab.java
index c7d9320d87f2..5301c2420ef1 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaTab.java
@@ -46,10 +46,12 @@ 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.dsl.jbang.core.commands.tui.OllamaMonitor.ActiveQuestion;
 import org.apache.camel.dsl.jbang.core.commands.tui.OllamaMonitor.HostStats;
 import org.apache.camel.dsl.jbang.core.commands.tui.OllamaMonitor.LoadedModel;
 import org.apache.camel.dsl.jbang.core.commands.tui.OllamaMonitor.ModelShape;
 import org.apache.camel.dsl.jbang.core.commands.tui.OllamaMonitor.QuestionGroup;
+import org.apache.camel.dsl.jbang.core.commands.tui.OllamaMonitor.QuestionSummary;
 import org.apache.camel.dsl.jbang.core.commands.tui.OllamaMonitor.RequestEntry;
 import org.apache.camel.dsl.jbang.core.commands.tui.OllamaMonitor.RequestSource;
 import org.apache.camel.dsl.jbang.core.commands.tui.OllamaMonitor.SessionTotals;
@@ -264,7 +266,15 @@ class OllamaTab extends AbstractTab {
                 LoadedModel m = s.models().get(i);
                 lines.add(Line.from(Span.styled("  " + m.name(), Style.EMPTY.fg(Theme.accent()).bold()),
                         Span.styled("   " + describeShape(m), Theme.muted())));
-                lines.add(Line.from(Span.styled("  " + describeResidency(m, Instant.now()), Theme.label())));
+                String residency = describeResidency(m, Instant.now());
+                if (i == 0 && s.panelWindow() > 0) {
+                    // the panel adopts the loaded window, so it only needs naming when the two differ
+                    if (s.panelWindow() != m.contextLength()) {
+                        residency += " · AI panel asks " + formatTokens(s.panelWindow());
+                    }
+                    residency += " · AI panel compacts above " + formatTokens(s.panelBudget());
+                }
+                lines.add(Line.from(Span.styled("  " + residency, Theme.label())));
             }
         }
         frame.renderWidget(Paragraph.builder()
@@ -455,7 +465,10 @@ class OllamaTab extends AbstractTab {
         for (int i = 0; i < n; i++) {
             data[n - 1 - i] = turns.get(i).contextPercent();
         }
-        Style level = last >= 80 ? Theme.error() : last >= 50 ? Theme.warning() : Theme.info();
+        // colour against the panel's compaction budget when known, else against the window
+        long lastPrompt = turns.get(0).promptTokens();
+        int pressure = s.panelBudget() > 0 ? (int) Math.min(100, lastPrompt * 100 / s.panelBudget()) : last;
+        Style level = pressure >= 100 ? Theme.error() : pressure >= 75 ? Theme.warning() : Theme.info();
         // bars start right after the label and grow to the right as turns are added
         return Line.from(
                 Span.styled(" turns ", Theme.muted()),
@@ -510,7 +523,8 @@ class OllamaTab extends AbstractTab {
 
     private void renderRequests(Frame frame, Rect area, Snapshot s) {
         List<RequestEntry> requests = s.requests();
-        if (requests.isEmpty()) {
+        ActiveQuestion active = s.activeQuestion();
+        if (requests.isEmpty() && active == null) {
             rowRefs = List.of();
             lastTableArea = area;
             frame.renderWidget(Paragraph.builder()
@@ -530,10 +544,16 @@ class OllamaTab extends AbstractTab {
         int questionWidth = Math.max(12, area.width() - FIXED_COLUMNS_WIDTH);
         List<Row> rows = new ArrayList<>();
         List<Object> refs = new ArrayList<>();
+        if (active != null && groups.stream().noneMatch(active::matches)) {
+            // asked, but the first request has not returned yet
+            rows.add(activeRow(active, questionWidth));
+            refs.add(active);
+        }
         for (QuestionGroup g : groups) {
             boolean multi = g.steps().size() > 1;
             boolean expanded = multi && expandedGroups.contains(g.key());
-            rows.add(questionRow(g, multi, expanded, questionWidth));
+            rows.add(questionRow(g, multi, expanded, questionWidth,
+                    active != null && active.matches(g) ? active : null));
             refs.add(g);
             if (expanded) {
                 int n = 1;
@@ -546,10 +566,16 @@ class OllamaTab extends AbstractTab {
         rowRefs = refs;
 
         String title = " Requests (" + groups.size() + (groups.size() == 1 ? " question, " : " questions, ")
-                       + requests.size() + (requests.size() == 1 ? " request)" : " requests)")
+                       + requests.size() + (requests.size() == 1 ? " request" : " requests")
+                       + (active != null ? ", 1 in progress" : "") + ")"
                        + "  tok/s for prefill and decode · CTX = prompt share of the context window ";
-        Table table = Table.builder()
-                .rows(rows)
+        QuestionSummary summary = QuestionSummary.of(groups);
+        Table.Builder builder = Table.builder()
+                .rows(rows);
+        if (summary.questions() >= 2) {
+            builder.footer(summaryRow(summary, questionWidth));
+        }
+        Table table = builder
                 .header(Row.from(
                         Cell.from(Span.styled(" TIME", Style.EMPTY.bold())),
                         Cell.from(Span.styled("SOURCE", Style.EMPTY.bold())),
@@ -587,8 +613,61 @@ class OllamaTab extends AbstractTab {
 
     private static final int FIXED_COLUMNS_WIDTH = 10 + 18 + 6 + 6 + 6 + 5 + 8 + 8 + 7 + 7 + 12 + 6;
 
-    /** One question (or route call) on one line: the question text cut to fit, then the whole-question figures. */
-    private static Row questionRow(QuestionGroup g, boolean multi, boolean expanded, int questionWidth) {
+    /**
+     * The footer under the questions, spreadsheet style: the session's average per question in every column that is per
+     * question above, pooled rates and cache hit, the peak context fill, and the tool-call limit count.
+     */
+    private static Row summaryRow(QuestionSummary s, int questionWidth) {
+        Style dim = Theme.muted();
+        String text = s.questions() + " questions · " + s.requests() + " requests · " + formatSeconds(s.totalWallMs());
+        return Row.from(
+                Cell.from(Span.styled("", dim)),
+                Cell.from(Span.styled("avg/question", dim)),
+                Cell.from(Span.styled(TuiHelper.truncate(text, questionWidth), dim)),
+                rightCell(formatTokens(s.avgPromptTokens()), 6, dim),
+                rightCell(formatTokens(s.avgOutputTokens()), 6, dim),
+                rightCell(s.cacheHitPercent() + "%", 6, dim),
+                rightCell(s.peakContextPercent() >= 0 ? s.peakContextPercent() + "%" : "-", 5, dim),
+                rightCell(s.prefillTokensPerSecond() > 0 ? formatRate(s.prefillTokensPerSecond()) : "-", 8, dim),
+                rightCell(s.decodeTokensPerSecond() > 0 ? formatRate(s.decodeTokensPerSecond()) : "-", 8, dim),
+                rightCell(s.avgTtftMs() > 0 ? formatSeconds(s.avgTtftMs()) : "-", 7, dim),
+                rightCell(formatSeconds(s.avgWallMs()), 7, Style.EMPTY.fg(Theme.accent()).bold()),
+                Cell.from(Span.styled(s.limitHits() > 0 ? " " + s.limitHits() + " limit" : "",
+                        s.limitHits() > 0 ? Theme.error() : dim)));
+    }
+
+    private static final String[] SPINNER = { "⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏" };
+
+    private static Span workingSpan() {
+        String frame = SPINNER[(int) ((System.currentTimeMillis() / 100) % SPINNER.length)];
+        return Span.styled(" " + frame + " working", Theme.info());
+    }
+
+    /** The question the AI panel is working on before its first request has returned: text and a clock, no figures. */
+    private static Row activeRow(ActiveQuestion a, int questionWidth) {
+        String text = a.text() != null ? firstLine(a.text()) : "";
+        return Row.from(
+                Cell.from(Span.styled(" " + TIME.format(a.startedAt()), Theme.muted())),
+                Cell.from(Span.styled("#" + a.question(), Theme.info())),
+                Cell.from(Span.styled(TuiHelper.truncate(text, questionWidth), Theme.label())),
+                rightCell("-", 6),
+                rightCell("-", 6),
+                rightCell("-", 6, Theme.muted()),
+                rightCell("-", 5),
+                rightCell("-", 8, Theme.info()),
+                rightCell("-", 8, Theme.success()),
+                rightCell("-", 7),
+                rightCell(formatSeconds(a.elapsedMs()), 7, Theme.info()),
+                Cell.from(workingSpan()));
+    }
+
+    /**
+     * One question (or route call) on one line: the question text cut to fit, then the whole-question figures.
+     * {@code active} is set while the AI panel is still working on it: the clock keeps running and the reason reads
+     * {@code working} instead of the last step's {@code tool_calls}.
+     */
+    private static Row questionRow(
+            QuestionGroup g, boolean multi, boolean expanded, int questionWidth, ActiveQuestion active) {
         String marker = multi ? (expanded ? TuiIcons.MORE_CHEVRON : TuiIcons.ARROW_RIGHT) : " ";
         String source;
         Style sourceStyle;
@@ -597,7 +676,7 @@ class OllamaTab extends AbstractTab {
             sourceStyle = Theme.notice();
         } else {
             source = (g.question() > 0 ? "#" + g.question() : "tui") + (multi ? " ×" + g.steps().size() : "");
-            sourceStyle = Theme.info();
+            sourceStyle = requestCountStyle(g.steps().size(), g.doneReason());
         }
         String text = g.questionText() != null && !g.questionText().isBlank()
                 ? firstLine(g.questionText())
@@ -618,8 +697,40 @@ class OllamaTab extends AbstractTab {
                         Theme.success()),
                 rightCell(g.hasTimings() ? formatSeconds(g.ttftMs()) : "-", 7,
                         g.coldStart() ? Theme.warning() : Style.EMPTY),
-                rightCell(g.wallMs() > 0 ? formatSeconds(g.wallMs()) : "-", 7),
-                Cell.from(Span.styled(" " + (g.doneReason() != null ? g.doneReason() : ""), Theme.muted())));
+                active != null
+                        ? rightCell(formatSeconds(Math.max(g.wallMs(), active.elapsedMs())), 7, Theme.info())
+                        : rightCell(g.wallMs() > 0 ? formatSeconds(g.wallMs()) : "-", 7, totalTimeStyle(g.wallMs())),
+                Cell.from(active != null
+                        ? workingSpan()
+                        : Span.styled(" " + (g.doneReason() != null ? g.doneReason() : ""),
+                                reasonStyle(g.doneReason()))));
+    }
+
+    /**
+     * A question's request count is the number of times the whole prompt was sent: yellow from {@value #MANY_REQUESTS}
+     * requests, red when it ended at the AI panel's tool-call limit.
+     */
+    static final int MANY_REQUESTS = 10;
+
+    /**
+     * A question that made you wait: yellow from {@value #SLOW_QUESTION_MS} ms, orange from
+     * {@value #VERY_SLOW_QUESTION_MS} ms.
+     */
+    static final long SLOW_QUESTION_MS = 30_000;
+    static final long VERY_SLOW_QUESTION_MS = 60_000;
+
+    static Style requestCountStyle(int requests, String doneReason) {
+        if ("limit".equals(doneReason)) {
+            return Theme.error().bold();
+        }
+        return requests >= MANY_REQUESTS ? Theme.warning() : Theme.info();
+    }
+
+    static Style totalTimeStyle(long wallMs) {
+        if (wallMs >= VERY_SLOW_QUESTION_MS) {
+            return Style.EMPTY.fg(Theme.accent()).bold();
+        }
+        return wallMs >= SLOW_QUESTION_MS ? Theme.warning() : Style.EMPTY;
     }
 
     /** One request of an unfolded question: step number, the model, and that request's own figures. */
@@ -638,7 +749,13 @@ class OllamaTab extends AbstractTab {
                 rightCell(e.hasTimings() ? formatSeconds(e.ttftMs()) : "-", 7,
                         e.coldStart() ? Theme.warning() : Theme.muted()),
                 rightCell(e.totalMs() > 0 ? formatSeconds(e.totalMs()) : "-", 7, Theme.muted()),
-                Cell.from(Span.styled(" " + (e.doneReason() != null ? e.doneReason() : ""), Theme.muted().dim())));
+                Cell.from(Span.styled(" " + (e.doneReason() != null ? e.doneReason() : ""),
+                        "limit".equals(e.doneReason()) ? Theme.warning() : Theme.muted().dim())));
+    }
+
+    /** "limit" (the AI panel's tool-call limit ended the question) and "length" (the token limit) stand out. */
+    private static Style reasonStyle(String reason) {
+        return "limit".equals(reason) || "length".equals(reason) ? Theme.warning() : Theme.muted();
     }
 
     static String firstLine(String text) {
@@ -704,6 +821,9 @@ class OllamaTab extends AbstractTab {
                 parts.add(shape.experts() + " experts"
                           + (shape.expertsUsed() > 0 ? " (" + shape.expertsUsed() + " active)" : ""));
             }
+            if (shape.maxContext() > 0) {
+                parts.add("max ctx " + formatTokens(shape.maxContext()));
+            }
             if (shape.capabilities() != null && !shape.capabilities().isEmpty()) {
                 List<String> caps = new ArrayList<>();
                 for (String c : shape.capabilities()) {
@@ -727,10 +847,7 @@ class OllamaTab extends AbstractTab {
             sb.append(", ").append(gpu >= 100 ? "100% GPU" : gpu > 0 ? gpu + "% GPU" : "CPU only");
         }
         if (m.contextLength() > 0) {
-            sb.append(" · ctx ").append(String.format(Locale.ROOT, "%,d", m.contextLength()));
-            if (m.shape() != null && m.shape().maxContext() > m.contextLength()) {
-                sb.append(" of ").append(String.format(Locale.ROOT, "%,d", m.shape().maxContext()));
-            }
+            sb.append(" · ctx ").append(formatTokens(m.contextLength()));
         }
         if (m.expiresAt() != null) {
             sb.append(" · ").append(formatCountdown(m.expiresAt(), now));
@@ -777,6 +894,10 @@ class OllamaTab extends AbstractTab {
         if (tokens < 1000) {
             return Long.toString(tokens);
         }
+        // context windows are powers of two and are known by their binary names: 32k, 64k, 256k
+        if (tokens % 1024 == 0 && tokens < 1_048_576) {
+            return (tokens / 1024) + "k";
+        }
         if (tokens < 10_000) {
             return String.format(Locale.ROOT, "%.1fk", tokens / 1000.0);
         }
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/resources/tui/help/ollama.md b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/resources/tui/help/ollama.md
index bc3bc9ae11f0..20ae86aba47a 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/resources/tui/help/ollama.md
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/resources/tui/help/ollama.md
@@ -48,10 +48,16 @@ The loaded model and its shape:
 - Size in memory and the share held by the GPU (`100% GPU` means fully
   offloaded; a lower figure means part of the model runs on the CPU
   and decode will be slow)
-- `ctx 32,768 of 262,144` — the context window Ollama allocated for
-  this load, and the maximum the model supports. The AI panel asks for
-  `32768` unless `OLLAMA_CONTEXT_LENGTH` is set. A request with a
-  different size makes Ollama reload the model.
+- `max ctx 256k` on the model line — the largest context the model was
+  trained for. `ctx 64k` on the loaded line — the window Ollama
+  allocated for this load; it is fixed for the life of the runner, and a
+  request for a different size makes Ollama reload the model.
+- `AI panel compacts above 32k` — the prompt size above which the TUI's
+  AI panel compacts its history, shown once the panel has made a
+  request. The panel asks for `OLLAMA_CONTEXT_LENGTH` when set, else the
+  window already loaded, else 64k when the model's cache fits the
+  machine's memory, else 32k; `AI panel asks ...` appears only when that
+  differs from the loaded window.
 - When the model unloads (its keep-alive)
 
 With no model loaded the installed models are listed instead; a model
@@ -89,8 +95,10 @@ loads on the first request.
   filled (system prompt, tool definitions, history, question). The
   bars grow as a conversation continues and drop when the history is
   compacted; the line ends with the latest fill, the session peak and
-  the number of compactions seen. Yellow from 50%, red from 80%: that is
-  when `/compact` in the AI panel, or a smaller toolset, pays off.
+  the number of compactions seen. The colour follows the AI panel's
+  compaction point once known (yellow from three quarters of it, red at
+  it), else the window (yellow from 50%, red from 80%): that is when
+  `/compact` in the AI panel, or a smaller toolset, pays off.
 
 Without the local runner the panel falls back to the last request's
 tokens against the model's context length.
@@ -116,6 +124,12 @@ whole. Press **Enter** (or **→**) on a question with `×N` in the SOURCE
 column to unfold its steps, **←** to fold them again. A call made by a
 Camel route is one line of its own.
 
+The question the AI panel is working on is listed from the moment it is
+asked, with `working` and a spinner as its reason and TOTAL counting up;
+the figures fill in as its requests return, and the reason becomes
+`stop` or `limit` when the answer lands (or the row goes when you cancel
+with Esc).
+
 | Column | Question line | Step line |
 |--------|---------------|-----------|
 | TIME | When the first request started | When the request started |
@@ -129,11 +143,23 @@ Camel route is one line of its own.
 | DECODE | Generated tokens per second across the steps | Same for this request |
 | TTFT | Time to the first token of the first step (load plus prefill), yellow after a cold start | Time to first token of this request |
 | TOTAL | From the first request starting to the last finishing: what you waited | This request as Ollama measured it |
-| REASON | Why the last step stopped: `stop`, `length` (hit the token limit) | `tool_calls` for every step but the last |
+| REASON | Why the last step stopped: `stop`, `length` (hit the token limit), `limit` (the AI panel's tool-call limit ended the question; the answer summarises what was found) | `tool_calls` for every step but the last |
 
 Route requests show `-` for prefill, decode and TTFT because the GenAI
 span carries tokens and duration only.
 
+With two or more questions a footer row, `avg/question`, gives the
+session's average per question for IN, OUT, TTFT and TOTAL, the pooled
+cache hit and rates, the peak CTX, and how many questions ended at the
+tool-call limit. Its TOTAL is the average time you waited per question,
+the figure the AI panel's usage view (Ctrl+U) reports as well. Route calls
+are not questions and are left out.
+
+Two figures are coloured so a costly question stands out without reading
+the row: the `×N` request count is yellow from 10 requests and red when
+the question ended at the AI panel's tool-call limit (REASON `limit`);
+TOTAL is yellow from 30 seconds and orange from a minute.
+
 ## Remote and Containerised Ollama
 
 The Ollama API and the per-request data work against any host. The
@@ -141,6 +167,15 @@ live figures, the context panel's live state and the host panel need
 the runner on this machine; against a remote host or a container the
 tab says so and keeps the rest.
 
+## How often the tab reads
+
+While the tab is showing, the runner's slot state is read twice a
+second during generation and every two seconds when idle, the Ollama
+API once a second and the host probes once a second. With the tab
+closed only a version probe every ten seconds keeps the More menu
+entry current. Each read shows up in Ollama's own log at the verbosity
+it starts the runner with.
+
 ## Keyboard Shortcuts
 
 | Key | Action |
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelHistoryCompactionTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelHistoryCompactionTest.java
index c9738a1f185a..32d3bdce519c 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelHistoryCompactionTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelHistoryCompactionTest.java
@@ -63,6 +63,77 @@ class AiPanelHistoryCompactionTest {
         assertTrue(AiPanel.shouldCompactAfterTurn(true, budgetChars + 4_000));
     }
 
+    @Test
+    void measuredPromptDecidesForLocalEndpointsWhenAvailable() {
+        int budget = AiPanel.compactionBudgetTokens(true, 32_768);
+        assertEquals(16_384, budget);
+        // the estimate says the history is small, Ollama measured a prompt over the budget: compact
+        assertTrue(AiPanel.shouldCompactAfterTurn(true, 1_000, 24_800, budget));
+        // the estimate says big, the measurement says fine: the measurement wins
+        assertFalse(AiPanel.shouldCompactAfterTurn(true, 100_000, 12_000, budget));
+        // nothing measured yet: the estimate decides
+        assertTrue(AiPanel.shouldCompactAfterTurn(true, 100_000, 0, budget));
+        assertFalse(AiPanel.shouldCompactAfterTurn(true, 1_000, 0, budget));
+        // hosted endpoints compact regardless
+        assertTrue(AiPanel.shouldCompactAfterTurn(false, 0, 0, budget));
+    }
+
+    @Test
+    void budgetIsHalfTheWindowCappedAtTheMaximum() {
+        assertEquals(AiPanel.LOCAL_HISTORY_BUDGET_TOKENS, AiPanel.compactionBudgetTokens(true, 0));
+        assertEquals(AiPanel.LOCAL_HISTORY_BUDGET_TOKENS, AiPanel.compactionBudgetTokens(false, 262_144));
+        assertEquals(16_384, AiPanel.compactionBudgetTokens(true, 32_768));
+        assertEquals(32_768, AiPanel.compactionBudgetTokens(true, 65_536));
+        // a 256k window adopted from another client is used, but the panel still budgets as if it were 64k
+        assertEquals(32_768, AiPanel.compactionBudgetTokens(true, 262_144));
+    }
+
+    @Test
+    void localCompactionShrinksThePreviousTurnAndDropsOldTurnsUntilHalfTheBudget() {
+        List<LlmClient.Message> history = new ArrayList<>();
+        for (int i = 1; i <= 6; i++) {
+            history.addAll(turn("q" + i, BIG));
+        }
+        // six turns of ~5,000 chars of tool results each; budget 4,000 tokens -> target ~2,000 tokens (8,000 chars)
+        AiPanel.compactLocalHistory(history, 4_000);
+
+        // the previous turn's tool result was cut too, unlike the per-turn compaction of hosted endpoints
+        for (LlmClient.Message m : history) {
+            if (m.toolResults() != null) {
+                assertTrue(m.toolResults().get(0).content().length() < 500, "tool results are cut");
+            }
+        }
+        assertTrue(AiPanel.estimateTokens(AiPanel.historyChars(history)) <= 2_000);
+        // the newest turn is always kept
+        assertEquals("answer to q6", history.get(history.size() - 1).content());
+    }
+
+    @Test
+    void dropOldestTurnRemovesTheFirstQuestionWithItsAnswer() {
+        List<LlmClient.Message> history = new ArrayList<>();
+        history.addAll(turn("q1", "r1"));
+        history.addAll(turn("q2", "r2"));
+        AiPanel.dropOldestTurn(history);
+        assertEquals(4, history.size());
+        assertEquals("q2", history.get(0).content());
+        // a single turn is never dropped by the loop in compactLocalHistory; the helper alone leaves it too
+        AiPanel.dropOldestTurn(history);
+        assertEquals(4, history.size());
+    }
+
+    @Test
+    void compactionNoticeExplainsTheRePrefillCostLocally() {
+        String local = AiPanel.describeCompaction(true, 24_800, 8_100, true, 650);
+        assertTrue(local.startsWith("History compacted automatically: ~24.8k -> ~8.1k tokens."), local);
+        assertTrue(local.contains("about 12s at 650 tok/s, measured"), local);
+        String manual = AiPanel.describeCompaction(false, 24_800, 8_100, true, 0);
+        assertTrue(manual.startsWith("Compacting history:"), manual);
+        assertTrue(manual.contains("at 600 tok/s, assumed"), manual);
+        String hosted = AiPanel.describeCompaction(true, 24_800, 8_100, false, 0);
+        assertEquals("History compacted automatically: ~24.8k -> ~8.1k tokens, saving ~16.7k tokens per request.",
+                hosted);
+    }
+
     @Test
     void truncatesOversizedToolResultsButKeepsShortOnes() {
         String small = "ok";
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java
index 3ad9ca8eb058..b5764201ec26 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java
@@ -47,6 +47,27 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
 
 class AiPanelTest {
 
+    @Test
+    void bylineSaysWhatTheQuestionCostInPlainWords() {
+        AiPanel.ConversationEntry plain = new AiPanel.ConversationEntry(
+                AiRole.ASSISTANT, "hi", 3_200, 3_200, 0, 0, 4_900, 1, false, 7);
+        assertEquals("3.2s · 4.9k tokens · ctx 7%", plain.byline());
+
+        AiPanel.ConversationEntry tools = new AiPanel.ConversationEntry(
+                AiRole.ASSISTANT, "hi", 11_700, 11_700, 40, 2, 14_200, 3, false, 7);
+        assertEquals("11.7s · 2 tool calls · 3 requests · 14.2k tokens · ctx 7%", tools.byline());
+
+        AiPanel.ConversationEntry limit = new AiPanel.ConversationEntry(
+                AiRole.ASSISTANT, "hi", 61_100, 61_100, 2_500, 25, 231_300, 26, true, 18);
+        assertEquals("61.1s · 25 tool calls, limit reached (2.5s in tools) · 26 requests · 231.3k tokens · ctx 18%",
+                limit.byline());
+
+        // hosted providers have no window: no fill; the old seven-argument form still works
+        AiPanel.ConversationEntry hosted = new AiPanel.ConversationEntry(
+                AiRole.ASSISTANT, "hi", 2_000, 2_000, 0, 1, 900);
+        assertEquals("2.0s · 1 tool call · 900 tokens", hosted.byline());
+    }
+
     @Test
     void normalTextStillGoesToLlm() throws Exception {
         AiPanel panel = new AiPanel();
@@ -982,8 +1003,34 @@ class AiPanelTest {
         assertEquals(AiPanel.MAX_ITERATIONS, last.toolCalls(), "every round trip before the wrap-up made a tool call");
         assertEquals(AiPanel.MAX_ITERATIONS, client.toolRoundTrips);
         assertTrue(client.sawWrapUpRequest, "the model must be told the tool budget is spent");
+        assertTrue(client.sawWrapUpWithTools, "the wrap-up keeps the tools in the request so the cached prefix holds");
         assertTrue(panel.conversationForTesting().stream().noneMatch(e -> e.role() == AiRole.ERROR),
                 "reaching the limit must not surface as an error when the model can still answer");
+        assertEquals(AiPanel.MAX_ITERATIONS + 1, last.requests(), "25 tool round trips plus the wrap-up");
+        assertTrue(last.limitReached());
+        assertTrue(last.byline().contains("25 tool calls, limit reached · 26 requests"), last.byline());
+    }
+
+    @Test
+    void aModelThatKeepsCallingToolsAtTheLimitIsAskedOnceMoreWithoutThem() throws Exception {
+        AiPanel panel = new AiPanel();
+        panel.setToolRegistryForTesting(new TuiToolRegistry(null));
+        BusyLlmClient client = new BusyLlmClient();
+        client.answersWhileToolsArePresent = false;
+        panel.setClientForTesting(client);
+        panel.open();
+        type(panel, "send a few messages into the app");
+        panel.handleKeyEvent(KeyEvent.ofKey(KeyCode.ENTER, KeyModifiers.NONE));
+        await().atMost(10, TimeUnit.SECONDS).until(() -> !panel.isAgentThreadRunningForTesting());
+
+        AiPanel.ConversationEntry last = panel.conversationForTesting().get(panel.conversationForTesting().size() - 1);
+        assertEquals(AiRole.ASSISTANT, last.role(), last.text());
+        assertEquals("I sent the messages; they all failed in the jq transform.", last.text());
+        // 25 tool round trips, the wrap-up with tools that the model answered with yet another tool call, then the
+        // wrap-up without tools
+        assertEquals(AiPanel.MAX_ITERATIONS + 1, client.toolRoundTrips);
+        assertEquals(AiPanel.MAX_ITERATIONS + 2, last.requests());
+        assertTrue(last.limitReached());
     }
 
     /**
@@ -994,6 +1041,7 @@ class AiPanelTest {
 
         volatile int toolRoundTrips;
         volatile boolean sawWrapUpRequest;
+        volatile boolean sawWrapUpWithTools;
 
         BusyLlmClient() {
             withModel("test-model");
@@ -1005,11 +1053,17 @@ class AiPanelTest {
             return true;
         }
 
+        volatile boolean answersWhileToolsArePresent = true;
+
         @Override
         public ChatResponse chatWithTools(String systemPrompt, List<Message> messages, List<ToolDef> tools) {
-            if (tools.isEmpty()) {
-                Message lastMessage = messages.get(messages.size() - 1);
-                if (lastMessage.content() != null && lastMessage.content().contains("cannot call any more")) {
+            Message lastMessage = messages.get(messages.size() - 1);
+            boolean wrapUp = lastMessage.content() != null && lastMessage.content().contains("cannot call any more");
+            if (wrapUp && !tools.isEmpty()) {
+                sawWrapUpWithTools = true;
+            }
+            if (tools.isEmpty() || (wrapUp && answersWhileToolsArePresent)) {
+                if (wrapUp) {
                     sawWrapUpRequest = true;
                 }
                 return new ChatResponse(
@@ -1103,6 +1157,34 @@ class AiPanelTest {
         assertEquals(2, panel.conversationForTesting().stream().filter(e -> e.role() == AiRole.USER).count());
     }
 
+    @Test
+    void usageAveragesPerQuestionAndPerRequestAreBothReported() {
+        AiPanel panel = new AiPanel();
+        panel.setClientForTesting(new RecordingLlmClient("ok"));
+        // question 1 took three round trips, question 2 one; a route call is not a question
+        Instant now = Instant.now();
+        panel.recordUsageForTesting(new AiPanel.AiUsageEntry(
+                "m", "ollama", 4_000, 20, 4_020, 3_000, "tool_calls", now,
+                AiPanel.AiUsageSource.TUI, null, 1));
+        panel.recordUsageForTesting(new AiPanel.AiUsageEntry(
+                "m", "ollama", 4_100, 20, 4_120, 1_000, "tool_calls", now,
+                AiPanel.AiUsageSource.TUI, null, 1));
+        panel.recordUsageForTesting(new AiPanel.AiUsageEntry(
+                "m", "ollama", 4_300, 90, 4_390, 2_000, "stop", now,
+                AiPanel.AiUsageSource.TUI, null, 1));
+        panel.recordUsageForTesting(new AiPanel.AiUsageEntry(
+                "m", "ollama", 4_400, 30, 4_430, 2_000, "stop", now,
+                AiPanel.AiUsageSource.TUI, null, 2));
+        panel.recordUsageForTesting(new AiPanel.AiUsageEntry(
+                "m", "ollama", 400, 30, 430, 8_000, "stop", now,
+                AiPanel.AiUsageSource.ROUTE, "chat-route", 0));
+
+        assertEquals(2, AiPanel.countQuestions(panel.combinedUsageEntriesForTesting()));
+        String summary = panel.usageSummary();
+        // 8 s of panel time over 2 questions; 16 s over 5 requests
+        assertTrue(summary.contains("- **Avg per question:** 4.0s (3.2s per request)"), summary);
+    }
+
     @Test
     void usageSummaryReportsTotalsPerModelAndLastRequest() {
         AiPanel panel = new AiPanel();
@@ -1118,7 +1200,8 @@ class AiPanelTest {
 
         assertTrue(summary.startsWith("**AI usage:** 2 request(s)"), summary);
         assertTrue(summary.contains("- **Tokens:** 6.5k (in 6.2k, out 300)"), summary);
-        assertTrue(summary.contains("- **Avg latency:** 3.5s"), summary);
+        // two requests without a question number are one question of 7.0s
+        assertTrue(summary.contains("- **Avg per question:** 7.0s (3.5s per request)"), summary);
         assertTrue(summary.contains("| [tui] qwen3.6:35b-a3b (ollama) | 2 | 6.2k | 300 | 6.5k | 3.5s |"), summary);
         assertTrue(summary.contains("- **Last request:** 3.4k tokens in 2.0s"), summary);
     }
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaMonitorTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaMonitorTest.java
index eff4841e1a1a..aeef31603617 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaMonitorTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaMonitorTest.java
@@ -249,7 +249,9 @@ class OllamaMonitorTest {
         assertEquals("stop", q7.doneReason());
         // evaluated 4,500 + 200 + 2,300 tokens over 9.2 s of prefill
         assertEquals(7_000 * 1000.0 / 9_200, q7.prefillTokensPerSecond(), 0.5);
-        assertTrue(q7.wallMs() >= 5_500);
+        // the three replies arrived within the same millisecond in this test, so the wall time is the first
+        // request's own duration plus nothing: at least as long as the first step, never shorter than the last
+        assertTrue(q7.wallMs() >= 6_900, "wall " + q7.wallMs());
 
         JsonArray questions = (JsonArray) monitor.toJson(10).get("questions");
         assertEquals(3, questions.size());
@@ -267,6 +269,110 @@ class OllamaMonitorTest {
         assertFalse(monitor.snapshot().connected());
     }
 
+    @Test
+    void theQuestionBeingAnsweredIsListedUntilTheTurnEnds() {
+        OllamaMonitor monitor = new OllamaMonitor();
+        monitor.questionStarted(9, "what's the name of the source file that has the route");
+
+        // asked, nothing back yet: a question with no steps
+        JsonArray questions = (JsonArray) monitor.toJson(10).get("questions");
+        assertEquals(1, questions.size());
+        JsonObject q = (JsonObject) questions.get(0);
+        assertEquals(9, q.get("question"));
+        assertEquals(0, q.get("steps"));
+        assertEquals(true, q.get("inProgress"));
+        assertNotNull(q.get("elapsedMs"));
+        assertNotNull(monitor.snapshot().activeQuestion());
+
+        // the first tool call returned: the same question, now with a step, still in progress
+        monitor.recordRequest("m", new LlmClient.TokenUsage(9_000, 40, 9_040, 0, 5_000, 700, 0, 5_800), 0,
+                "tool_calls", 9, "what's the name of the source file that has the route");
+        questions = (JsonArray) monitor.toJson(10).get("questions");
+        assertEquals(1, questions.size());
+        q = (JsonObject) questions.get(0);
+        assertEquals(1, q.get("steps"));
+        assertEquals(true, q.get("inProgress"));
+
+        // the answer landed
+        monitor.recordRequest("m", new LlmClient.TokenUsage(9_400, 120, 9_520, 9_000, 300, 2_000, 0, 2_400), 0,
+                "stop", 9, "what's the name of the source file that has the route");
+        monitor.questionFinished();
+        q = (JsonObject) ((JsonArray) monitor.toJson(10).get("questions")).get(0);
+        assertEquals(2, q.get("steps"));
+        assertNull(q.get("inProgress"));
+        assertNull(monitor.snapshot().activeQuestion());
+    }
+
+    @Test
+    void theQuestionSummaryAveragesPerQuestionAndLeavesRoutesOut() {
+        OllamaMonitor monitor = new OllamaMonitor();
+        monitor.updateModels(List.of(new OllamaMonitor.LoadedModel(
+                "m", "f", "35.5B", "Q4_K_M", 1, 1, 65_536, null, null)));
+        // question 1: two steps, 4 s of wall time, ended at the tool-call limit
+        monitor.recordRequest("m", new LlmClient.TokenUsage(5_000, 40, 5_040, 4_000, 500, 1_000, 0, 1_500), 0,
+                "tool_calls", 1, "one");
+        monitor.recordRequest("m", new LlmClient.TokenUsage(5_200, 160, 5_360, 5_000, 200, 2_300, 0, 2_500), 0,
+                "limit", 1, "one");
+        // question 2: one step of 2 s
+        monitor.recordRequest("m", new LlmClient.TokenUsage(5_400, 100, 5_500, 5_200, 200, 1_800, 0, 2_000), 0,
+                "stop", 2, "two");
+        // a route call is not a question
+        monitor.ingestSpans(List.of(genAiSpan("s1", "ollama", "m", "chat-route", 412, 180, 9_000)));
+
+        OllamaMonitor.QuestionSummary s
+                = OllamaMonitor.QuestionSummary.of(OllamaMonitor.groupByQuestion(monitor.snapshot().requests()));
+        assertEquals(2, s.questions());
+        assertEquals(3, s.requests());
+        assertEquals(5_300, s.avgPromptTokens(), "average of each question's largest prompt");
+        assertEquals(150, s.avgOutputTokens());
+        assertEquals(91, s.cacheHitPercent(), "14.2k cached of 15.6k prompt tokens");
+        assertEquals(8, s.peakContextPercent());
+        assertEquals(1, s.limitHits());
+        // the fake requests land at once, so a question's wall time is its first step's total plus the rest:
+        // (1.5 s + 1 s) and 2 s, averaged
+        assertTrue(s.avgWallMs() >= 2_250 && s.avgWallMs() < 2_400, "was " + s.avgWallMs());
+        assertEquals(350, s.avgTtftMs());
+        assertEquals(59, Math.round(s.decodeTokensPerSecond()), "300 tokens over 5.1 s of decode");
+        assertEquals(1556, Math.round(s.prefillTokensPerSecond()), "1.4k evaluated tokens over 0.9 s");
+
+        JsonObject js = (JsonObject) monitor.toJson(10).get("questionSummary");
+        assertEquals(2, js.get("questions"));
+        assertEquals(1, js.get("limitHits"));
+        assertEquals(s.avgWallMs(), js.get("avgWallMs"));
+
+        assertEquals(OllamaMonitor.QuestionSummary.EMPTY, OllamaMonitor.QuestionSummary.of(List.of()));
+    }
+
+    @Test
+    void panelContextAppearsInTheJsonOnceKnown() {
+        OllamaMonitor monitor = new OllamaMonitor();
+        assertNull(monitor.toJson(1).get("aiPanel"));
+        monitor.setPanelContext(32_768, 16_384);
+        JsonObject panel = (JsonObject) monitor.toJson(1).get("aiPanel");
+        assertEquals(32_768, panel.get("contextWindow"));
+        assertEquals(16_384, panel.get("compactsAbove"));
+    }
+
+    @Test
+    void aSmallerStepWithinAQuestionIsNotACompactionButASmallerNextQuestionIs() {
+        OllamaMonitor monitor = new OllamaMonitor();
+        monitor.updateModels(List.of(new OllamaMonitor.LoadedModel(
+                "m", "f", "35.5B", "Q4_K_M", 1, 1, 32_768, null, null)));
+        // question 3 grows over its steps, then the wrap-up after the tool-call limit is smaller: no compaction
+        monitor.recordRequest("m", new LlmClient.TokenUsage(20_000, 40, 20_040, 19_000, 300, 700, 0, 1_000), 0,
+                "tool_calls", 3, "q3");
+        monitor.recordRequest("m", new LlmClient.TokenUsage(24_000, 40, 24_040, 23_000, 300, 700, 0, 1_000), 0,
+                "tool_calls", 3, "q3");
+        monitor.recordRequest("m", new LlmClient.TokenUsage(15_000, 200, 15_200, 0, 20_000, 3_000, 0, 23_000), 0,
+                "limit", 3, "q3");
+        assertEquals(0, monitor.snapshot().totals().compactions());
+        // the next question starts far below where the previous one ended: that is a compaction
+        monitor.recordRequest("m", new LlmClient.TokenUsage(9_000, 40, 9_040, 0, 900, 700, 0, 1_600), 0,
+                "stop", 4, "q4");
+        assertEquals(1, monitor.snapshot().totals().compactions());
+        assertEquals("limit", OllamaMonitor.groupByQuestion(monitor.snapshot().requests()).get(1).doneReason());
+    }
+
     @Test
     void availabilityFollowsTheServer() {
         OllamaMonitor monitor = new OllamaMonitor();
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaTabRenderTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaTabRenderTest.java
index 8a77262cbae3..3a4dd722fb76 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaTabRenderTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/OllamaTabRenderTest.java
@@ -22,6 +22,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.concurrent.atomic.AtomicReference;
 
+import dev.tamboui.style.Style;
 import dev.tamboui.tui.event.KeyCode;
 import dev.tamboui.tui.event.KeyEvent;
 import dev.tamboui.tui.event.KeyModifiers;
@@ -94,8 +95,10 @@ class OllamaTabRenderTest {
         assertTrue(rendered.contains("qwen35moe"), rendered);
         assertTrue(rendered.contains("41 layers"), rendered);
         assertTrue(rendered.contains("256 experts (8 active)"), rendered);
+        assertTrue(rendered.contains("max ctx 256k"), rendered);
         assertTrue(rendered.contains("100% GPU"), rendered);
-        assertTrue(rendered.contains("ctx 262,144"), rendered);
+        assertTrue(rendered.contains("· ctx 256k ·"), rendered);
+        assertFalse(rendered.contains("of 256k"), rendered);
         // panels
         assertTrue(rendered.contains("Throughput"), rendered);
         assertTrue(rendered.contains("decode"), rendered);
@@ -190,6 +193,91 @@ class OllamaTabRenderTest {
         assertFalse(rendered.contains("step 1/3"), rendered);
     }
 
+    @Test
+    void aQuestionThatCostManyRequestsOrRanLongIsColoured() {
+        // the request count: plain for a few, yellow from ten, red when the tool-call limit ended the question
+        assertEquals(Theme.info(), OllamaTab.requestCountStyle(3, "stop"));
+        assertEquals(Theme.warning(), OllamaTab.requestCountStyle(OllamaTab.MANY_REQUESTS, "stop"));
+        assertEquals(Theme.error().bold(), OllamaTab.requestCountStyle(26, "limit"));
+        assertEquals(Theme.error().bold(), OllamaTab.requestCountStyle(2, "limit"));
+
+        // the total: plain under half a minute, yellow from there, orange from a minute
+        assertEquals(Style.EMPTY, OllamaTab.totalTimeStyle(12_000));
+        assertEquals(Theme.warning(), OllamaTab.totalTimeStyle(OllamaTab.SLOW_QUESTION_MS));
+        assertEquals(Style.EMPTY.fg(Theme.accent()).bold(), OllamaTab.totalTimeStyle(75_000));
+
+        // and the row still reads the same
+        localServerWithModel();
+        String question = "what's the name of the source file that has the route";
+        for (int i = 0; i < 25; i++) {
+            monitor.recordRequest("qwen3.6:35b-a3b", new LlmClient.TokenUsage(
+                    9_000 + i * 200, 40, 9_040, 8_800, 300,
+                    1_500, 0, 2_000), 0, "tool_calls", 9, question);
+        }
+        monitor.recordRequest("qwen3.6:35b-a3b", new LlmClient.TokenUsage(
+                14_000, 120, 14_120, 13_800, 300, 3_000, 0,
+                3_500), 0, "limit", 9, question);
+        String rendered = TuiTestHelper.renderToString(new OllamaTab(ctx, monitor), 200, 40);
+        assertTrue(rendered.contains("#9 ×26"), rendered);
+        assertTrue(rendered.contains("limit"), rendered);
+    }
+
+    @Test
+    void theQuestionBeingAnsweredShowsAsWorkingFromTheMomentItIsAsked() {
+        localServerWithModel();
+        String question = "what's the name of the source file that has the route";
+        monitor.questionStarted(9, question);
+
+        // before the first request returns: a row with the question, a running clock and no figures
+        OllamaTab tab = new OllamaTab(ctx, monitor);
+        String rendered = TuiTestHelper.renderToString(tab, 200, 40);
+        assertTrue(rendered.contains("Requests (0 questions, 0 requests, 1 in progress)"), rendered);
+        assertTrue(rendered.contains("#9"), rendered);
+        assertTrue(rendered.contains(question), rendered);
+        assertTrue(rendered.contains("working"), rendered);
+        assertFalse(rendered.contains("No requests yet"), rendered);
+
+        // a tool call came back: the normal row, still working rather than tool_calls
+        monitor.recordRequest("qwen3.6:35b-a3b", new LlmClient.TokenUsage(9_000, 40, 9_040, 0, 5_000, 700, 0, 5_800),
+                0, "tool_calls", 9, question);
+        rendered = TuiTestHelper.renderToString(tab, 200, 40);
+        assertTrue(rendered.contains("Requests (1 question, 1 request, 1 in progress)"), rendered);
+        assertTrue(rendered.contains("working"), rendered);
+        assertFalse(rendered.contains("tool_calls"), rendered);
+
+        // the answer landed
+        monitor.recordRequest("qwen3.6:35b-a3b", new LlmClient.TokenUsage(
+                9_400, 120, 9_520, 9_000, 300, 2_000, 0,
+                2_400), 0, "stop", 9, question);
+        monitor.questionFinished();
+        rendered = TuiTestHelper.renderToString(tab, 200, 40);
+        assertTrue(rendered.contains("Requests (1 question, 2 requests)"), rendered);
+        assertTrue(rendered.contains("#9 ×2"), rendered);
+        assertFalse(rendered.contains("working"), rendered);
+        assertTrue(rendered.contains("stop"), rendered);
+    }
+
+    @Test
+    void aFooterAveragesTheQuestionsOnceThereAreTwo() {
+        localServerWithModel();
+        monitor.recordRequest("qwen3.6:35b-a3b", new LlmClient.TokenUsage(
+                5_000, 100, 5_100, 4_000, 500, 1_500, 0,
+                2_000), 0, "stop", 1, "how many routes");
+        String rendered = TuiTestHelper.renderToString(new OllamaTab(ctx, monitor), 200, 40);
+        assertFalse(rendered.contains("avg/question"), rendered);
+
+        monitor.recordRequest("qwen3.6:35b-a3b", new LlmClient.TokenUsage(
+                5_200, 40, 5_240, 5_000, 500, 500, 0,
+                1_000), 0, "tool_calls", 2, "how much memory");
+        monitor.recordRequest("qwen3.6:35b-a3b", new LlmClient.TokenUsage(
+                5_400, 300, 5_700, 5_200, 200, 4_800, 0,
+                5_000), 0, "limit", 2, "how much memory");
+        rendered = TuiTestHelper.renderToString(new OllamaTab(ctx, monitor), 200, 40);
+        assertTrue(rendered.contains("avg/question"), rendered);
+        assertTrue(rendered.contains("2 questions · 3 requests"), rendered);
+        assertTrue(rendered.contains("1 limit"), rendered);
+    }
+
     @Test
     void routeRequestsShowTheirRouteId() {
         localServerWithModel();
@@ -218,6 +306,21 @@ class OllamaTabRenderTest {
         assertEquals(1, ((JsonArray) summary.get("loadedModels")).size());
     }
 
+    @Test
+    void headerShowsWhatThePanelAsksForAndWhereItCompacts() {
+        localServerWithModel();
+        // the model in this fixture is loaded at 256k while the panel asked for 64k: both are named
+        monitor.setPanelContext(65_536, 32_768);
+        String rendered = TuiTestHelper.renderToString(new OllamaTab(ctx, monitor), 200, 40);
+        assertTrue(rendered.contains("AI panel asks 64k · AI panel compacts above 32k"), rendered);
+        // when the panel adopted the loaded window only the compaction point is worth a mention
+        monitor.setPanelContext(262_144, 32_768);
+        rendered = TuiTestHelper.renderToString(new OllamaTab(ctx, monitor), 200, 40);
+        assertFalse(rendered.contains("AI panel asks"), rendered);
+        assertTrue(rendered.contains("ctx 256k · unloads in"), rendered);
+        assertTrue(rendered.contains("AI panel compacts above 32k"), rendered);
+    }
+
     @Test
     void contextTrendShowsTurnsPeakAndCompactions() {
         localServerWithModel(); // ctx 262,144
@@ -253,7 +356,10 @@ class OllamaTabRenderTest {
         assertEquals("0", OllamaTab.formatRate(0));
         assertEquals("999", OllamaTab.formatTokens(999));
         assertEquals("1.2k", OllamaTab.formatTokens(1203));
-        assertEquals("262k", OllamaTab.formatTokens(262144));
+        assertEquals("256k", OllamaTab.formatTokens(262144));
+        assertEquals("64k", OllamaTab.formatTokens(65536));
+        assertEquals("32k", OllamaTab.formatTokens(32768));
+        assertEquals("250k", OllamaTab.formatTokens(250_000));
         assertEquals("1.5M", OllamaTab.formatTokens(1_500_000));
         assertEquals("0.14s", OllamaTab.formatSeconds(138));
         assertEquals("2.8s", OllamaTab.formatSeconds(2829));