Skip to content

Agent Zero AI framework

Refresh context usage during tool-only runs

Alessandro10ec70643b99
diff --git a/plugins/_context_window/AGENTS.md b/plugins/_context_window/AGENTS.md
index fee9d7dfd..60ad6529f 100644
--- a/plugins/_context_window/AGENTS.md
+++ b/plugins/_context_window/AGENTS.md
@@ -43,9 +43,10 @@
restores the accepted response after the accounting tail is drained.
- Responses API turns keep their native result and callback behavior unchanged.
- Older chats without a stored breakdown show the explanatory empty state.
-- The indicator refreshes once per new Agent 0 generation, when the run
- completes, and when the active chat log GUID changes (including Clear Chat);
- streamed updates to the same generation do not refetch it.
+- The indicator refreshes once per new Agent 0 generation, after four root-agent
+ tool calls without another refresh, when the final response completes the run,
+ and when the active chat log GUID changes (including Clear Chat). Streamed
+ updates to an existing generation or tool log do not refetch it.
- `_model_config` supplies the effective model limit and the
`model-context-strip-end` WebUI slot; it does not own this feature's state.
- The `contextWindowUsage` Interface setting defaults to visible on mobile and
diff --git a/plugins/_context_window/extensions/webui/apply_snapshot_before/refresh-context-window.js b/plugins/_context_window/extensions/webui/apply_snapshot_before/refresh-context-window.js
index 51a17cdd5..f5dc58c3f 100644
--- a/plugins/_context_window/extensions/webui/apply_snapshot_before/refresh-context-window.js
+++ b/plugins/_context_window/extensions/webui/apply_snapshot_before/refresh-context-window.js
@@ -1,10 +1,16 @@
import { store as contextWindowStore } from "/plugins/_context_window/webui/context-window-store.js";
const OVERRIDE_REVISION_KEY = "_model_config_override_revision";
+const TOOL_REFRESH_INTERVAL = 4;
+const TOOL_LOG_TYPES = new Set([
+ "tool", "mcp", "code_exe", "text_editor", "subagent",
+]);
let lastContextId = "";
let lastRevision = null;
let lastLogGuid = "";
let lastGenerationKey = "";
+let lastToolNo = -1;
+let toolCallsSinceRefresh = 0;
function latestGenerationKey(logs) {
if (!Array.isArray(logs)) return "";
@@ -16,6 +22,14 @@ function latestGenerationKey(logs) {
return "";
}
+function rootToolNos(logs) {
+ if (!Array.isArray(logs)) return [];
+ return [...new Set(logs
+ .filter(item => TOOL_LOG_TYPES.has(item?.type) && Number(item.agentno || 0) === 0)
+ .map(item => Number(item.no))
+ .filter(Number.isInteger))];
+}
+
export default async function refreshContextWindow(ctx) {
const snapshot = ctx?.snapshot;
const contextId = String(snapshot?.context || "");
@@ -24,6 +38,8 @@ export default async function refreshContextWindow(ctx) {
lastRevision = null;
lastLogGuid = "";
lastGenerationKey = "";
+ lastToolNo = -1;
+ toolCallsSinceRefresh = 0;
return;
}
@@ -32,16 +48,29 @@ export default async function refreshContextWindow(ctx) {
const revision = active?.[OVERRIDE_REVISION_KEY] || null;
const logGuid = String(snapshot?.log_guid || "");
const generationKey = latestGenerationKey(snapshot?.logs);
+ const activeLogChanged = contextId !== lastContextId || logGuid !== lastLogGuid;
+ const toolNos = rootToolNos(snapshot?.logs);
+ if (activeLogChanged) {
+ lastToolNo = toolNos.length ? Math.max(...toolNos) : -1;
+ toolCallsSinceRefresh = 0;
+ } else {
+ const newToolNos = toolNos.filter(no => no > lastToolNo);
+ if (newToolNos.length) {
+ lastToolNo = Math.max(lastToolNo, ...newToolNos);
+ toolCallsSinceRefresh += newToolNos.length;
+ }
+ }
if (
- contextId === lastContextId
+ !activeLogChanged
&& revision === lastRevision
- && logGuid === lastLogGuid
&& (!generationKey || generationKey === lastGenerationKey)
+ && toolCallsSinceRefresh < TOOL_REFRESH_INTERVAL
) return;
lastContextId = contextId;
lastRevision = revision;
lastLogGuid = logGuid;
if (generationKey) lastGenerationKey = generationKey;
+ toolCallsSinceRefresh = 0;
await contextWindowStore.refresh(contextId);
}
diff --git a/plugins/_context_window/tests/test_context_window.py b/plugins/_context_window/tests/test_context_window.py
index 04ae433b3..a8d9ca3be 100644
--- a/plugins/_context_window/tests/test_context_window.py
+++ b/plugins/_context_window/tests/test_context_window.py
@@ -1,3 +1,6 @@
+import base64
+import shutil
+import subprocess
import sys
from pathlib import Path
from types import SimpleNamespace
@@ -195,8 +198,60 @@ def test_webui_and_accounting_are_plugin_owned():
assert 'item?.type !== "agent"' in refresh_hook
assert "Number(item.agentno || 0) !== 0" in refresh_hook
assert 'const logGuid = String(snapshot?.log_guid || "")' in refresh_hook
- assert "logGuid === lastLogGuid" in refresh_hook
+ assert "logGuid !== lastLogGuid" in refresh_hook
assert "generationKey === lastGenerationKey" in refresh_hook
+ assert "TOOL_REFRESH_INTERVAL = 4" in refresh_hook
+ assert 'watch("$store.chats.selectedContext?.running"' in context_store
+
+
[email protected](not shutil.which("node"), reason="Node.js is required")
+def test_webui_refreshes_after_four_distinct_root_tool_calls():
+ source = (
+ ROOT
+ / "plugins/_context_window/extensions/webui/apply_snapshot_before/refresh-context-window.js"
+ ).read_text(encoding="utf-8")
+ source = source.replace(
+ 'import { store as contextWindowStore } from "/plugins/_context_window/webui/context-window-store.js";',
+ "const contextWindowStore = { refresh: async id => globalThis.refreshes.push(id) };",
+ )
+ module_url = "data:text/javascript;base64," + base64.b64encode(
+ source.encode("utf-8")
+ ).decode("ascii")
+ script = f"""
+globalThis.refreshes = [];
+const {{ default: refresh }} = await import({module_url!r});
+const snapshot = (logs) => ({{
+ context: "chat-1",
+ contexts: [{{ id: "chat-1" }}],
+ log_guid: "log-1",
+ logs,
+}});
+const call = (logs) => refresh({{ snapshot: snapshot(logs) }});
+const assertCount = expected => {{
+ if (globalThis.refreshes.length !== expected) throw new Error(
+ `expected ${{expected}} refreshes, got ${{globalThis.refreshes.length}}`
+ );
+}};
+
+await call([]);
+assertCount(1);
+await call([{{ no: 1, type: "tool", agentno: 0 }}]);
+await call([{{ no: 1, type: "tool", agentno: 0, content: "updated" }}]);
+await call([{{ no: 2, type: "mcp", agentno: 0 }}]);
+await call([{{ no: 3, type: "code_exe", agentno: 0 }}]);
+await call([{{ no: 4, type: "text_editor", agentno: 0 }}]);
+assertCount(2);
+await call([{{ no: 5, type: "agent", agentno: 0, id: "gen-1" }}]);
+assertCount(3);
+await call([{{ no: 6, type: "tool", agentno: 0 }}]);
+await call([{{ no: 7, type: "mcp", agentno: 1 }}]);
+await call([{{ no: 8, type: "subagent", agentno: 0 }}]);
+await call([{{ no: 9, type: "text_editor", agentno: 0 }}]);
+assertCount(3);
+await call([{{ no: 10, type: "code_exe", agentno: 0 }}]);
+assertCount(4);
+"""
+ subprocess.run(["node", "--input-type=module", "-e", script], check=True)
def test_source_prompt_extensions_are_registered():