feat(webui): inspect file context in a live graph sidebar (#6562)

* feat(webui): inspect file context in a live graph sidebar

* refactor(webui): place preview controls in the shared sidebar header

* fix(webui): synchronize npm lockfile for graph dependencies

* fix(webui): preserve compacted context and refine graph inspection

* fix(context): harden provenance, request usage, and drawer lifecycle

* fix(webui): align source skeleton and browser fixtures

* perf(context): reuse source analysis and capture request graphs once

* perf(webui): compact graph history and render graph motion on canvas

* fix(webui): remove redundant context sidebar header

* style(webui): clarify context replay icon

* perf(webui): pace context replay on an adaptive timeline

* feat(webui): briefly reveal labels for new context nodes

* fix(webui): reveal new labels only for loaded context files

* fix(webui): restart graph animation clock after idle

* fix(webui): reveal labels when replay reverses node exit

* refactor(context): project file-use facts without retention tracking

* refactor(context): observe file reads outside agent execution

* fix(webui): animate context sidebar closing

* refactor(context): remove unused graph and usage panel code

* refactor(context): isolate prompt observation from execution metadata

* fix(webui): clarify cache rate and show context token usage

* fix(webui): abbreviate context token counts in thousands

* fix(webui): omit token unit from context usage details

* fix(webui): restore large source preview highlighting and panel elevation

* fix(webui): distinguish modifier scrolling from keyboard focus

* fix(webui): align preview tab and panel corner radii

* fix(webui): attach file tabs to the header divider

* fix(webui): use one action to toggle file preview mode

* fix(webui): use hover hint for context replay

* fix(webui): share composer layout between graph and file sidebars

* fix(webui): align sidebar bottom with composer surface

* fix(webui): restore mobile graph drawing and touch file details

* test(webui): align legacy cache assertions with current label

* perf(context): retain source analysis and bound graph animation work

* style(webui): add light elevation to user messages

* test(webui): await lazy graph scene before replay assertions

* fix(webui): align preview skeleton and browser contracts
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-05 17:09:20 +08:00
1 parent 2b44088413
commit 519ed81132
132 files changed
+4673 -1159

No files matched your search

+2 -1
View File
@@ -26,6 +26,7 @@ UPDATE_RETRY_CAPABILITY = "webui.update-jobs.retry-handoff.v1"
UPDATE_SETTLE_HANDOFF_CAPABILITY = "webui.update-jobs.settle-handoff.v1"
UPDATE_FLOW_CAPABILITY = "webui.update-flow.v1"
UPDATE_CHANNEL_CAPABILITY = "webui.update-channels.v1"
CONTEXT_GRAPH_REFERENCES_CAPABILITY = "webui.context-graph.references.v1"
PROMPT_NAVIGATION_CAPABILITY = "webui.prompt-navigation.v1"
@@ -46,7 +47,7 @@ def webui_contract() -> dict[str, object]:
BINARY_ATTACHMENTS_CAPABILITY, UPDATE_PLAN_CAPABILITY,
UPDATE_JOB_CAPABILITY, UPDATE_PREPARATION_CAPABILITY, UPDATE_EXECUTION_CAPABILITY,
UPDATE_RETRY_CAPABILITY, UPDATE_SETTLE_HANDOFF_CAPABILITY, UPDATE_FLOW_CAPABILITY, UPDATE_CHANNEL_CAPABILITY,
PROMPT_NAVIGATION_CAPABILITY,
PROMPT_NAVIGATION_CAPABILITY, CONTEXT_GRAPH_REFERENCES_CAPABILITY,
],
}
+179
View File
@@ -0,0 +1,179 @@
"""Observe completed reads on the ordered display stream, outside agent execution."""
from __future__ import annotations
import asyncio
import re
from collections.abc import Mapping
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, cast
from loguru import logger
from nanobot.context_graph import ContextGraph, ContextNode, graph_from_sources
from nanobot.context_sources import PromptSource, SourceReceipt, parse_source_receipt
from nanobot.file_references import source_receipt
from nanobot.session.display_history import (
HISTORY_GENERATION_METADATA_KEY,
HistoryKind,
HistoryReader,
)
from nanobot.session.history_graph import decode_graph
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":
return None
arguments, result = event.get("arguments"), event.get("result")
if not isinstance(arguments, dict) or not isinstance(result, str):
return None
path = cast(dict[str, object], arguments).get("path")
if not isinstance(path, str) or not path:
return None
file = Path(path).expanduser()
if not file.is_absolute():
directory = event.get("working_directory")
if not isinstance(directory, str) or not Path(directory).is_absolute():
return None
file = Path(directory) / file
# ReadFileTool uses numbered lines even for a clipped first line. Its notices
# and unchanged-file response have no such prefix and must not count twice.
lines: list[str] = []
for line in result.splitlines():
match = re.match(r"^\d+\| ?(.*)$", line)
if match is None:
break
lines.append(match.group(1))
if not lines:
return None
return source_receipt(file, "\n".join(lines))
@dataclass
class _State:
graph: ContextGraph = field(default_factory=lambda: {"nodes": [], "edges": []})
calls: set[tuple[str | None, str]] = field(default_factory=set)
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.calls.add((turn_id, call_id))
def _restore(history: HistoryReader, generation: str | None) -> _State:
state = _State()
revision = history.revision
if revision is None or generation != revision[0]:
return state
pending: list[tuple[Mapping[str, Any], str | None]] = []
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:
state.graph = graph
for event, turn_id in reversed(pending):
state.apply(event, turn_id)
return state
events = fact.content.get("tool_events")
if not isinstance(events, list):
continue
for event in reversed(cast(list[object], events)):
if isinstance(event, dict) and "context_source" in event:
pending.append((cast(dict[str, Any], event), fact.turn_id))
for event, turn_id in reversed(pending):
state.apply(event, turn_id)
return state
class ContextGraphObserver:
"""Display delivery serializes each chat; other chats have independent state."""
def __init__(self, sessions: SessionManager | None) -> None:
self._sessions = sessions
self._states: dict[tuple[str, str | None], _State] = {}
def discard(self, chat_id: str) -> None:
for key in tuple(self._states):
if key[0] == chat_id:
del self._states[key]
async def _state(self, chat_id: str, metadata: Mapping[str, Any], *, persistent: bool) -> _State:
raw_generation = metadata.get(HISTORY_GENERATION_METADATA_KEY)
generation = raw_generation if isinstance(raw_generation, str) else None
key = (chat_id, generation)
if key not in self._states:
self.discard(chat_id)
state = await self._sessions.state.project_history(
webui_session_key(chat_id), lambda history: _restore(history, generation),
) if persistent and self._sessions is not None else _State()
self._states[key] = state
return self._states[key]
async def observe_tools(
self, chat_id: str, events: list[dict[str, Any]], metadata: Mapping[str, Any], *, persistent: bool,
) -> None:
for event in events:
if event.get("name") != "read_file" or event.get("phase") != "end":
continue
try:
source = await asyncio.to_thread(read_source, event)
if source is not None:
state = await self._state(chat_id, metadata, persistent=persistent)
event["context_source"] = source
turn_id = metadata.get(WEBUI_TURN_METADATA_KEY)
state.apply(event, turn_id if isinstance(turn_id, str) else None)
except Exception:
# A presentation parser failure must not lose the tool result.
logger.exception("Unable to observe file read for context graph")
async def observe_prompt(
self, chat_id: str, sources: tuple[PromptSource, ...], metadata: Mapping[str, Any], *, persistent: bool,
) -> None:
if not sources:
return
def project() -> ContextGraph:
receipts = [source_receipt(source.path, source.content, loaded=source.loaded) for source in sources]
return graph_from_sources(receipts)
try:
graph = await asyncio.to_thread(project)
state = await self._state(chat_id, metadata, persistent=persistent)
state.graph = merge_graph(state.graph, graph)
except Exception:
logger.exception("Unable to observe prompt sources for context graph")
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
async def reset(self, chat_id: str, metadata: Mapping[str, Any], *, persistent: bool) -> None:
state = await self._state(chat_id, metadata, persistent=persistent)
state.graph = {"nodes": [], "edges": []}
state.calls.clear()
+32
View File
@@ -0,0 +1,32 @@
"""Turn-scoped prompt observation installed by WebUI runtime composition."""
from __future__ import annotations
from nanobot.agent.hook import AgentHook, AgentRunHookContext, AgentTurnHookContext
from nanobot.context_sources import PromptSourcesEvent, capture_sources
from nanobot.events import EventSink
class ContextSourceHook(AgentHook):
def __init__(self, events: EventSink) -> None:
super().__init__()
self._events = events
self._capture = capture_sources()
self._sources = self._capture.__enter__()
def has_run_hooks(self) -> bool:
# Cleanup owns no transcript; avoid copying all messages for this observer.
return False
async def before_model_request(self) -> None:
sources = tuple(self._sources)
self._sources.clear()
if sources:
await self._events.emit(PromptSourcesEvent(sources))
async def on_finally(self, context: AgentRunHookContext) -> None:
self._sources.clear()
self._capture.__exit__(None, None, None)
def create_context_source_hook(context: AgentTurnHookContext) -> AgentHook | None:
return ContextSourceHook(context.events) if context.events.accepts(PromptSourcesEvent) else None
+5 -4
View File
@@ -5,6 +5,7 @@ from typing import Any
from nanobot.bus.events import INBOUND_META_LOCAL_MEDIA
from nanobot.session.display_history import HistoryFact, HistoryKind, HistoryReader
from nanobot.session.history_graph import expand_graph_fields
from nanobot.webui.session_identity import webui_chat_id
_EVENTS = {
@@ -31,7 +32,7 @@ _CONTENT_FIELDS = frozenset({
"merge_next", "latency_ms", "usage", "round_usages", "context_window_tokens", "goal_state",
"outcome", "failure_kind", "failure_error_kind", "failure_attempts", "failure_message",
"transcript_incomplete", "stream_id", "compaction_id", "phase", "reason", "render_as",
"request_id", "run_id", "sequence",
"request_usage", "request_id", "run_id", "sequence", "context_graph", "context_snapshot",
})
@@ -63,14 +64,14 @@ def fact_from_record(record: Mapping[str, Any]) -> HistoryFact:
return fact
def record_from_fact(fact: HistoryFact, key: str) -> dict[str, Any]:
def record_from_fact(fact: HistoryFact, key: str, *, expand_graphs: bool = True) -> dict[str, Any]:
if fact.kind in _MESSAGE_KINDS.values():
event = "message"
message_kind = next(name for name, kind in _MESSAGE_KINDS.items() if kind is fact.kind)
else:
event = next(name for name, kind in _EVENTS.items() if kind is fact.kind)
message_kind = None
record = {"event": event, "chat_id": webui_chat_id(key), **fact.content,
record = {"event": event, "chat_id": webui_chat_id(key), **(expand_graph_fields(fact.content) if expand_graphs else fact.content),
"created_at_ms": fact.created_at_ms}
if message_kind:
record["kind"] = message_kind
@@ -86,6 +87,6 @@ def record_from_fact(fact: HistoryFact, key: str) -> dict[str, Any]:
def turn_records(
history: HistoryReader, ordinal: int, *, max_records: int | None = None, max_bytes: int | None = None,
) -> list[dict[str, Any]]:
return [{**record_from_fact(fact, history.key),
return [{**record_from_fact(fact, history.key, expand_graphs=False),
"_webui_replay_identity": f"turn:{ordinal}:record:{position}"}
for position, fact in history.read_entries(ordinal, max_records=max_records, max_bytes=max_bytes)]
+54 -9
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import asyncio
import json
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
@@ -24,6 +25,8 @@ 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_sources import PromptSourcesEvent
from nanobot.events import ModelRequestEvent
from nanobot.pairing.events import PairingChanged
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
@@ -32,6 +35,7 @@ from nanobot.session.webui_turns import (
mark_websocket_turn_transcript_persistence_failed,
websocket_turn_transcript_persistence_failed,
)
from nanobot.webui.context_observer import ContextGraphObserver
from nanobot.webui.media_gateway import WebUIMediaGateway
from nanobot.webui.metadata import (
WEBSOCKET_TURN_OWNER_METADATA_KEY,
@@ -44,6 +48,7 @@ from nanobot.webui.outbound_wire import (
GoalStateWirePayload,
GoalStatusWirePayload,
MessageWirePayload,
NotificationProjection,
RuntimeModelWirePayload,
SessionUpdatedWirePayload,
StreamWirePayload,
@@ -73,6 +78,12 @@ WebUIAudience: TypeAlias = ChatAudience | Literal["all_connections", "authentica
_ACTIVITY_BATCH_BYTES = 128 * 1024
async def _encode_payload(payload: Mapping[str, object]) -> str:
if "context_graph" in payload or "context_snapshot" in payload:
return await asyncio.to_thread(json.dumps, payload, ensure_ascii=False)
return json.dumps(payload, ensure_ascii=False)
class WebUIOutboundTransport(Protocol):
"""Snapshot recipients and enqueue already projected public JSON frames."""
@@ -100,17 +111,39 @@ class WebUIOutboundDelivery:
self._transcripts = transcripts
self._temporary_chats = temporary_chats
self._session_projection = session_projection
self._context_graph = ContextGraphObserver(transcripts.sessions)
self._stream_text_buffers: dict[tuple[str, str], list[str]] = {}
self._reasoning_text_buffers: dict[tuple[str, str], list[str]] = {}
async def _project_notification(self, msg: OutboundMessage) -> NotificationProjection | None:
event = msg.event
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)
def bind_pairing(self, bus: MessageBus, *, channel: str) -> Callable[[], None]:
async def queue_changed(event: PairingChanged) -> None:
await bus.publish_event(event, channel=channel, chat_id="*")
return bus.subscribe(queue_changed, PairingChanged)
def discard(self, chat_id: str) -> None:
def discard(self, chat_id: str, *, complete: bool = False) -> None:
"""Forget unclosed streams when a turn ends or its chat is discarded."""
if not complete or self._temporary_chats.should_persist_transcript(chat_id):
self._context_graph.discard(chat_id)
for buffers in (self._stream_text_buffers, self._reasoning_text_buffers):
for key in tuple(buffers):
if key[0] == chat_id:
@@ -134,7 +167,9 @@ class WebUIOutboundDelivery:
*,
label: str,
) -> None:
raw = json.dumps(payload, ensure_ascii=False)
if not recipients:
return
raw = await _encode_payload(payload)
for connection in recipients:
await self._transport.webui_send_raw(connection, raw, label=label)
@@ -182,10 +217,10 @@ class WebUIOutboundDelivery:
for msg in messages:
progress = msg.event if isinstance(msg.event, ProgressEvent) else None
if progress is not None:
body = self._message_payload(msg, progress)
body = await self._message_payload(msg, progress)
persistent, label = True, " "
else:
notification = project_notification(msg.chat_id, msg.event, msg.metadata)
notification = await self._project_notification(msg)
assert notification is not None
body = dict(notification.payload)
persistent = notification.persistence == "turn_activity"
@@ -195,7 +230,7 @@ class WebUIOutboundDelivery:
msg.chat_id, body, metadata=msg.metadata, phase="activity", include_source=progress is not None,
)
try:
raw = json.dumps(body, ensure_ascii=False)
raw = await _encode_payload(body)
size = len(raw.encode("utf-8"))
except (TypeError, ValueError, RecursionError) as exc:
logger.warning("WebUI activity encoding failed for {}: {}", msg.chat_id, exc)
@@ -212,6 +247,12 @@ class WebUIOutboundDelivery:
async def send(self, msg: OutboundMessage) -> None:
event = msg.event
if isinstance(event, PromptSourcesEvent):
await self._context_graph.observe_prompt(
msg.chat_id, event.sources, msg.metadata,
persistent=self._temporary_chats.should_persist_transcript(msg.chat_id),
)
return
if isinstance(event, PairingChanged):
await self._fanout(
self._transport.webui_recipients("authenticated_webui"),
@@ -248,7 +289,7 @@ class WebUIOutboundDelivery:
body["provenance"] = event.provenance
await self._fanout(recipients, body, label=" user_message ")
return
notification = project_notification(msg.chat_id, event, msg.metadata)
notification = await self._project_notification(msg)
if notification is not None:
if recipients or notification.deliver_offline:
await self._send_payload(
@@ -373,7 +414,7 @@ class WebUIOutboundDelivery:
chat_id, persisted=persisted, metadata=metadata, phase=phase,
)
def _message_payload(self, msg: OutboundMessage, progress: ProgressEvent | None) -> dict[str, Any]:
async def _message_payload(self, msg: OutboundMessage, progress: ProgressEvent | None) -> dict[str, Any]:
text = msg.content
user_shell = msg.metadata.get(INBOUND_META_USER_SHELL) is True
payload: MessageWirePayload = {
@@ -401,6 +442,10 @@ class WebUIOutboundDelivery:
payload["latency_ms"] = int(latency)
if progress and progress.tool_events:
payload["tool_events"] = project_tool_events(progress.tool_events)
await self._context_graph.observe_tools(
msg.chat_id, payload["tool_events"], msg.metadata,
persistent=self._temporary_chats.should_persist_transcript(msg.chat_id),
)
agent_ui = msg.metadata.get(OUTBOUND_META_AGENT_UI)
if agent_ui is not None:
payload["agent_ui"] = agent_ui
@@ -410,7 +455,7 @@ class WebUIOutboundDelivery:
async def _send_message(self, msg: OutboundMessage, progress: ProgressEvent | None) -> None:
recipients = self._transport.webui_recipients(ChatAudience(msg.chat_id))
body = self._message_payload(msg, progress)
body = await self._message_payload(msg, progress)
await self._persist_turn_transcript_event(
msg.chat_id, body, metadata=msg.metadata,
phase="activity" if progress else "answer", include_source=True,
@@ -528,7 +573,7 @@ class WebUIOutboundDelivery:
if persisted:
# A durable incomplete marker allows HTTP recovery after restart.
clear_websocket_turn_if_current(chat_id, turn_owner)
self.discard(chat_id)
self.discard(chat_id, complete=True)
await self._fanout(recipients, body, label=f" {body['event']} ")
async def _send_goal_state(self, chat_id: str, blob: dict[str, Any]) -> None:
+8
View File
@@ -11,6 +11,7 @@ from nanobot.bus.outbound_events import (
RetryStatusEvent,
TurnEndEvent,
)
from nanobot.context_graph import ContextGraph, ContextSnapshot
from nanobot.events import AgentEvent, CompactionReason, ModelRequestEvent
from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY
@@ -97,6 +98,8 @@ class TurnEndWirePayload(_ChatWirePayload):
class ModelRequestWirePayload(_ChatWirePayload):
request_usage: dict[str, int] | None
context_graph: NotRequired[ContextGraph]
event: Literal["model_request"]
request_id: str
run_id: str
@@ -108,6 +111,7 @@ class ModelRequestWirePayload(_ChatWirePayload):
class ContextCompactionWirePayload(_ChatWirePayload):
context_snapshot: NotRequired[ContextSnapshot]
event: Literal["context_compaction"]
compaction_id: str
phase: Literal["started", "succeeded", "failed", "cancelled"]
@@ -253,6 +257,7 @@ class NotificationProjection:
def project_notification(
chat_id: str, event: AgentEvent | None, metadata: Mapping[str, object] | None = None,
*, context_graph: ContextGraph | None = None,
) -> NotificationProjection | None:
"""Keep notification serialization and persistence decisions at one boundary."""
if isinstance(event, ModelRequestEvent):
@@ -260,7 +265,10 @@ def project_notification(
"event": "model_request", "chat_id": chat_id,
"request_id": event.request_id, "run_id": event.run_id,
"sequence": event.sequence, "phase": event.phase,
"request_usage": event.request_usage.to_turn_dict() if event.request_usage is not None else None,
}
if context_graph is not None:
payload["context_graph"] = context_graph
if event.usage is not None:
payload["usage"] = event.usage.to_turn_dict()
payload["round_usages"] = [usage.to_turn_dict() for usage in event.round_usages[-8:]]
+20 -6
View File
@@ -28,6 +28,12 @@ from nanobot.session.display_history import (
HistoryFact,
HistoryReader,
)
from nanobot.session.history_graph import (
decode_graph,
decode_snapshot,
graph_decoding,
graph_size_adjustment,
)
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import Session, SessionManager
from nanobot.session.sqlite_store import SessionConflictError
@@ -233,7 +239,7 @@ def _record_json_line(record: dict[str, Any]) -> str:
def _records_bytes(records: list[dict[str, Any]]) -> int:
total = 0
for record in records:
total += len(_record_json_line(record).encode("utf-8")) + 1
total += len(_record_json_line(record).encode("utf-8")) + graph_size_adjustment(record) + 1
return total
@@ -581,9 +587,6 @@ class WebUITranscriptRecorder:
for event in events:
try:
fact = fact_from_record(_record_for_append(event))
if len(events) > 1:
# An invalid member must not roll back otherwise valid activity.
fact.encode()
facts.append(fact)
except (ValueError, TypeError) as exc:
self._log.warning("history append failed for {}: {}", chat_id, exc)
@@ -591,8 +594,12 @@ class WebUITranscriptRecorder:
if not facts:
return False
try:
await self.sessions.state.append_history(webui_session_key(chat_id), facts,
expected_generation=generation)
errors = await self.sessions.state.append_history(webui_session_key(chat_id), facts,
expected_generation=generation,
skip_invalid=len(events) > 1)
for error in errors:
self._log.warning("history append failed for {}: {}", chat_id, error)
valid = valid and not errors
except (OSError, ValueError, TypeError, sqlite3.Error, SessionConflictError, SessionOperationQueueFullError) as exc:
self._log.warning("history append failed for {}: {}", chat_id, exc)
return False
@@ -1510,6 +1517,8 @@ def _client_projection_event(
"compaction_id": compaction_id,
"phase": phase,
}
if (snapshot := decode_snapshot(record.get("context_snapshot"))) is not None:
projected["context_snapshot"] = snapshot
reason = record.get("reason")
if isinstance(reason, str) and reason in {"idle", "context_pressure", "manual", "provider_native"}:
projected["reason"] = reason
@@ -1528,6 +1537,10 @@ def _client_projection_event(
):
return None
projected.update(request_id=request_id, run_id=run_id, sequence=sequence, phase=phase)
if "request_usage" in record:
projected["request_usage"] = _sanitize_turn_usage(record["request_usage"]) or None
if (graph := decode_graph(record.get("context_graph"))) is not None:
projected["context_graph"] = graph
latency_ms = record.get("latency_ms")
if isinstance(latency_ms, int | float) and latency_ms >= 0:
projected["latency_ms"] = int(latency_ms)
@@ -1757,6 +1770,7 @@ def build_session_thread_response(
"active_turn_id": turn_id if active else None}
@graph_decoding()
def build_webui_thread_response(
session_key: str,
*,
+71 -13
View File
@@ -18,7 +18,7 @@ import time
from collections.abc import Awaitable, Callable, Mapping
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Any, Protocol, cast
from typing import TYPE_CHECKING, Any, Protocol, TypeVar, cast
from urllib.parse import quote, unquote, urlsplit, urlunsplit
from loguru import logger
@@ -29,6 +29,7 @@ from websockets.http11 import Response
from nanobot.agent.subagent import SubagentControlError
from nanobot.agent.subagent_status import SubagentSessionError
from nanobot.command.application import builtin_command_palette
from nanobot.context_graph import ContextGraph
from nanobot.cron.binding import CronBindingError, binding_revision
from nanobot.cron.session_turns import is_bound_cron_job
from nanobot.cron.types import CronJob, CronSchedule
@@ -348,8 +349,58 @@ def _resolve_bootstrap_model_name(
return _default_model_name_from_config(config_path) or ""
class _HistoryProjection(Protocol):
def __call__(self, request: WsRequest, key: str, *, history: HistoryReader) -> Response: ...
_ProjectionResult = TypeVar("_ProjectionResult", covariant=True)
class _HistoryProjection(Protocol[_ProjectionResult]):
def __call__(self, request: WsRequest, key: str, *, history: HistoryReader) -> _ProjectionResult: ...
@dataclass
class _PreparedThreadResponse:
data: dict[str, Any]
headers: list[tuple[str, str]]
def _encode_thread_response(data: dict[str, Any], *, graph_references: bool, **kwargs: Any) -> Response:
if graph_references:
graphs: dict[str, object] = {}
references: dict[int, tuple[str, ContextGraph]] = {}
nodes: list[object] = []
edges: list[object] = []
node_ids: dict[int, int] = {}
edge_ids: dict[int, int] = {}
def index(value: object, values: list[object], ids: dict[int, int]) -> int:
identity = id(value)
if identity not in ids:
ids[identity] = len(values)
values.append(value)
return ids[identity]
def reference(graph: ContextGraph) -> str:
identity = id(graph)
if identity not in references:
key = str(len(graphs))
references[identity] = (key, graph)
graphs[key] = {
"nodes": [index(node, nodes, node_ids) for node in graph["nodes"]],
"edges": [index(edge, edges, edge_ids) for edge in graph["edges"]],
}
return references[identity][0]
for event in data.get("events", []):
if "context_graph" in event:
event["context_graph_ref"] = reference(event.pop("context_graph"))
snapshot = event.get("context_snapshot")
if isinstance(snapshot, dict) and "graph" in snapshot:
snapshot = cast(dict[str, Any], snapshot)
event["context_snapshot"] = {**snapshot, "graph_ref": reference(snapshot["graph"])}
event["context_snapshot"].pop("graph")
data["context_graphs"] = graphs
data["context_graph_nodes"] = nodes
data["context_graph_edges"] = edges
return _http_json_response(data, **kwargs)
class GatewayHTTPHandler:
@@ -1048,8 +1099,8 @@ class GatewayHTTPHandler:
return self.session_manager.read_session_version(key) if self.session_manager is not None else None
async def _project_session_history(
self, request: WsRequest, key: str, project: _HistoryProjection,
) -> Response:
self, request: WsRequest, key: str, project: _HistoryProjection[_ProjectionResult],
) -> _ProjectionResult | Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
decoded = _decode_api_key(key)
@@ -1111,11 +1162,20 @@ class GatewayHTTPHandler:
timer = loop.call_later(0.05, sample_event_loop_lag)
started = time.perf_counter()
def project(request: WsRequest, key: str, *, history: HistoryReader) -> Response:
def project(request: WsRequest, key: str, *, history: HistoryReader) -> Response | _PreparedThreadResponse:
return self._handle_webui_thread_get(request, key, history=history, diagnostics=diagnostics)
try:
response = await self._project_session_history(request, key, project)
prepared = await self._project_session_history(request, key, project)
if isinstance(prepared, _PreparedThreadResponse):
response = await asyncio.to_thread(
_encode_thread_response, prepared.data,
graph_references=_query_first(_parse_query(request.path), "context_graph_encoding") == "references-v1",
accept_encoding=_combined_list_header(request.headers, "Accept-Encoding"),
extra_headers=prepared.headers, metrics=diagnostics.response,
)
else:
response = prepared
finally:
active = False
timer.cancel()
@@ -1170,7 +1230,7 @@ class GatewayHTTPHandler:
*,
history: HistoryReader,
diagnostics: _WebUIThreadDiagnostics | None = None,
) -> Response:
) -> Response | _PreparedThreadResponse:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
decoded_key = _decode_api_key(key)
@@ -1215,6 +1275,7 @@ class GatewayHTTPHandler:
include_model_requests = _query_first(query, "include_model_requests") == "1"
revision_variant = {
"include_model_requests": include_model_requests,
"context_graph_encoding": _query_first(query, "context_graph_encoding"),
"active_turn_id": active_turn_id,
"active_turn_started_at": active_turn_started_at,
"active_turn_transcript_persistence_failed": (
@@ -1267,11 +1328,8 @@ class GatewayHTTPHandler:
if final_revision is not None and final_revision == initial_revision:
response_headers.append(("ETag", _quoted_etag(final_revision)))
data["revision"] = final_revision
return _http_json_response(
data,
accept_encoding=_combined_list_header(request.headers, "Accept-Encoding"),
extra_headers=response_headers,
metrics=diagnostics.response if diagnostics is not None else None,
return _PreparedThreadResponse(
data=data, headers=response_headers,
)
def _handle_webui_trace_detail_get(self, request: WsRequest, key: str, *, history: HistoryReader) -> Response: