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

+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: