From 4212ad726d041a6a11107d978dc33243ca5618e7 Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Mon, 9 Nov 2026 13:20:46 +0800 Subject: [PATCH] fix(webui): retain system context graph after compaction (#6608) --- nanobot/agent/context.py | 19 +- nanobot/agent/context_governance.py | 20 +- nanobot/agent/subagent.py | 4 +- .../tests/test_websocket_outbound_delivery.py | 274 ++++++++++++++++++ nanobot/context_graph.py | 27 ++ nanobot/context_sources.py | 71 ++++- nanobot/session/history_graph.py | 39 ++- nanobot/webui/context_observer.py | 89 ++++-- nanobot/webui/context_source_hook.py | 9 +- nanobot/webui/outbound_delivery.py | 49 ++-- nanobot/webui/outbound_wire.py | 9 +- nanobot/webui/transcript.py | 2 + tests/agent/test_context_source_hook.py | 66 ++++- tests/agent/test_skills_loader.py | 4 +- tests/agent/test_subagent.py | 22 +- tests/session/test_history_graph.py | 26 +- tests/test_context_graph.py | 7 +- tests/webui/test_context_observer.py | 39 ++- webui/browser/history-hydration.spec.ts | 39 +++ webui/src/lib/api.ts | 1 + webui/src/lib/thread-event-projection.ts | 2 +- webui/src/lib/types.ts | 2 +- webui/src/lib/webui-thread-cache.ts | 11 +- webui/src/tests/model-request.test.ts | 18 ++ webui/src/tests/reload-cache.test.ts | 1 + 25 files changed, 748 insertions(+), 102 deletions(-) diff --git a/nanobot/agent/context.py b/nanobot/agent/context.py index dcb480423..268c70bf9 100644 --- a/nanobot/agent/context.py +++ b/nanobot/agent/context.py @@ -10,7 +10,7 @@ from nanobot.agent.skills import SkillsLoader from nanobot.agent.tools import mcp as mcp_tools from nanobot.agent.tools import sessions as session_tools from nanobot.apps.cli import utils as cli_app_utils -from nanobot.context_sources import record_source +from nanobot.context_sources import record_source, system_source_scope from nanobot.runtime_context import ( RUNTIME_CONTEXT_MESSAGE_META, RuntimeContextBlock, @@ -275,16 +275,15 @@ class ContextBuilder: """Build a model transcript while preserving the fresh-turn boundary.""" root = workspace or self.workspace with self.skills.snapshot(): + with system_source_scope(): + system_prompt = self.build_system_prompt( + channel=channel, + session_summary=transcript.session_summary, + workspace=root, + include_memory=include_memory, + ) messages: list[dict[str, Any]] = [ - { - "role": "system", - "content": self.build_system_prompt( - channel=channel, - session_summary=transcript.session_summary, - workspace=root, - include_memory=include_memory, - ), - }, + {"role": "system", "content": system_prompt}, *transcript.history, ] if transcript.current_message is None: diff --git a/nanobot/agent/context_governance.py b/nanobot/agent/context_governance.py index 3646d3769..12c9d00f2 100644 --- a/nanobot/agent/context_governance.py +++ b/nanobot/agent/context_governance.py @@ -21,6 +21,7 @@ from uuid import uuid4 from loguru import logger from nanobot.agent.context import TranscriptInput +from nanobot.context_sources import drain_system_sources from nanobot.events import NO_EVENTS, ContextCompactionEvent, EventSink from nanobot.providers.base import ( CONTEXT_SAFETY_BUFFER, @@ -706,13 +707,18 @@ class ContextGovernor: ), ) raise - await state.events.emit( - ContextCompactionEvent( - compaction_id=compaction_id, - phase="succeeded", - reason="context_pressure", - ), - ) + async def publish_success() -> None: + if (sources := drain_system_sources()) is not None: + await state.events.emit(sources) + await state.events.emit( + ContextCompactionEvent( + compaction_id=compaction_id, + phase="succeeded", + reason="context_pressure", + ), + ) + + await shield_and_drain(publish_success()) return prepared async def prepare_request( diff --git a/nanobot/agent/subagent.py b/nanobot/agent/subagent.py index 26b3965fd..1621c1eb9 100644 --- a/nanobot/agent/subagent.py +++ b/nanobot/agent/subagent.py @@ -38,6 +38,7 @@ from nanobot.bus.queue import MessageBus from nanobot.bus.runtime_events import RuntimeEventContext, SubagentTaskChanged from nanobot.config.network import NetworkConfig from nanobot.config.schema import AgentDefaults, ToolsConfig +from nanobot.context_sources import without_source_capture from nanobot.events import AgentEvent, EventSink from nanobot.llm_usage.context import LLMUsageSource, current_llm_usage_source from nanobot.providers.base import LLMProvider, ToolCallRequest @@ -597,7 +598,8 @@ class SubagentManager: ) self._tasks[task_id] = record self._publish_status(status) - execution = asyncio.create_task(self._run_subagent(record)) + with without_source_capture(): + execution = asyncio.create_task(self._run_subagent(record)) self._running_tasks[task_id] = execution execution.add_done_callback(partial(self._task_done, record)) logger.info("Started subagent [{}]: {}", task_id, diff --git a/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py b/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py index b2aee5c9c..da3f125ca 100644 --- a/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py +++ b/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py @@ -826,3 +826,277 @@ async def test_context_observer_orders_reads_requests_and_compaction(history, tm await channel.send(await message(ModelRequestEvent("reset", "run", 4, "started"))) requests = [row for row in history.read(f"websocket:{chat}") if row["event"] == "model_request"] assert requests[-1]["context_graph"] == {"nodes": [], "edges": []} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("mode", ["local", "native", "response"]) +async def test_compaction_keeps_system_sources_in_new_graph(history, tmp_path, mode) -> None: + from functools import partial + + from nanobot.agent.context import ContextBuilder, TranscriptInput + from nanobot.agent.runner import AgentRunner, AgentRunSpec + from nanobot.bus.outbound_events import ProgressEvent + from nanobot.events import EventSink, ModelRequestEvent + from nanobot.providers.base import GenerationSettings, LLMResponse + from nanobot.providers.compaction import NativeCompaction, ProviderCompactionEvents + from nanobot.providers.openai_responses.state import ( + attach_responses_state, + build_responses_compaction_state, + ) + from nanobot.utils.llm_runtime import LLMRuntime + from nanobot.webui.context_observer import ContextGraphObserver + from nanobot.webui.context_source_hook import ContextSourceHook + + workspace = tmp_path / "prompt-workspace" + workspace.mkdir() + soul = workspace / "SOUL.md" + soul.write_text("Be precise. [Old](old.md)" if mode == "local" else "Be precise. [Guide](guide.md)", encoding="utf-8") + skill = workspace / "skills" / "review" / "SKILL.md" + if mode == "local": + skill.parent.mkdir(parents=True) + skill.write_text("---\nname: review\ndescription: Review changes.\n---\n\n# Review workflow", encoding="utf-8") + channel = _channel(history.sessions) + chat = "compacted-graph" + metadata = await history.metadata(chat, {"webui_turn_id": "turn"}) + connection = _RecordingConnection() + channel._attach(cast(Any, connection), chat) + + async def send(event): + await channel.send(OutboundMessage("websocket", chat, "", metadata=metadata, event=event)) + + def read_event(name, call_id): + return ProgressEvent(tool_events=[{ + "name": "read_file", "phase": "end", "call_id": call_id, + "arguments": {"path": str(workspace / name)}, "result": "1| content", + }]) + + async def provider_call(**kwargs): + assert "Be precise" in kwargs["messages"][0]["content"] + response = LLMResponse(content="done") + if mode == "native": + compaction = ProviderCompactionEvents(kwargs["provider_context"].events) + event_id = await compaction.start("provider_native") + state = build_responses_compaction_state(provider="codex", model="test", output_items=[ + {"type": "compaction", "encrypted_content": "synthetic"}, + ]) + assert state is not None + await compaction.accept(NativeCompaction(state, state, event_id), commit=None) + response.provider_compaction_applied = True + response.provider_compaction_state = state + response.provider_compaction_scope = "prior_context" + response.provider_compaction_event_id = event_id + async with asyncio.timeout(2): + while True: + frame = json.loads(await connection.sent.get()) + if frame.get("event") == "context_compaction" and frame.get("phase") == "succeeded": + break + graph = frame["context_graph"] + assert {"SOUL.md", "guide.md"} <= {node["name"] for node in graph["nodes"]} + assert "before.py" not in {node["name"] for node in graph["nodes"]} + replay = history.build(f"websocket:{chat}", include_model_requests=True) + boundary = next(row for row in replay["events"] if row.get("event") == "context_compaction") + assert boundary["context_graph"] == graph + observer = ContextGraphObserver(history.sessions) + assert await observer.snapshot(chat, metadata, persistent=True) == graph + elif mode == "local": + assert "Summary of earlier work" in kwargs["messages"][0]["content"] + else: + attach_responses_state(response, provider="codex", model="test", input_items=[], output_items=[ + {"type": "compaction", "encrypted_content": "synthetic"}, + ]) + return response + + provider = MagicMock() + provider.chat_stream_with_retry = provider_call + tools = MagicMock() + tools.get_definitions.return_value = [] + events = EventSink(send) + + async def consolidate_history(_messages, _summary): + soul.write_text("Be precise. [Guide](guide.md)", encoding="utf-8") + return "Summary of earlier work" + + try: + await send(read_event("before.py", "before")) + result = await AgentRunner().run(AgentRunSpec( + initial_messages=None, tools=tools, + runtime=LLMRuntime(provider=provider, model="test", generation=GenerationSettings(max_tokens=1000), + context_window_tokens=8192 if mode == "local" else 128000), + max_iterations=2, max_tool_result_chars=10000, workspace=workspace, + transcript_input=TranscriptInput( + history=[{"role": "user", "content": "previous work " * 12000}] if mode == "local" else [], + current_message="hello $review" if mode == "local" else "hello", + ), + transcript_builder=partial(ContextBuilder(workspace).build_transcript, channel="websocket"), + consolidate_history=consolidate_history, hook=ContextSourceHook(events), events=events, + )) + assert result.final_content == "done" + records = history.read(f"websocket:{chat}") + boundary = next(row for row in records if row.get("event") == "context_compaction" and row.get("phase") == "succeeded") + if mode != "local": + started = next(row for row in records if row.get("event") == "model_request" and row.get("phase") == "started") + assert "before.py" in {node["name"] for node in started["context_graph"]["nodes"]} + boundary_names = {node["name"] for node in boundary["context_graph"]["nodes"]} + assert {"SOUL.md", "guide.md"} <= boundary_names + assert "before.py" not in boundary_names + assert "old.md" not in boundary_names + completed = next(row for row in records if row.get("event") == "model_request" and row.get("phase") == "completed") + names = {node["name"] for node in completed["context_graph"]["nodes"]} + assert {"SOUL.md", "guide.md"} <= names + if mode == "local": + boundary_skill = next(node for node in boundary["context_graph"]["nodes"] if node["path"] == str(skill)) + request_skill = next(node for node in completed["context_graph"]["nodes"] if node["path"] == str(skill)) + assert boundary_skill["state"] == "discovered" + assert request_skill["state"] == "loaded" + assert {"source": str(soul), "target": str(workspace / "guide.md")} in completed["context_graph"]["edges"] + if mode == "response": + assert records.index(completed) < records.index(boundary) + else: + assert records.index(boundary) < records.index(completed) + assert "before.py" not in names + assert "old.md" not in names + + await send(read_event("after.py", "after")) + request = ModelRequestEvent("next", "run-next", 1, "started") + restored_channel = _channel(history.sessions) + await restored_channel.send(OutboundMessage("websocket", chat, "", metadata=metadata, event=request)) + records = history.read(f"websocket:{chat}") + latest = next(row for row in reversed(records) if row.get("event") == "model_request") + names = {node["name"] for node in latest["context_graph"]["nodes"]} + assert {"SOUL.md", "guide.md", "after.py"} <= names + assert "before.py" not in names + finally: + await channel._cleanup_connection(cast(Any, connection)) + + +@pytest.mark.asyncio +async def test_local_compaction_publishes_rebuilt_system_graph_before_next_request(history, tmp_path, monkeypatch) -> None: + from functools import partial + + from nanobot.agent.context import ContextBuilder, TranscriptInput + from nanobot.agent.runner import AgentRunner, AgentRunSpec + from nanobot.events import EventSink + from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest + from nanobot.utils.llm_runtime import LLMRuntime + from nanobot.webui.context_source_hook import ContextSourceHook + + workspace = tmp_path / "prompt-workspace" + workspace.mkdir() + soul = workspace / "SOUL.md" + soul.write_text("[Old](old.md)", encoding="utf-8") + channel = _channel(history.sessions) + chat = "rebuilt-prompt" + metadata = await history.metadata(chat, {"webui_turn_id": "turn"}) + + async def send(event): + await channel.send(OutboundMessage("websocket", chat, "", metadata=metadata, event=event)) + + provider = MagicMock(spec=LLMProvider) + provider.can_resume_conversation_state.return_value = False + provider.supports_pre_request_compaction.return_value = False + prompts = [] + + async def provider_call(**kwargs): + prompts.append(kwargs["messages"][0]["content"]) + if len(prompts) == 1: + return LLMResponse(content=None, tool_calls=[ToolCallRequest(id="edit", name="edit_file", arguments={})]) + return LLMResponse(content="done") + + provider.chat_stream_with_retry = provider_call + tools = MagicMock() + tools.get_definitions.return_value = [] + + async def edit_file(*_args, **_kwargs): + soul.write_text("[New](new.md)", encoding="utf-8") + return "updated" + + tools.execute = AsyncMock(side_effect=edit_file) + + def estimate(_provider, _model, messages, _tools): + has_tool_result = any(message.get("role") == "tool" and message.get("content") == "updated" for message in messages) + has_summary = any(message.get("role") == "system" and "Summary after compaction" in message.get("content", "") for message in messages) + return (600 if has_tool_result and not has_summary else 100, "test-counter") + + monkeypatch.setattr("nanobot.agent.context_governance.estimate_prompt_tokens_chain", estimate) + events = EventSink(send) + result = await AgentRunner().run(AgentRunSpec( + initial_messages=None, tools=tools, + runtime=LLMRuntime(provider=provider, model="test", generation=GenerationSettings(max_tokens=100), + context_window_tokens=1624), + max_iterations=2, max_tool_result_chars=10000, workspace=workspace, + transcript_input=TranscriptInput(history=[], current_message="update the prompt"), + transcript_builder=partial(ContextBuilder(workspace).build_transcript, channel="websocket"), + consolidate_history=AsyncMock(return_value="Summary after compaction"), + hook=ContextSourceHook(events), events=events, + )) + assert result.final_content == "done" + assert "[Old](old.md)" in prompts[0] + assert "[New](new.md)" in prompts[1] + records = history.read(f"websocket:{chat}") + boundary = next(row for row in records if row.get("event") == "context_compaction" and row.get("phase") == "succeeded") + request = next(row for row in reversed(records) if row.get("event") == "model_request" and row.get("phase") == "started") + assert boundary["context_graph"] == request["context_graph"] + names = {node["name"] for node in boundary["context_graph"]["nodes"]} + assert "new.md" in names and "old.md" not in names + replay = history.build(f"websocket:{chat}", include_model_requests=True) + replay_boundary = next(row for row in replay["events"] if row.get("event") == "context_compaction") + assert replay_boundary["context_graph"] == boundary["context_graph"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("batched", [False, True]) +@pytest.mark.parametrize("request_after_read", [False, True]) +async def test_next_turn_replaces_restored_system_sources_without_losing_reads(history, tmp_path, request_after_read, batched) -> None: + from nanobot.bus.outbound_events import ProgressEvent, TurnEndEvent + from nanobot.context_sources import PromptSource, PromptSourcesEvent + from nanobot.events import AgentEvent, ContextCompactionEvent, ModelRequestEvent + from nanobot.file_references import source_receipt + + channel = _channel(history.sessions) + chat = "restored-prompt" + first = await history.metadata(chat, {"webui_turn_id": "first"}) + second = await history.metadata(chat, {"webui_turn_id": "second"}) + soul = tmp_path / "SOUL.md" + old_prompt, new_prompt, read_content = "[Old](old.md)", "[New](new.md)", "[Post](post.md)" + + async def send(event, metadata): + await channel.send(OutboundMessage("websocket", chat, "", metadata=metadata, event=event)) + + def read(path, content, call_id): + return ProgressEvent(tool_events=[{ + "name": "read_file", "phase": "end", "call_id": call_id, + "arguments": {"path": str(path)}, "result": f"1| {content}", + }]) + + async def send_events(events, metadata): + messages = [OutboundMessage("websocket", chat, "", metadata=metadata, event=event) for event in events] + if batched: + await channel.send_batch(messages) + else: + for message in messages: + await channel.send(message) + + await send(PromptSourcesEvent((), (PromptSource(soul, old_prompt),)), first) + await send_events([ + ModelRequestEvent("first", "run-first", 1, "started"), + read(tmp_path / "before.py", "old read", "before"), + ], first) + await send(ContextCompactionEvent("compact", "succeeded"), first) + events: list[AgentEvent] = [read(soul, read_content, "after")] + if request_after_read: + events.append(ModelRequestEvent("after", "run-first", 2, "started")) + await send_events(events, first) + await send(TurnEndEvent(), first) + + await send(PromptSourcesEvent((), (PromptSource(soul, new_prompt),)), second) + await send(ModelRequestEvent("second", "run-second", 1, "started"), second) + records = history.read(f"websocket:{chat}") + graph = next(row["context_graph"] for row in reversed(records) if row.get("event") == "model_request") + nodes = {node["name"]: node for node in graph["nodes"]} + assert {"SOUL.md", "new.md", "post.md"} <= nodes.keys() + assert "old.md" not in nodes and "before.py" not in nodes + assert nodes["SOUL.md"]["tokens"] == ( + source_receipt(soul, new_prompt)["tokens"] + source_receipt(soul, read_content)["tokens"] + ) + assert {"source": str(soul), "target": str(tmp_path / "new.md")} in graph["edges"] + assert {"source": str(soul), "target": str(tmp_path / "post.md")} in graph["edges"] diff --git a/nanobot/context_graph.py b/nanobot/context_graph.py index f337b681e..3927a1e60 100644 --- a/nanobot/context_graph.py +++ b/nanobot/context_graph.py @@ -26,6 +26,33 @@ class ContextGraph(TypedDict): edges: list[ContextEdge] +class ContextGraphParts(TypedDict): + kind: Literal["context_graph_parts"] + stage: ContextGraph + system: ContextGraph + reads: ContextGraph + + +def merge_graph(target: ContextGraph, incoming: ContextGraph, *, accumulate: bool = False) -> ContextGraph: + nodes: dict[str, ContextNode] = {node["path"]: node.copy() for node in target["nodes"]} + for node in incoming["nodes"]: + previous = nodes.get(node["path"]) + if previous is None: + nodes[node["path"]] = node.copy() + elif node["state"] == "loaded": + previous["name"] = node["name"] + previous["state"] = "loaded" + previous["tokens"] = (previous["tokens"] + node["tokens"] if accumulate + else max(previous["tokens"], node["tokens"])) + edges = {(edge["source"], edge["target"]): edge for edge in target["edges"]} + edges.update({(edge["source"], edge["target"]): edge for edge in incoming["edges"]}) + return {"nodes": list(nodes.values()), "edges": list(edges.values())} + + +def graph_from_parts(parts: ContextGraphParts) -> ContextGraph: + return merge_graph(merge_graph(parts["stage"], parts["system"]), parts["reads"], accumulate=True) + + def parse_context_graph(value: object) -> ContextGraph | None: """Validate persisted graph data at the transcript boundary.""" if not isinstance(value, dict): diff --git a/nanobot/context_sources.py b/nanobot/context_sources.py index 86f1aa7c1..10c33d047 100644 --- a/nanobot/context_sources.py +++ b/nanobot/context_sources.py @@ -5,7 +5,7 @@ from __future__ import annotations from collections.abc import Generator from contextlib import contextmanager from contextvars import ContextVar -from dataclasses import dataclass +from dataclasses import dataclass, field from pathlib import Path from typing import TypedDict, cast @@ -30,26 +30,79 @@ class PromptSource: @dataclass(frozen=True) class PromptSourcesEvent(AgentEvent): sources: tuple[PromptSource, ...] + # None means no rebuild; an empty tuple is a rebuilt prompt with no sources. + system_sources: tuple[PromptSource, ...] | None = None -_sources: ContextVar[list[PromptSource] | None] = ContextVar("context_sources", default=None) +@dataclass +class SourceCapture: + sources: list[PromptSource] = field(default_factory=list) + system_sources: list[PromptSource] | None = None + + def drain(self) -> PromptSourcesEvent: + event = PromptSourcesEvent(tuple(self.sources), None if self.system_sources is None else tuple(self.system_sources)) + self.sources.clear() + self.system_sources = None + return event + + def drain_system(self) -> PromptSourcesEvent | None: + if self.system_sources is None: + return None + event = PromptSourcesEvent((), tuple(self.system_sources)) + self.system_sources = None + return event + + +_sources: ContextVar[SourceCapture | None] = ContextVar("context_sources", default=None) +_system_source: ContextVar[bool] = ContextVar("context_system_source", default=False) @contextmanager -def capture_sources() -> Generator[list[PromptSource]]: +def capture_sources() -> Generator[SourceCapture]: """Observe builder reads in one run, including its prompt worker tasks.""" - sources: list[PromptSource] = [] - token = _sources.set(sources) + capture = SourceCapture() + token = _sources.set(capture) try: - yield sources + yield capture finally: _sources.reset(token) +@contextmanager +def without_source_capture() -> Generator[None]: + """Keep independently scheduled runs from inheriting their parent's capture.""" + token = _sources.set(None) + try: + yield + finally: + _sources.reset(token) + + +@contextmanager +def system_source_scope() -> Generator[None]: + """Capture a replacement snapshot of the system prompt's file sources.""" + if (capture := _sources.get()) is not None: + # Compaction can rebuild the prompt before a request; keep the latest build. + capture.system_sources = [] + token = _system_source.set(True) + try: + yield + finally: + _system_source.reset(token) + + +def drain_system_sources() -> PromptSourcesEvent | None: + """Take a committed prompt rebuild without consuming pending turn sources.""" + capture = _sources.get() + return capture.drain_system() if capture is not None else None + + def record_source(path: Path, content: str, *, loaded: bool = True) -> None: - if (sources := _sources.get()) is not None: - # Keep parsing and token estimation out of prompt construction. - sources.append(PromptSource(path, content, loaded)) + if (capture := _sources.get()) is not None: + sources = capture.system_sources if _system_source.get() else capture.sources + if sources is not None: + # Keep parsing and token estimation out of prompt construction. + sources.append(PromptSource(path, content, loaded)) def parse_source_receipt(value: object) -> SourceReceipt | None: diff --git a/nanobot/session/history_graph.py b/nanobot/session/history_graph.py index b16172d14..d8f8afdc1 100644 --- a/nanobot/session/history_graph.py +++ b/nanobot/session/history_graph.py @@ -13,8 +13,10 @@ from typing import Any, cast from nanobot.context_graph import ( ContextEdge, ContextGraph, + ContextGraphParts, ContextNode, ContextSnapshot, + graph_from_parts, parse_context_graph, ) @@ -53,10 +55,25 @@ def encode_graph(value: object) -> object: return encoded if encoded is not None else value +def _parts_mapping(value: object) -> dict[str, object] | None: + if not isinstance(value, dict): + return None + parts = cast(dict[str, object], value) + return parts if parts.get("kind") == "context_graph_parts" else None + + def encode_graph_fields(content: Mapping[str, Any]) -> dict[str, Any]: result = dict(content) if "context_graph" in result: - result["context_graph"] = encode_graph(result["context_graph"]) + graph: object = result["context_graph"] + parts = _parts_mapping(graph) + if parts is not None: + result["context_graph"] = { + "kind": "context_graph_parts", + **{key: encode_graph(parts.get(key)) for key in ("stage", "system", "reads")}, + } + else: + result["context_graph"] = encode_graph(graph) snapshot = result.get("context_snapshot") if isinstance(snapshot, dict) and "graph" in snapshot: snapshot = cast(dict[str, Any], snapshot) @@ -150,6 +167,15 @@ class GraphDecoder: size += sum(self.sizes[id(node)] for node in nodes) + sum(self.sizes[id(edge)] for edge in edges) return {"nodes": nodes, "edges": edges} if size <= logical_bytes else None + def parts(self, value: object) -> ContextGraphParts | None: + parts = _parts_mapping(value) + if parts is None: + return None + stage, system, reads = (self.graph(parts.get(key)) for key in ("stage", "system", "reads")) + if stage is None or system is None or reads is None: + return None + return {"kind": "context_graph_parts", "stage": stage, "system": system, "reads": reads} + def graph(self, value: object) -> ContextGraph | None: if isinstance(value, str): key = value @@ -179,6 +205,9 @@ class GraphDecoder: graph = self.columns(json.loads(expanded), logical_size) except (ValueError, zlib.error, UnicodeDecodeError): return None + elif (raw_parts := _parts_mapping(cast(object, value))) is not None: + parts = self.parts(raw_parts) + graph = self.inline(graph_from_parts(parts)) if parts is not None else None else: graph = self.inline(cast(object, value)) self.graphs[key] = graph @@ -201,6 +230,10 @@ def decode_graph(value: object) -> ContextGraph | None: return (_decoder.get() or GraphDecoder()).graph(value) +def decode_graph_parts(value: object) -> ContextGraphParts | None: + return (_decoder.get() or GraphDecoder()).parts(value) + + def decode_snapshot(value: object) -> ContextSnapshot | None: if not isinstance(value, dict): return None @@ -226,7 +259,9 @@ def expand_graph_fields(content: Mapping[str, Any]) -> dict[str, Any]: def graph_size_adjustment(content: Mapping[str, Any]) -> int: """Retain the original replay byte budget despite storage compression.""" - values = [content.get("context_graph")] + graph: object = content.get("context_graph") + parts = _parts_mapping(graph) + values: list[object] = [parts.get(key) for key in ("stage", "system", "reads")] if parts is not None else [graph] snapshot = content.get("context_snapshot") if isinstance(snapshot, dict): values.append(cast(dict[str, object], snapshot).get("graph")) diff --git a/nanobot/webui/context_observer.py b/nanobot/webui/context_observer.py index ca21b171b..e7bc92f6e 100644 --- a/nanobot/webui/context_observer.py +++ b/nanobot/webui/context_observer.py @@ -11,7 +11,13 @@ from typing import Any, cast from loguru import logger -from nanobot.context_graph import ContextGraph, ContextNode, graph_from_sources +from nanobot.context_graph import ( + ContextGraph, + ContextGraphParts, + graph_from_parts, + graph_from_sources, + merge_graph, +) from nanobot.context_sources import PromptSource, SourceReceipt, parse_source_receipt from nanobot.file_references import source_receipt from nanobot.session.display_history import ( @@ -19,28 +25,12 @@ from nanobot.session.display_history import ( HistoryKind, HistoryReader, ) -from nanobot.session.history_graph import decode_graph +from nanobot.session.history_graph import decode_graph, decode_graph_parts from nanobot.session.manager import SessionManager from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY from nanobot.webui.session_identity import webui_session_key -def merge_graph(target: ContextGraph, incoming: ContextGraph, *, accumulate: bool = False) -> ContextGraph: - nodes: dict[str, ContextNode] = {node["path"]: node.copy() for node in target["nodes"]} - for node in incoming["nodes"]: - previous = nodes.get(node["path"]) - if previous is None: - nodes[node["path"]] = node.copy() - elif node["state"] == "loaded": - previous["name"] = node["name"] - previous["state"] = "loaded" - previous["tokens"] = (previous["tokens"] + node["tokens"] if accumulate - else max(previous["tokens"], node["tokens"])) - edges = {(edge["source"], edge["target"]): edge for edge in target["edges"]} - edges.update({(edge["source"], edge["target"]): edge for edge in incoming["edges"]}) - return {"nodes": list(nodes.values()), "edges": list(edges.values())} - - def read_source(event: Mapping[str, Any]) -> SourceReceipt | None: """Use only the returned numbered text, never reread a source or link target.""" if event.get("name") != "read_file" or event.get("phase") != "end": @@ -72,15 +62,27 @@ def read_source(event: Mapping[str, Any]) -> SourceReceipt | None: @dataclass class _State: + # Prompt sources and reads belong to the compaction stage; system sources + # belong to the current turn's prompt and are replaced on each rebuild. graph: ContextGraph = field(default_factory=lambda: {"nodes": [], "edges": []}) + reads: ContextGraph = field(default_factory=lambda: {"nodes": [], "edges": []}) + system_graph: ContextGraph = field(default_factory=lambda: {"nodes": [], "edges": []}) + system_turn_id: str | None = None calls: set[tuple[str | None, str]] = field(default_factory=set) + def request_parts(self, turn_id: object) -> ContextGraphParts: + system: ContextGraph = ( + self.system_graph if isinstance(turn_id, str) and turn_id and turn_id == self.system_turn_id + else {"nodes": [], "edges": []} + ) + return {"kind": "context_graph_parts", "stage": self.graph, "system": system, "reads": self.reads} + def apply(self, event: Mapping[str, Any], turn_id: str | None = None) -> None: call_id = event.get("call_id") source = parse_source_receipt(event.get("context_source")) if not isinstance(call_id, str) or (turn_id, call_id) in self.calls or source is None: return - self.graph = merge_graph(self.graph, graph_from_sources([source]), accumulate=True) + self.reads = merge_graph(self.reads, graph_from_sources([source]), accumulate=True) self.calls.add((turn_id, call_id)) @@ -93,9 +95,16 @@ def _restore(history: HistoryReader, generation: str | None) -> _State: for turn in history.turns(reverse=True): for _, fact in reversed(history.read_entries(turn.ordinal)): boundary = fact.kind is HistoryKind.COMPACTION and fact.content.get("phase") == "succeeded" - graph = decode_graph(fact.content.get("context_graph")) if fact.kind is HistoryKind.MODEL_REQUEST else None - if boundary or graph is not None: - if graph is not None: + value = fact.content.get("context_graph") + parts = decode_graph_parts(value) if fact.kind is HistoryKind.MODEL_REQUEST or boundary else None + graph = decode_graph(value) if parts is None and (fact.kind is HistoryKind.MODEL_REQUEST or boundary) else None + if boundary or parts is not None or graph is not None: + if parts is not None: + state.graph = parts["stage"] + state.system_graph = parts["system"] + state.system_turn_id = fact.turn_id + state.reads = parts["reads"] + elif graph is not None: state.graph = graph for event, turn_id in reversed(pending): state.apply(event, turn_id) @@ -154,26 +163,46 @@ class ContextGraphObserver: async def observe_prompt( self, chat_id: str, sources: tuple[PromptSource, ...], metadata: Mapping[str, Any], *, persistent: bool, + system_sources: tuple[PromptSource, ...] | None = None, ) -> None: - if not sources: + if not sources and system_sources is None: return - def project() -> ContextGraph: - receipts = [source_receipt(source.path, source.content, loaded=source.loaded) for source in sources] - return graph_from_sources(receipts) + def project() -> tuple[ContextGraph, ContextGraph | None]: + def graph_for(items: tuple[PromptSource, ...]) -> ContextGraph: + return graph_from_sources([ + source_receipt(source.path, source.content, loaded=source.loaded) for source in items + ]) + return graph_for(sources), graph_for(system_sources) if system_sources is not None else None try: - graph = await asyncio.to_thread(project) + graph, system_graph = await asyncio.to_thread(project) state = await self._state(chat_id, metadata, persistent=persistent) + if system_graph is not None: + turn_id = metadata.get(WEBUI_TURN_METADATA_KEY) + state.system_graph = system_graph + state.system_turn_id = turn_id if isinstance(turn_id, str) else None state.graph = merge_graph(state.graph, graph) except Exception: logger.exception("Unable to observe prompt sources for context graph") + async def snapshot_parts( + self, chat_id: str, metadata: Mapping[str, Any], *, persistent: bool, + ) -> ContextGraphParts: + state = await self._state(chat_id, metadata, persistent=persistent) + return state.request_parts(metadata.get(WEBUI_TURN_METADATA_KEY)) + async def snapshot( self, chat_id: str, metadata: Mapping[str, Any], *, persistent: bool, ) -> ContextGraph: - state = await self._state(chat_id, metadata, persistent=persistent) - return state.graph + return graph_from_parts(await self.snapshot_parts(chat_id, metadata, persistent=persistent)) - async def reset(self, chat_id: str, metadata: Mapping[str, Any], *, persistent: bool) -> None: + async def reset( + self, chat_id: str, metadata: Mapping[str, Any], *, persistent: bool, + ) -> ContextGraphParts | None: state = await self._state(chat_id, metadata, persistent=persistent) state.graph = {"nodes": [], "edges": []} + state.reads = {"nodes": [], "edges": []} state.calls.clear() + turn_id = metadata.get(WEBUI_TURN_METADATA_KEY) + if isinstance(turn_id, str) and turn_id and state.system_turn_id == turn_id: + return state.request_parts(turn_id) + return None diff --git a/nanobot/webui/context_source_hook.py b/nanobot/webui/context_source_hook.py index 0b28c2046..b779a06d4 100644 --- a/nanobot/webui/context_source_hook.py +++ b/nanobot/webui/context_source_hook.py @@ -18,13 +18,12 @@ class ContextSourceHook(AgentHook): return False async def before_model_request(self) -> None: - sources = tuple(self._sources) - self._sources.clear() - if sources: - await self._events.emit(PromptSourcesEvent(sources)) + event = self._sources.drain() + if event.sources or event.system_sources is not None: + await self._events.emit(event) async def on_finally(self, context: AgentRunHookContext) -> None: - self._sources.clear() + self._sources.drain() self._capture.__exit__(None, None, None) diff --git a/nanobot/webui/outbound_delivery.py b/nanobot/webui/outbound_delivery.py index 82e93b3fb..3370bf044 100644 --- a/nanobot/webui/outbound_delivery.py +++ b/nanobot/webui/outbound_delivery.py @@ -3,7 +3,7 @@ from __future__ import annotations import asyncio import json from collections.abc import Callable, Mapping, Sequence -from dataclasses import dataclass +from dataclasses import dataclass, replace from pathlib import Path from typing import TYPE_CHECKING, Any, Literal, Protocol, TypeAlias @@ -25,7 +25,7 @@ from nanobot.bus.outbound_events import ( ) from nanobot.bus.queue import MessageBus from nanobot.bus.runtime_events import SubagentTaskChanged -from nanobot.context_graph import ContextGraph +from nanobot.context_graph import ContextGraph, ContextGraphParts, graph_from_parts from nanobot.context_sources import PromptSourcesEvent from nanobot.events import ModelRequestEvent from nanobot.pairing.events import PairingChanged @@ -120,19 +120,22 @@ class WebUIOutboundDelivery: if not isinstance(event, ModelRequestEvent | ContextCompactionEvent): return project_notification(msg.chat_id, event, msg.metadata) persistent = self._temporary_chats.should_persist_transcript(msg.chat_id) - if isinstance(event, ModelRequestEvent): - graph: ContextGraph = {"nodes": [], "edges": []} - try: - graph = await self._context_graph.snapshot(msg.chat_id, msg.metadata, persistent=persistent) - except Exception: - logger.exception("Unable to restore context graph") - return project_notification(msg.chat_id, event, msg.metadata, context_graph=graph) - if event.phase == "succeeded": - try: - await self._context_graph.reset(msg.chat_id, msg.metadata, persistent=persistent) - except Exception: - logger.exception("Unable to reset context graph") - return project_notification(msg.chat_id, event, msg.metadata) + parts: ContextGraphParts | None = None + graph: ContextGraph | None = None + try: + if isinstance(event, ModelRequestEvent): + parts = await self._context_graph.snapshot_parts(msg.chat_id, msg.metadata, persistent=persistent) + elif event.phase == "succeeded": + parts = await self._context_graph.reset(msg.chat_id, msg.metadata, persistent=persistent) + if parts is not None: + graph = graph_from_parts(parts) + except Exception: + logger.exception("Unable to observe context graph") + if graph is None and isinstance(event, ModelRequestEvent): + graph = {"nodes": [], "edges": []} + notification = project_notification(msg.chat_id, event, msg.metadata, context_graph=graph) + assert notification is not None + return replace(notification, context_graph_parts=parts) async def initialize(self) -> None: await self._transcripts.initialize() @@ -219,6 +222,7 @@ class WebUIOutboundDelivery: for msg in messages: progress = msg.event if isinstance(msg.event, ProgressEvent) else None + parts: ContextGraphParts | None = None if progress is not None: body = await self._message_payload(msg, progress) persistent, label = True, " " @@ -226,6 +230,7 @@ class WebUIOutboundDelivery: notification = await self._project_notification(msg) assert notification is not None body = dict(notification.payload) + parts = notification.context_graph_parts persistent = notification.persistence == "turn_activity" label = f" {body['event']} " if persistent: @@ -244,7 +249,10 @@ class WebUIOutboundDelivery: recipients = self._transport.webui_recipients(ChatAudience(msg.chat_id)) frames.append((recipients, raw, label)) if persistent: - records.append({**body, "text": msg.content} if progress is not None else body) + record = {**body, "text": msg.content} if progress is not None else dict(body) + if parts is not None: + record["context_graph"] = parts + records.append(record) byte_count += size await flush() @@ -252,7 +260,7 @@ class WebUIOutboundDelivery: event = msg.event if isinstance(event, PromptSourcesEvent): await self._context_graph.observe_prompt( - msg.chat_id, event.sources, msg.metadata, + msg.chat_id, event.sources, msg.metadata, system_sources=event.system_sources, persistent=self._temporary_chats.should_persist_transcript(msg.chat_id), ) return @@ -298,6 +306,7 @@ class WebUIOutboundDelivery: await self._send_payload( msg.chat_id, notification.payload, persistence=notification.persistence, metadata=msg.metadata if notification.attach_turn_metadata else None, + context_graph_parts=notification.context_graph_parts, ) return if isinstance(event, GoalStateSyncEvent): @@ -559,11 +568,15 @@ class WebUIOutboundDelivery: persistence: WebUIWirePersistence, metadata: dict[str, Any] | None = None, turn_owner: str | None = None, + context_graph_parts: ContextGraphParts | None = None, ) -> None: recipients = self._transport.webui_recipients(ChatAudience(chat_id)) body: dict[str, Any] = dict(payload) if persistence == "turn_activity": - await self._persist_turn_transcript_event(chat_id, body, metadata=metadata, phase="activity") + await self._persist_turn_transcript_event( + chat_id, body, metadata=metadata, phase="activity", + transcript_overrides={"context_graph": context_graph_parts} if context_graph_parts is not None else None, + ) elif persistence == "turn_complete": prior_failure = ( (metadata or {}).get("webui") is True diff --git a/nanobot/webui/outbound_wire.py b/nanobot/webui/outbound_wire.py index 753485678..a12b69b6c 100644 --- a/nanobot/webui/outbound_wire.py +++ b/nanobot/webui/outbound_wire.py @@ -11,7 +11,7 @@ from nanobot.bus.outbound_events import ( RetryStatusEvent, TurnEndEvent, ) -from nanobot.context_graph import ContextGraph, ContextSnapshot +from nanobot.context_graph import ContextGraph, ContextGraphParts, ContextSnapshot from nanobot.events import AgentEvent, CompactionReason, ModelRequestEvent from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY @@ -111,6 +111,7 @@ class ModelRequestWirePayload(_ChatWirePayload): class ContextCompactionWirePayload(_ChatWirePayload): + context_graph: NotRequired[ContextGraph] context_snapshot: NotRequired[ContextSnapshot] event: Literal["context_compaction"] compaction_id: str @@ -253,6 +254,7 @@ class NotificationProjection: persistence: WebUIWirePersistence = "transient" deliver_offline: bool = False attach_turn_metadata: bool = False + context_graph_parts: ContextGraphParts | None = None def project_notification( @@ -278,8 +280,11 @@ def project_notification( payload, persistence="turn_activity", deliver_offline=True, attach_turn_metadata=True, ) if isinstance(event, ContextCompactionEvent): + compaction_payload = encode_context_compaction(chat_id, event) + if context_graph is not None: + compaction_payload["context_graph"] = context_graph return NotificationProjection( - encode_context_compaction(chat_id, event), + compaction_payload, persistence="transient" if event.phase == "started" else "turn_activity", deliver_offline=True, attach_turn_metadata=True, diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py index de9c18023..51109c9b9 100644 --- a/nanobot/webui/transcript.py +++ b/nanobot/webui/transcript.py @@ -1542,6 +1542,8 @@ def _client_projection_event( "compaction_id": compaction_id, "phase": phase, } + if (graph := decode_graph(record.get("context_graph"))) is not None: + projected["context_graph"] = graph if (snapshot := decode_snapshot(record.get("context_snapshot"))) is not None: projected["context_snapshot"] = snapshot reason = record.get("reason") diff --git a/tests/agent/test_context_source_hook.py b/tests/agent/test_context_source_hook.py index 22cb06538..c59584a1f 100644 --- a/tests/agent/test_context_source_hook.py +++ b/tests/agent/test_context_source_hook.py @@ -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() diff --git a/tests/agent/test_skills_loader.py b/tests/agent/test_skills_loader.py index 633bf0daa..3b30b1b4e 100644 --- a/tests/agent/test_skills_loader.py +++ b/tests/agent/test_skills_loader.py @@ -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 diff --git a/tests/agent/test_subagent.py b/tests/agent/test_subagent.py index 0187c58cb..05968f7c8 100644 --- a/tests/agent/test_subagent.py +++ b/tests/agent/test_subagent.py @@ -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() diff --git a/tests/session/test_history_graph.py b/tests/session/test_history_graph.py index 83a7d764a..395960cc0 100644 --- a/tests/session/test_history_graph.py +++ b/tests/session/test_history_graph.py @@ -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]) diff --git a/tests/test_context_graph.py b/tests/test_context_graph.py index 28e2e88fa..428903041 100644 --- a/tests/test_context_graph.py +++ b/tests/test_context_graph.py @@ -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")}] diff --git a/tests/webui/test_context_observer.py b/tests/webui/test_context_observer.py index 68304ed73..ebe871cca 100644 --- a/tests/webui/test_context_observer.py +++ b/tests/webui/test_context_observer.py @@ -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 diff --git a/webui/browser/history-hydration.spec.ts b/webui/browser/history-hydration.spec.ts index c3a2b5789..0474f2e8f 100644 --- a/webui/browser/history-hydration.spec.ts +++ b/webui/browser/history-hydration.spec.ts @@ -341,6 +341,45 @@ test("synthetic HTTP-first cumulative text suppresses delayed covered chunks but backend.healthy(); }); +test("compaction keeps active system files in the context graph through live delivery and replay", async ({ page }) => { + const { backend } = await openFixture(page); + const base = closedTurn("before-graph", "Previous question", "Previous answer."); + await backend.release(await backend.read(), history(base)); + const question = input(TURN, "Question requiring compaction"); + const system = { path: "/SOUL.md", name: "SOUL.md", state: "loaded" as const, tokens: 40 }; + const guide = { path: "/guide.md", name: "guide.md", state: "discovered" as const, tokens: 0 }; + const previous = { path: "/before.py", name: "before.py", state: "loaded" as const, tokens: 100 }; + const systemGraph = { nodes: [system, guide], edges: [{ source: system.path, target: guide.path }] }; + const started: ThreadProjectionEvent = { ...at(TURN, 1, "activity"), event: "model_request", + run_id: "run", request_id: "active", sequence: 1, phase: "started", + context_graph: { nodes: [system, guide, previous], edges: systemGraph.edges } }; + const compact: ThreadProjectionEvent = { ...at(TURN, 2, "activity"), event: "context_compaction", + compaction_id: "active", phase: "succeeded", context_graph: systemGraph }; + await backend.send(question); + await backend.send(started); + await page.getByTestId("composer-context-usage").click(); + const sidebar = page.getByTestId("context-sidebar"); + await expect(sidebar.getByRole("button", { name: "before.py", exact: true })).toBeVisible(); + await backend.send(compact); + await expect(sidebar.getByRole("button", { name: "SOUL.md", exact: true })).toBeVisible(); + await expect(sidebar.getByRole("button", { name: "guide.md", exact: true })).toBeVisible(); + await expect(sidebar.getByRole("button", { name: "before.py", exact: true })).toHaveCount(0); + + const replay = history([...base, question, started, compact], { active: TURN }); + backend.refreshThread(); + await backend.release(await backend.read(A, null, 1), replay); + await expect(sidebar.getByRole("button", { name: "SOUL.md", exact: true })).toBeVisible(); + await expect(sidebar.getByRole("button", { name: "before.py", exact: true })).toHaveCount(0); + await page.reload(); + await backend.ready(); + await backend.release(await backend.read(A, null, 2), replay); + if (!await sidebar.isVisible()) await page.getByTestId("composer-context-usage").click(); + await expect(sidebar.getByRole("button", { name: "SOUL.md", exact: true })).toBeVisible(); + await expect(sidebar.getByRole("button", { name: "guide.md", exact: true })).toBeVisible(); + await expect(sidebar.getByRole("button", { name: "before.py", exact: true })).toHaveCount(0); + backend.healthy(); +}); + test("the open context sidebar keeps its slot through hydration and empty conversation transitions", async ({ page }) => { const { backend } = await openFixture(page); await page.emulateMedia({ reducedMotion: "no-preference" }); diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.ts index af4f4216f..60d41d0f8 100644 --- a/webui/src/lib/api.ts +++ b/webui/src/lib/api.ts @@ -385,6 +385,7 @@ function parseThreadProjectionEvent(value: unknown, validatedGraphs: ReadonlySet if (value.text !== undefined && typeof value.text !== "string") break; return value as unknown as ThreadProjectionEvent; case "context_compaction": + if (value.context_graph !== undefined && !validatedGraphs.has(value.context_graph) && !isContextGraph(value.context_graph)) break; if (value.context_snapshot !== undefined && !isContextInspection(value.context_snapshot, (graph): graph is ContextGraph => validatedGraphs.has(graph) || isContextGraph(graph))) break; if (typeof value.compaction_id !== "string" || !value.compaction_id || !isCompactionPhase(value.phase) diff --git a/webui/src/lib/thread-event-projection.ts b/webui/src/lib/thread-event-projection.ts index 5f5230e59..5d78f1f45 100644 --- a/webui/src/lib/thread-event-projection.ts +++ b/webui/src/lib/thread-event-projection.ts @@ -1050,7 +1050,7 @@ export function projectThreadEvent( id, graph: event.context_snapshot.graph, estimatedTokens: event.context_snapshot.estimated_tokens, contextWindowTokens: event.context_snapshot.context_window_tokens, - } } : {}), + } } : event.context_graph ? { contextSnapshot: { id, graph: event.context_graph } } : {}), ...(!options.persisted ? { announce: true } : {}), }, ...positionedTurnFields(state.messages[existing], turnFieldsForProjection(state, event, "activity"), options), diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts index 70a8028c1..954205509 100644 --- a/webui/src/lib/types.ts +++ b/webui/src/lib/types.ts @@ -1588,7 +1588,7 @@ export type InboundEvent = agent_ui?: AgentUIBlob; } & InboundTurnMetadata) | (Exclude & InboundTurnMetadata) - | (Extract & InboundTurnMetadata & { context_snapshot?: ContextInspection }) + | (Extract & InboundTurnMetadata & { context_snapshot?: ContextInspection; context_graph?: ContextGraph }) | ({ event: "file_edit"; chat_id: string; diff --git a/webui/src/lib/webui-thread-cache.ts b/webui/src/lib/webui-thread-cache.ts index dac3bb619..2e4a5e631 100644 --- a/webui/src/lib/webui-thread-cache.ts +++ b/webui/src/lib/webui-thread-cache.ts @@ -40,9 +40,14 @@ function reloadPayload(body: WebuiThreadPersistedPayload): unknown { const { context_graph, ...rest } = event; return { ...rest, context_graph_ref: reference(context_graph) }; } - if (event.event === "context_compaction" && event.context_snapshot) { - const { graph, ...snapshot } = event.context_snapshot; - return { ...event, context_snapshot: { ...snapshot, graph_ref: reference(graph) } }; + if (event.event === "context_compaction" && (event.context_graph || event.context_snapshot)) { + const { context_graph, context_snapshot, ...rest } = event; + const snapshot = context_snapshot && (({ graph, ...fields }) => ({ ...fields, graph_ref: reference(graph) }))(context_snapshot); + return { + ...rest, + ...(context_graph ? { context_graph_ref: reference(context_graph) } : {}), + ...(snapshot ? { context_snapshot: snapshot } : {}), + }; } return event; }); diff --git a/webui/src/tests/model-request.test.ts b/webui/src/tests/model-request.test.ts index 935ffdf64..830170f3f 100644 --- a/webui/src/tests/model-request.test.ts +++ b/webui/src/tests/model-request.test.ts @@ -257,3 +257,21 @@ it.each(["failed", "cancelled", "completed"] as const)("does not borrow previous expect(frames[0].usage).toEqual(usage(1)); expect(frames[1].usage).toBeUndefined(); }); + + +it.each([false, true])("shows the active system graph immediately after compaction (persisted=%s)", (persisted) => { + const transcript = new ThreadTranscript(); + const oldGraph = { nodes: [{ path: "/before.py", name: "before.py", state: "loaded" as const, tokens: 50 }], edges: [] }; + const systemGraph = { nodes: [{ path: "/SOUL.md", name: "SOUL.md", state: "loaded" as const, tokens: 40 }], edges: [] }; + project(transcript, request(1, { request_id: "active", context_graph: oldGraph }), persisted); + const event = parseWebuiThreadPayload({ schemaVersion: 3, projection: "events", events: [{ ...envelope, + event: "context_compaction", compaction_id: "boundary", phase: "succeeded", turn_seq: 2, context_graph: systemGraph, + }] }).events[0]; + project(transcript, event, persisted); + expect(composerContextSnapshots(transcript.messages, transcript.modelRequests)).toEqual([ + { id: "compaction-boundary", graph: systemGraph }, + ]); + project(transcript, request(3, { request_id: "active", phase: "completed", context_graph: systemGraph }), persisted); + expect(composerContextSnapshots(transcript.messages, transcript.modelRequests).map((snapshot) => snapshot.graph)) + .toEqual([systemGraph, systemGraph]); +}); diff --git a/webui/src/tests/reload-cache.test.ts b/webui/src/tests/reload-cache.test.ts index 4f0286cd4..f2b7f0637 100644 --- a/webui/src/tests/reload-cache.test.ts +++ b/webui/src/tests/reload-cache.test.ts @@ -43,6 +43,7 @@ describe("tab reload cache", () => { const body = parseWebuiThreadPayload({ schemaVersion: 3, sessionKey: "websocket:growing", revision: "growing-50", projection: "events", active_turn_id: null, page: { before_cursor: "older", has_more_before: true }, events: [{ event: "context_compaction", chat_id: "growing", compaction_id: "checkpoint", phase: "succeeded", + ...(format === "inline" ? { context_graph: structuredClone(graphs[0]) } : { context_graph_ref: "0" }), context_snapshot: { estimated_tokens: 100, context_window_tokens: 100000, ...(format === "inline" ? { graph: structuredClone(graphs[0]) } : { graph_ref: "0" }) } }, ...events], ...(format === "references" ? { context_graphs: table, context_graph_nodes: nodes, context_graph_edges: edges } : {}),