fix(webui): retain system context graph after compaction (#6608)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-09 13:20:46 +08:00
1 parent d789e1bfc7
commit 4212ad726d
25 files changed
+748 -102

No files matched your search

+65 -1
View File
@@ -46,7 +46,7 @@ async def test_prompt_scopes_isolate_parallel_runs_and_cleanup_after_cancel(tmp_
))
finally:
record_source(tmp_path / "after.md", "after")
assert [source.path.name for source in enclosing] == ["after.md"]
assert [source.path.name for source in enclosing.sources] == ["after.md"]
cancelled = asyncio.create_task(run("first.md", blocked=True))
try:
@@ -57,3 +57,67 @@ async def test_prompt_scopes_isolate_parallel_runs_and_cleanup_after_cancel(tmp_
with pytest.raises(asyncio.CancelledError):
await cancelled
assert [[source.path.name for source in event.sources] for event in events] == [["first.md"], ["second.md"]]
async def test_compaction_publishes_rebuilt_sources_and_success_before_cancellation(tmp_path, monkeypatch):
from functools import partial
from unittest.mock import AsyncMock, MagicMock
from agent.runner_helpers import make_run_spec
from nanobot.agent.context import ContextBuilder, TranscriptInput
from nanobot.agent.runner import AgentRunner
from nanobot.context_sources import PromptSourcesEvent
from nanobot.events import ContextCompactionEvent
from nanobot.providers.base import LLMProvider
from nanobot.webui.context_source_hook import ContextSourceHook
(tmp_path / "SOUL.md").write_text("Be precise.", encoding="utf-8")
entered = asyncio.Event()
release = asyncio.Event()
events = []
async def publish(event):
if isinstance(event, PromptSourcesEvent):
events.append("sources")
entered.set()
await release.wait()
elif isinstance(event, ContextCompactionEvent):
events.append(event.phase)
provider = MagicMock(spec=LLMProvider)
provider.can_resume_conversation_state.return_value = False
provider.supports_pre_request_compaction.return_value = False
provider.chat_stream_with_retry = AsyncMock()
tools = MagicMock()
tools.get_definitions.return_value = []
def estimate(_provider, _model, messages, _tools):
return (600 if any("previous work" in str(message.get("content", "")) for message in messages) else 100, "test-counter")
monkeypatch.setattr("nanobot.agent.context_governance.estimate_prompt_tokens_chain", estimate)
async def run():
sink = EventSink(publish)
return await AgentRunner().run(make_run_spec(
provider, initial_messages=None, tools=tools, model="test", max_iterations=1,
max_tool_result_chars=10000, context_window_tokens=1624, max_tokens=100,
transcript_input=TranscriptInput(history=[{"role": "user", "content": "previous work"}], current_message="hello"),
transcript_builder=partial(ContextBuilder(tmp_path).build_transcript, channel="websocket"),
consolidate_history=AsyncMock(return_value="summary"), hook=ContextSourceHook(sink), events=sink,
))
task = asyncio.create_task(run())
ready = asyncio.create_task(entered.wait())
try:
done, _ = await asyncio.wait((ready, task), return_when=asyncio.FIRST_COMPLETED)
if task in done:
await task
pytest.fail("compaction did not publish prompt sources")
task.cancel()
finally:
release.set()
ready.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert events == ["started", "sources", "succeeded"]
provider.chat_stream_with_retry.assert_not_awaited()
+2 -2
View File
@@ -676,6 +676,6 @@ def test_context_skills_observe_resolved_alias_and_share_discovery(tmp_path, mon
with capture_sources() as sources:
content = loader.load_skills_for_context(["legacy", "canonical"])
assert content.count("# Instructions") == 2
assert [source.path for source in sources] == [path, path]
assert all(source.content == "# Instructions" for source in sources)
assert [source.path for source in sources.sources] == [path, path]
assert all(source.content == "# Instructions" for source in sources.sources)
assert len(discoveries) == 1
+17 -5
View File
@@ -12,6 +12,12 @@ from nanobot.agent.tools.cli_apps_config import CliAppsToolConfig
from nanobot.agent.tools.filesystem import FileToolsConfig
from nanobot.bus.queue import MessageBus
from nanobot.config.schema import ToolsConfig
from nanobot.context_sources import (
PromptSource,
capture_sources,
record_source,
system_source_scope,
)
from nanobot.llm_usage.context import llm_usage_source
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest
from nanobot.security.workspace_access import build_workspace_scope
@@ -297,11 +303,17 @@ async def test_subagent_pressure_uses_transient_summary(tmp_path):
context_window_tokens=1_624,
)
result = await manager.run_inline(
task="inspect the workspace",
session_key="test:direct",
runtime=runtime,
)
with capture_sources() as parent_sources:
with system_source_scope():
record_source(tmp_path / "SOUL.md", "parent prompt")
result = await manager.run_inline(
task="inspect the workspace",
session_key="test:direct",
runtime=runtime,
)
captured = parent_sources.drain()
assert captured.sources == ()
assert captured.system_sources == (PromptSource(tmp_path / "SOUL.md", "parent prompt"),)
assert result == "done"
consolidator.summarize_transcript.assert_awaited_once()
+25 -1
View File
@@ -6,7 +6,12 @@ import zlib
import pytest
from nanobot.session.display_history import HistoryFact, HistoryKind
from nanobot.session.history_graph import decode_graph, encode_graph, graph_decoding
from nanobot.session.history_graph import (
decode_graph,
decode_graph_parts,
encode_graph,
graph_decoding,
)
from nanobot.session.manager import SessionManager
from nanobot.webui.history import fact_from_record, record_from_fact
from nanobot.webui.transcript import build_webui_thread_response
@@ -16,6 +21,22 @@ def graph(count=5):
return {"nodes": [{"path": f"/{n}.md", "name": f"{n}.md", "tokens": 10, "state": "loaded"} for n in range(count)], "edges": []}
def test_graph_parts_keep_provenance_without_exposing_it_in_history():
system, reads = graph(1), graph(1)
system["nodes"][0]["tokens"] = 20
reads["nodes"][0]["tokens"] = 7
parts = {"kind": "context_graph_parts", "stage": graph(0), "system": system, "reads": reads}
fact = fact_from_record({"event": "model_request", "context_graph": parts, "turn_id": "turn"})
stored = HistoryFact.decode(fact.encode())
assert decode_graph_parts(stored.content["context_graph"]) == parts
projected = record_from_fact(stored, "websocket:test")
assert projected["context_graph"] == {
"nodes": [{"path": "/0.md", "name": "0.md", "tokens": 27, "state": "loaded"}], "edges": [],
}
copied = HistoryFact.decode(stored.encode())
assert record_from_fact(copied, "websocket:fork")["context_graph"] == projected["context_graph"]
def test_graph_codec_roundtrip_is_self_contained_and_preserves_order():
original = graph()
fact = fact_from_record({"event": "model_request", "context_graph": original})
@@ -40,6 +61,9 @@ def test_byte_limit_still_applies_before_graph_compression(monkeypatch):
monkeypatch.setattr("nanobot.session.display_history.MAX_HISTORY_FACT_BYTES", 2000)
with pytest.raises(ValueError, match="8 MiB"):
HistoryFact(HistoryKind.MODEL_REQUEST, {"context_graph": graph(100)}).encode()
parts = {"kind": "context_graph_parts", "stage": graph(30), "system": graph(30), "reads": graph(30)}
with pytest.raises(ValueError, match="8 MiB"):
HistoryFact(HistoryKind.MODEL_REQUEST, {"context_graph": parts}).encode()
@pytest.mark.parametrize("compressed", [False, True])
+4 -3
View File
@@ -14,7 +14,7 @@ def graph_from_observations(sources):
def graph_from_build(build):
with capture_sources() as sources:
build()
return graph_from_observations(sources)
return graph_from_observations([*sources.sources, *(sources.system_sources or [])])
def test_markdown_discovers_only_real_local_links_without_reading_targets(tmp_path: Path):
@@ -226,7 +226,8 @@ async def test_queued_skill_sources_reach_the_request(tmp_path: Path):
injected = [m for call in provider.chat_stream_with_retry.call_args_list
for m in call.kwargs['messages'] if m.get('role') == 'user' and '$example' in str(m.get('content'))]
assert injected
graph = graph_from_observations([source for event in events if isinstance(event, PromptSourcesEvent) for source in event.sources])
graph = graph_from_observations([source for event in events if isinstance(event, PromptSourcesEvent)
for source in (*event.sources, *(event.system_sources or ()))])
assert any(node['path'] == expected_path and node['state'] == 'loaded' for node in graph['nodes'])
assert {'source': expected_path, 'target': str(skill / 'guide.md')} in graph['edges']
@@ -254,6 +255,6 @@ def test_image_with_explicit_skill_reports_sources(tmp_path: Path):
with capture_sources() as sources:
current = ContextBuilder(tmp_path).build_current_message("$example", media=[str(image)])
assert isinstance(current["content"], list)
graph = graph_from_observations(sources)
graph = graph_from_observations(sources.sources)
assert graph["nodes"][0]["state"] == "loaded"
assert graph["edges"] == [{"source": str(skill / "SKILL.md"), "target": str(skill / "guide.md")}]
+38 -1
View File
@@ -6,7 +6,7 @@ import pytest
from nanobot.agent.hook import AgentHookContext
from nanobot.agent.progress_hook import AgentProgressHook
from nanobot.agent.tools.filesystem import ReadFileTool
from nanobot.context_graph import graph_from_sources
from nanobot.context_graph import graph_from_parts, graph_from_sources
from nanobot.context_sources import PromptSource
from nanobot.events import EventSink
from nanobot.file_references import REFERENCE_PARSERS, source_receipt
@@ -164,3 +164,40 @@ async def test_prompt_rebuild_deduplicates_files_and_compaction_refreshes_source
assert await observer.snapshot("chat", {}, persistent=False) == graph_from_sources([
source_receipt(refreshed.path, refreshed.content),
])
async def test_compaction_reuses_only_the_active_turns_system_sources(tmp_path):
observer = ContextGraphObserver(None)
first = {"webui_turn_id": "first"}
second = {"webui_turn_id": "second"}
soul = tmp_path / "SOUL.md"
await observer.observe_prompt("chat", (), first, persistent=False,
system_sources=(PromptSource(soul, "[Old](old.md)"),))
await observer.snapshot("chat", first, persistent=False)
parts = await observer.reset("chat", first, persistent=False)
assert parts is not None
assert {node["name"] for node in graph_from_parts(parts)["nodes"]} == {"SOUL.md", "old.md"}
await observer.observe_prompt("chat", (), second, persistent=False,
system_sources=(PromptSource(soul, "[New](new.md)"),))
graph = await observer.snapshot("chat", second, persistent=False)
assert {node["name"] for node in graph["nodes"]} == {"SOUL.md", "new.md"}
parts = await observer.reset("chat", second, persistent=False)
assert parts is not None
assert {node["name"] for node in graph_from_parts(parts)["nodes"]} == {"SOUL.md", "new.md"}
assert await observer.snapshot("other-chat", second, persistent=False) == EMPTY
async def test_reading_a_system_file_adds_its_read_tokens_once(tmp_path):
observer = ContextGraphObserver(None)
metadata = {"webui_turn_id": "turn"}
path = tmp_path / "SOUL.md"
prompt = "Be precise in all responses."
await observer.observe_prompt("chat", (), metadata, persistent=False,
system_sources=(PromptSource(path, prompt),))
event = read_event(path, "1| Additional instructions", call_id="read")
await observer.observe_tools("chat", [event, event], metadata, persistent=False)
expected = source_receipt(path, prompt)["tokens"] + event["context_source"]["tokens"]
first = await observer.snapshot("chat", metadata, persistent=False)
assert first["nodes"][0]["tokens"] == expected
assert await observer.snapshot("chat", metadata, persistent=False) == first