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

+59 -30
View File
@@ -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
+4 -5
View File
@@ -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)
+31 -18
View File
@@ -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
+7 -2
View File
@@ -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,
+2
View File
@@ -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")