Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
feat(webui): inspect file context in a live graph sidebar (#6562)
chengyongru519ed81132c3
diff --git a/docs/webui.md b/docs/webui.mdindex ee2ad8eca..6c9a86b2d 100644--- a/docs/webui.md+++ b/docs/webui.md@@ -111,6 +111,8 @@ Tasks in persistent topics can continue while the connection is lost. Status andThe context indicator beside the model badge shows context-window usage. **Recent rounds** includes token usage, generation time and KV cache hits when reported. Provider figures may be estimated or unavailable and are not a billing statement.+Open the file graph to see files used since the latest compaction and local Markdown references discovered in those files. Click a node to see its estimated token count or open the file, and drag across the usage bar or use replay to review earlier rounds. A loaded node means the file was read or supplied during this phase; it does not guarantee that the whole file, or its original text, remains in the model's current request. Compaction starts a new replay phase; its graph appears with the next request. Previously saved snapshots remain readable, but missing historical snapshots are not reconstructed from current files.+During compaction, the model switches to a summary plus subsequent messages; the original messages remain in chat history. Use `/compact` to compact the current topic manually. See [Memory](./memory.md) for compaction and Dream consolidation.### File and diagram previewsdiff --git a/nanobot/agent/context.py b/nanobot/agent/context.pyindex d1102e06e..dcb480423 100644--- a/nanobot/agent/context.py+++ b/nanobot/agent/context.py@@ -10,6 +10,7 @@ from nanobot.agent.skills import SkillsLoaderfrom nanobot.agent.tools import mcp as mcp_toolsfrom nanobot.agent.tools import sessions as session_toolsfrom nanobot.apps.cli import utils as cli_app_utils+from nanobot.context_sources import record_sourcefrom nanobot.runtime_context import (RUNTIME_CONTEXT_MESSAGE_META,RuntimeContextBlock,@@ -98,7 +99,7 @@ class ContextBuilder:if bootstrap:parts.append(bootstrap)- parts.append(render_template("agent/tool_contract.md"))+ parts.append(render_template("agent/tool_contract.md", track_source=True))project_path = root.expanduser().resolve()if project_path != self.workspace.expanduser().resolve():@@ -112,6 +113,9 @@ class ContextBuilder:memory = self.memory.read_memory()if memory and not self._is_template_content(memory, "memory/MEMORY.md"):parts.append(memory)+ record_source(self.memory.memory_file, memory)+ elif self.memory.memory_file.is_file():+ record_source(self.memory.memory_file, "", loaded=False)with self.skills.snapshot():active_skills = self.skills.get_always_skills()@@ -125,7 +129,7 @@ class ContextBuilder:workspace=root,)if skills_summary:- parts.append(render_template("agent/skills_section.md", skills_summary=skills_summary))+ parts.append(render_template("agent/skills_section.md", skills_summary=skills_summary, track_source=True))if session_summary and session_summary["text"] != "(nothing)":parts.append(@@ -145,6 +149,7 @@ class ContextBuilder:return render_template("agent/identity.md",+ track_source=True,workspace_path=workspace_path,agent_workspace_path=agent_workspace_path,runtime=runtime,@@ -194,12 +199,15 @@ class ContextBuilder:):content = load_bundled_template("SOUL.md") or contentif not content.strip():+ record_source(file_path, "", loaded=False)continueif filename in self._SKIPPABLE_DEFAULTS and self._is_template_content(content, filename):+ record_source(file_path, "", loaded=False)continueparts.append(f"## {filename}\n\n{content}")+ record_source(file_path, content)return "\n\n".join(parts) if parts else ""diff --git a/nanobot/agent/hook.py b/nanobot/agent/hook.pyindex 69f398e99..232c88408 100644--- a/nanobot/agent/hook.py+++ b/nanobot/agent/hook.py@@ -92,6 +92,10 @@ class AgentHook:async def on_finally(self, context: AgentRunHookContext) -> None:pass+ async def before_model_request(self) -> None:+ """Observe a prepared logical request, including recovery requests."""+ pass+async def before_iteration(self, context: AgentHookContext) -> None:pass@@ -207,6 +211,9 @@ class CompositeHook(AgentHook):"AgentHook.{} error in {}", method_name, type(h).__name__,)+ async def before_model_request(self) -> None:+ await self._for_each_hook_safe("before_model_request")+async def before_iteration(self, context: AgentHookContext) -> None:await self._for_each_hook_safe("before_iteration", context)diff --git a/nanobot/agent/progress_hook.py b/nanobot/agent/progress_hook.pyindex ad2f4125a..e17000f9e 100644--- a/nanobot/agent/progress_hook.py+++ b/nanobot/agent/progress_hook.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+from pathlib import Pathfrom typing import Anyfrom loguru import logger@@ -8,6 +9,7 @@ from loguru import loggerfrom nanobot.agent.hook import AgentHook, AgentHookContextfrom nanobot.bus.outbound_events import ProgressEvent, StreamDeltaEvent, StreamEndEventfrom nanobot.events import NO_EVENTS, EventSink+from nanobot.security.workspace_access import current_tool_workspacefrom nanobot.utils.helpers import IncrementalThinkExtractor, strip_thinkfrom nanobot.utils.progress_events import (build_tool_event_finish_payloads,@@ -25,12 +27,15 @@ class AgentProgressHook(AgentHook):streaming: bool = False,session_key: str | None = None,log_content: bool = True,+ workspace: Path | None = None,) -> None:super().__init__(reraise=True)self._publish = events.publishself._streaming = streamingself._session_key = session_keyself._log_content = log_content+ self._workspace = workspace+ self._tool_workspaces: dict[str, str] = {}self._stream_buf = ""self._think_extractor = IncrementalThinkExtractor()self._reasoning_open = False@@ -150,10 +155,19 @@ class AgentProgressHook(AgentHook):async def on_tool_execution_event(self, context: AgentHookContext) -> None:if self._publish:finished = bool(context.tool_events)+ if not finished:+ directory = str(current_tool_workspace(self._workspace).project_path or Path.cwd())+ for call in context.tool_calls:+ self._tool_workspaces[call.id] = directorypayloads = (build_tool_event_finish_payloads(context) if finishedelse [build_tool_event_start_payload(tc) for tc in context.tool_calls])+ for payload in payloads:+ call_id = payload["call_id"]+ directory = self._tool_workspaces.pop(call_id, None) if finished else self._tool_workspaces.get(call_id)+ if directory is not None:+ payload["working_directory"] = directoryawait self._publish(ProgressEvent(tool_hint=not finished, tool_events=payloads))async def after_iteration(self, context: AgentHookContext) -> None:diff --git a/nanobot/agent/runner.py b/nanobot/agent/runner.pyindex d681f0d97..b0fd12071 100644--- a/nanobot/agent/runner.py+++ b/nanobot/agent/runner.py@@ -929,6 +929,7 @@ class AgentRunner:Callers reserve a live round slot; recovery invocations update it."""request_id = uuid4().hex+ request_usage: LLMUsage | None = Noneasync def emit(phase: Literal["started", "completed", "failed", "cancelled"]) -> None:state.request_sequence += 1@@ -940,9 +941,12 @@ class AgentRunner:usage=state.request_usage,round_usages=tuple(usage for usage in state.recent_round_usages if usage is not None),context_window_tokens=spec.runtime.context_window_tokens,+ request_usage=request_usage,))try:+ if spec.hook is not None:+ await spec.hook.before_model_request()await emit("started")_raise_if_cancelling()response = await spec.runtime.provider.chat_stream_with_retry(**kwargs)@@ -962,6 +966,7 @@ class AgentRunner:reported_usage = response.usage.with_timing(generation_ms=response.generation_ms, ttft_ms=response.ttft_ms,)+ request_usage = reported_usagestate.request_usage = self._merge_usage(state.request_usage, reported_usage)state.recent_round_usages[-1] = self._merge_usage(state.recent_round_usages[-1], reported_usage,diff --git a/nanobot/agent/skills.py b/nanobot/agent/skills.pyindex a9e93a238..23498fb2b 100644--- a/nanobot/agent/skills.py+++ b/nanobot/agent/skills.py@@ -21,6 +21,7 @@ from nanobot.agent.skill_metadata import (from nanobot.agent.skill_metadata import (valid_skill_metadata as valid_skill_metadata,)+from nanobot.context_sources import record_sourcefrom nanobot.runtime_context import RuntimeContextBlock_SKILL_REFERENCE = re.compile(r"(?<![\w$])\$([A-Za-z0-9_-]+)")@@ -166,7 +167,7 @@ class SkillsLoader:with self.snapshot():return self._load_skill(name)- def _load_skill(self, name: str) -> str | None:+ def _load_skill(self, name: str, *, for_context: bool = False) -> str | None:skills = self.list_skills(filter_unavailable=False)available = {skill["name"] for skill in skills}resolved = name if name in available else self._skill_aliases().get(name, name)@@ -175,10 +176,14 @@ class SkillsLoader:return Nonesnapshot = self._snapshot.get()if snapshot is not None and resolved in snapshot.documents:- return snapshot.documents[resolved]- content = Path(entry["path"]).read_text(encoding="utf-8")- if snapshot is not None:- snapshot.documents[resolved] = content+ content = snapshot.documents[resolved]+ else:+ content = Path(entry["path"]).read_text(encoding="utf-8")+ if snapshot is not None:+ snapshot.documents[resolved] = content+ if for_context:+ content = self._strip_frontmatter(content)+ record_source(Path(entry["path"]), content)return contentdef load_skills_for_context(self, skill_names: list[str]) -> str:@@ -191,11 +196,12 @@ class SkillsLoader:Returns:Formatted skills content."""- parts = [- f"### Skill: {name}\n\n{self._strip_frontmatter(markdown)}"- for name in skill_names- if (markdown := self.load_skill(name))- ]+ with self.snapshot():+ parts = [+ f"### Skill: {name}\n\n{content}"+ for name in skill_names+ if (content := self._load_skill(name, for_context=True))+ ]return "\n\n---\n\n".join(parts)def get_explicitly_invoked_skills(self, text: str) -> list[str]:@@ -297,6 +303,7 @@ class SkillsLoader:lines = [f"### {label} (`{display_root}`)"]for entry in entries:skill_name = entry["name"]+ record_source(Path(entry["path"]), "", loaded=False)desc = self.get_skill_description(skill_name)relative_path = Path(entry["path"]).relative_to(root).as_posix()lines.append(f"- **{skill_name}** — {desc} `{relative_path}`")diff --git a/nanobot/agent/turn_hooks.py b/nanobot/agent/turn_hooks.pyindex 60a5ba047..475f5f967 100644--- a/nanobot/agent/turn_hooks.py+++ b/nanobot/agent/turn_hooks.py@@ -46,6 +46,7 @@ def build_agent_turn_hook(spec: AgentTurnHookSpec) -> AgentHook:streaming=spec.streaming,session_key=spec.session_key,log_content=log_content,+ workspace=spec.workspace,)if spec.ephemeral and not spec.run_extra_hooks_for_ephemeral:return progress_hookdiff --git a/nanobot/bus/notification_delivery.py b/nanobot/bus/notification_delivery.pyindex 77cb62c14..cb63339fc 100644--- a/nanobot/bus/notification_delivery.py+++ b/nanobot/bus/notification_delivery.py@@ -7,6 +7,7 @@ from nanobot.bus.outbound_events import (StreamDeltaEvent,StreamEndEvent,)+from nanobot.context_sources import PromptSourcesEventfrom nanobot.events import (AgentEvent,ContextCompactionEvent,@@ -29,6 +30,7 @@ NOTIFICATION_AUDIENCES: dict[type[AgentEvent], NotificationAudience] = {RetryStatusEvent: "interactive",ResponseSourceEvent: "interactive",ModelRequestEvent: "interactive",+ PromptSourcesEvent: "interactive",}diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.pyindex 911387c4a..2ec1c0651 100644--- a/nanobot/channels/websocket/tests/test_websocket_channel.py+++ b/nanobot/channels/websocket/tests/test_websocket_channel.py@@ -3700,10 +3700,10 @@ async def test_durable_incomplete_marker_stays_pending_without_safe_session_recooriginal_append = history.sessions.state.append_history- async def fail_answer(session_key, facts, *, expected_generation):+ async def fail_answer(session_key, facts, *, expected_generation, skip_invalid=False):if any(fact.kind is HistoryKind.ANSWER for fact in facts):raise OSError("transient disk failure")- await original_append(session_key, facts, expected_generation=expected_generation)+ return await original_append(session_key, facts, expected_generation=expected_generation, skip_invalid=skip_invalid)monkeypatch.setattr(history.sessions.state, "append_history", fail_answer)@@ -3807,10 +3807,10 @@ async def test_http_replay_recovers_marked_answer_from_session_after_gateway_resoriginal_append = history.sessions.state.append_history- async def fail_answer(session_key, facts, *, expected_generation):+ async def fail_answer(session_key, facts, *, expected_generation, skip_invalid=False):if any(fact.kind is HistoryKind.ANSWER for fact in facts):raise OSError("transient disk failure")- await original_append(session_key, facts, expected_generation=expected_generation)+ return await original_append(session_key, facts, expected_generation=expected_generation, skip_invalid=skip_invalid)monkeypatch.setattr(history.sessions.state, "append_history", fail_answer)await channel.send(await history.message(@@ -7004,3 +7004,99 @@ async def test_history_model_request_opt_in_preserves_old_clients_cursors_and_etassert old_page["events"] == [event for event in modern_page["events"] if event["event"] != "model_request"]assert old_page["page"]["loaded_event_count"] == len(old_page["events"])assert modern_page["page"]["loaded_event_count"] == len(modern_page["events"])++[email protected]("state", ["missing", "present", "new_request"])+async def test_thread_replays_durable_compaction_boundaries(history, tmp_path, monkeypatch, state):+ from urllib.parse import quote++ from websockets.http11 import Request++ monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)+ key = "websocket:legacy-context"+ snapshot = {"graph": {"nodes": [], "edges": []}, "estimated_tokens": 100, "context_window_tokens": 1000}+ history.append(key, {"event": "user", "chat_id": "legacy-context", "text": "hello"})+ compact = {"event": "context_compaction", "compaction_id": "compact", "phase": "succeeded"}+ if state == "present":+ compact["context_snapshot"] = snapshot+ history.append(key, compact)+ if state == "new_request":+ history.append(key, {"event": "model_request", "request_id": "request", "run_id": "run", "sequence": 1, "phase": "started"})+ gateway = _basic_handler(MagicMock(), workspace_path=tmp_path, session_manager=history.sessions)+ gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0++ encoded = quote(key, safe="")+ path = f"/api/sessions/{encoded}/webui-thread?include_model_requests=1"+ request = Request(path, Headers([("Authorization", "Bearer tok")]))+ response = await gateway.http._handle_webui_thread_get_async(request, encoded)+ assert response.status_code == 200+ body = json.loads(response.body)+ event = next(event for event in body["events"] if event["event"] == "context_compaction")+ assert event["phase"] == "succeeded"+ assert event["compaction_id"] == "compact"+ if state == "present":+ assert event["context_snapshot"] == snapshot+ else:+ # Historical reads must not invent a snapshot from today's disk files.+ assert "context_snapshot" not in event+ cached_request = Request(path, Headers([("Authorization", "Bearer tok"), ("If-None-Match", response.headers["ETag"])]))+ cached = await gateway.http._handle_webui_thread_get_async(cached_request, encoded)+ assert cached.status_code == 304+++async def test_context_graph_dictionary_pages_are_self_contained_and_opt_in(history):+ from urllib.parse import quote++ from websockets.http11 import Request++ key = "websocket:graph-pages"+ graph = {"nodes": [{"path": "/guide.md", "name": "guide.md", "tokens": 10, "state": "loaded"}], "edges": []}+ for number in range(3):+ history.append(key, {"event": "user", "text": f"question {number}"})+ history.append(key, {"event": "model_request", "request_id": str(number), "run_id": str(number), "sequence": 2, "phase": "completed", "context_graph": graph, "request_usage": {"context_tokens": number + 10}})+ history.append(key, {"event": "context_compaction", "compaction_id": str(number), "phase": "succeeded", "context_snapshot": {"graph": graph, "estimated_tokens": 5, "context_window_tokens": 100}})+ history.append(key, {"event": "turn_end"})+ channel = _ch(MagicMock(), session_manager=history.sessions)+ channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300+ encoded = quote(key, safe="")++ async def fetch(before=None, compact=False, etag=None):+ query = "include_model_requests=1&limit=1"+ if before:+ query += "&before=" + quote(before, safe="")+ if compact:+ query += "&context_graph_encoding=references-v1"+ headers = [("Authorization", "Bearer tok")]+ if etag:+ headers.append(("If-None-Match", etag))+ return await channel.gateway.http._handle_webui_thread_get_async(Request(f"/api/sessions/{encoded}/webui-thread?{query}", Headers(headers)), encoded)++ before = None+ seen = []+ for _ in range(3):+ old_response = await fetch(before)+ compact_response = await fetch(before, compact=True, etag=old_response.headers["ETag"])+ assert compact_response.status_code == 200+ old = json.loads(old_response.body)+ compact = json.loads(compact_response.body)+ assert "context_graphs" not in old+ assert len(compact["context_graphs"]) == 1+ assert compact["context_graph_nodes"] == graph["nodes"]+ assert compact["context_graph_edges"] == graph["edges"]+ decoded_graphs = {key: {+ "nodes": [compact["context_graph_nodes"][index] for index in descriptor["nodes"]],+ "edges": [compact["context_graph_edges"][index] for index in descriptor["edges"]],+ } for key, descriptor in compact["context_graphs"].items()}+ for event in compact["events"]:+ if "context_graph_ref" in event:+ event["context_graph"] = decoded_graphs[event.pop("context_graph_ref")]+ seen.append(event["request_id"])+ if "context_snapshot" in event:+ snapshot = event["context_snapshot"]+ snapshot["graph"] = decoded_graphs[snapshot.pop("graph_ref")]+ assert compact["events"] == old["events"]+ assert compact["page"]["before_cursor"] == old["page"]["before_cursor"]+ before = compact["page"]["before_cursor"]+ assert seen == ["2", "1", "0"]diff --git a/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py b/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.pyindex 948661ef6..b2aee5c9c 100644--- a/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py+++ b/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py@@ -574,10 +574,18 @@ async def test_ready_activity_group_commits_before_ordered_fanout(history, monkeif index < 2:entered[index].set()await release[index].wait()- await append(key, facts, **kwargs)+ return await append(key, facts, **kwargs)monkeypatch.setattr(history.sessions.state, "append_history", gated_append)usage = LLMUsage.reported(input_tokens=100, output_tokens=20)+ from nanobot.context_graph import graph_from_sources+ from nanobot.context_sources import PromptSource, PromptSourcesEvent+ from nanobot.file_references import source_receipt+ source = PromptSource(tmp_path / "guide.md", "Guide content")+ graph = graph_from_sources([source_receipt(source.path, source.content)])+ await channel.send(OutboundMessage(+ "websocket", chat, "", metadata=metadata, event=PromptSourcesEvent((source,)),+ ))events = [ModelRequestEvent("request", "run", 1, "started"),RetryStatusEvent(state="cleared", attempt=1, max_attempts=None, error_kind="unknown"),@@ -612,12 +620,14 @@ async def test_ready_activity_group_commits_before_ordered_fanout(history, monke"model_request", "retry_status", "model_request", "message", "message", "message", "turn_end", "session_updated",]assert frames[2]["usage"] == usage.to_turn_dict()+ assert frames[0]["context_graph"] == frames[2]["context_graph"] == graphassert frames[4]["tool_events"][0]["result"] == "complete"assert [len(facts) for facts in writes] == [1, 4, 1, 1]durable = history.read(f"websocket:{chat}")assert [row["turn_seq"] for row in durable] == list(range(1, 8))assert durable[4]["tool_events"][0]["result"] == "complete"assert durable[-1]["event"] == "turn_end"+ assert all(row["context_graph"] == graph for row in durable if row["event"] == "model_request")late_frames = [json.loads(late.sent.get_nowait()) for _ in range(late.sent.qsize())]assert [frame["event"] for frame in late_frames] == ["message", "turn_end", "session_updated"]assert late_frames[0]["text"] == "answer"@@ -768,3 +778,51 @@ async def test_unencodable_tool_argument_does_not_discard_neighboring_activity(hassert [row["text"] for row in history.read(f"websocket:{chat}")] == ["first", "last"]finally:await channel.stop()++[email protected]("batched", [False, True])+async def test_context_observer_orders_reads_requests_and_compaction(history, tmp_path, batched):+ from nanobot.agent.tools.filesystem import ReadFileTool+ from nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEvent, TurnEndEvent+ from nanobot.events import ModelRequestEvent+ from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY++ (tmp_path / "guide.md").write_text("[Reference](reference.md)")+ result = await ReadFileTool(workspace=tmp_path).execute(path="guide.md")+ tool = {"name": "read_file", "call_id": "read", "phase": "end",+ "arguments": {"path": "guide.md"}, "result": result}+ channel = _channel(history.sessions)+ chat = "observed-context"++ async def message(event):+ return await history.message(channel="websocket", chat_id=chat, content="", event=event,+ metadata={WEBUI_TURN_METADATA_KEY: "turn"})++ events = [+ ModelRequestEvent("before", "run", 1, "started"),+ ProgressEvent(tool_events=[{**tool, "working_directory": str(tmp_path)}]),+ ModelRequestEvent("after", "run", 2, "started"),+ ]+ messages = [await message(event) for event in events]+ if batched:+ await channel.send_batch(messages)+ else:+ for msg in messages:+ await channel.send(msg)+ requests = [row for row in history.read(f"websocket:{chat}") if row["event"] == "model_request"]+ assert requests[0]["context_graph"] == {"nodes": [], "edges": []}+ graph = requests[-1]["context_graph"]+ assert [(node["name"], node["state"]) for node in graph["nodes"]] == [+ ("guide.md", "loaded"), ("reference.md", "discovered"),+ ]+ # End-of-turn cleanup and a fresh delivery service must recover display state.+ await channel.send(await message(TurnEndEvent()))+ channel = _channel(history.sessions)+ await channel.send(await message(ContextCompactionEvent("failed", "failed")))+ await channel.send(await message(ModelRequestEvent("restored", "run", 3, "started")))+ requests = [row for row in history.read(f"websocket:{chat}") if row["event"] == "model_request"]+ assert requests[-1]["context_graph"] == graph+ await channel.send(await message(ContextCompactionEvent("done", "succeeded")))+ 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": []}diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.pyindex 463b90951..01b280806 100644--- a/nanobot/cli/commands.py+++ b/nanobot/cli/commands.py@@ -65,6 +65,7 @@ from nanobot.utils.helpers import sanitize_surrogates as _sanitize_surrogates #from nanobot.utils.helpers import ( # noqa: E402sync_workspace_templates,)+from nanobot.webui.context_source_hook import create_context_source_hook # noqa: E402# Backward-compatible import for callers that used the former module location.SafeFileHistory = cli_terminal.SafeFileHistory@@ -388,7 +389,7 @@ def serve(runtime_config, bus,provider=unconfigured_provider,session_manager=session_manager,- hook_factories=[create_file_edit_activity_hook],+ hook_factories=[create_file_edit_activity_hook, create_context_source_hook],tool_registry=tools,builtin_assembly=install_goal,)diff --git a/nanobot/cli/gateway_runtime.py b/nanobot/cli/gateway_runtime.pyindex 813ad9967..3f23adf34 100644--- a/nanobot/cli/gateway_runtime.py+++ b/nanobot/cli/gateway_runtime.py@@ -55,6 +55,7 @@ from nanobot.utils.evaluator import evaluate_response, resolve_evaluator_promptfrom nanobot.utils.helpers import sync_workspace_templatesfrom nanobot.utils.token_encoding import warmup_token_encodingfrom nanobot.webui.build import BuildMode+from nanobot.webui.context_source_hook import create_context_source_hookfrom nanobot.webui.dev import WebUIDevError, WebUIDevServerfrom nanobot.webui.sidebar_state import ensure_webui_session_archives@@ -608,7 +609,7 @@ def _run_claimed_gateway(provider_signature=provider_snapshot.signature,local_trigger_store=trigger_store,hooks=[_MCPReadinessHook(mcp_provider)],- hook_factories=[create_file_edit_activity_hook],+ hook_factories=[create_file_edit_activity_hook, create_context_source_hook],tool_registry=tools,recovery_admission=recovery,builtin_assembly=install_goal,diff --git a/nanobot/context_graph.py b/nanobot/context_graph.pynew file mode 100644index 000000000..f337b681e--- /dev/null+++ b/nanobot/context_graph.py@@ -0,0 +1,85 @@+"""Client graph projection of file-use facts and persisted snapshot validation."""++from __future__ import annotations++from collections.abc import Sequence+from pathlib import Path+from typing import Literal, TypedDict, cast++from nanobot.context_sources import SourceReceipt+++class ContextNode(TypedDict):+ path: str+ name: str+ state: Literal["loaded", "discovered"]+ tokens: int+++class ContextEdge(TypedDict):+ source: str+ target: str+++class ContextGraph(TypedDict):+ nodes: list[ContextNode]+ edges: list[ContextEdge]+++def parse_context_graph(value: object) -> ContextGraph | None:+ """Validate persisted graph data at the transcript boundary."""+ if not isinstance(value, dict):+ return None+ value = cast(dict[str, object], value)+ raw_nodes, raw_edges = value.get("nodes"), value.get("edges")+ if not isinstance(raw_nodes, list) or not isinstance(raw_edges, list):+ return None+ nodes: list[ContextNode] = []+ for raw_node in cast(list[object], raw_nodes):+ if not isinstance(raw_node, dict):+ return None+ node = cast(dict[str, object], raw_node)+ path, name = node.get("path"), node.get("name")+ if not isinstance(path, str) or not isinstance(name, str):+ return None+ tokens, state = node.get("tokens"), node.get("state")+ if not isinstance(tokens, int) or isinstance(tokens, bool) or tokens < 0 or state not in ("loaded", "discovered"):+ return None+ nodes.append({"path": path, "name": name, "tokens": tokens,+ "state": "loaded" if state == "loaded" else "discovered"})+ paths = {node["path"] for node in nodes}+ edges: list[ContextEdge] = []+ for raw_edge in cast(list[object], raw_edges):+ if not isinstance(raw_edge, dict):+ return None+ edge = cast(dict[str, object], raw_edge)+ source, target = edge.get("source"), edge.get("target")+ if not isinstance(source, str) or not isinstance(target, str):+ return None+ if source not in paths or target not in paths:+ return None+ edges.append({"source": source, "target": target})+ return {"nodes": nodes, "edges": edges}+++def graph_from_sources(sources: Sequence[SourceReceipt]) -> ContextGraph:+ """Project files used in this epoch, regardless of subsequent text edits."""+ nodes: dict[str, ContextNode] = {}+ edges: dict[tuple[str, str], ContextEdge] = {}+ for source in sources:+ path = source["path"]+ node = nodes.setdefault(path, {"path": path, "name": source["name"], "state": "discovered", "tokens": 0})+ if source["loaded"]:+ node["state"] = "loaded"+ node["tokens"] = max(node["tokens"], source["tokens"])+ for target in source["links"]:+ if target not in nodes:+ nodes[target] = {"path": target, "name": Path(target).name, "state": "discovered", "tokens": 0}+ edges[path, target] = {"source": path, "target": target}+ return {"nodes": list(nodes.values()), "edges": list(edges.values())}+++class ContextSnapshot(TypedDict):+ graph: ContextGraph+ estimated_tokens: int+ context_window_tokens: intdiff --git a/nanobot/context_sources.py b/nanobot/context_sources.pynew file mode 100644index 000000000..86f1aa7c1--- /dev/null+++ b/nanobot/context_sources.py@@ -0,0 +1,70 @@+"""Compact file-use facts captured at source boundaries, not prompt-retention claims."""++from __future__ import annotations++from collections.abc import Generator+from contextlib import contextmanager+from contextvars import ContextVar+from dataclasses import dataclass+from pathlib import Path+from typing import TypedDict, cast++from nanobot.events import AgentEvent+++class SourceReceipt(TypedDict):+ path: str+ name: str+ tokens: int+ links: list[str]+ loaded: bool+++@dataclass(frozen=True)+class PromptSource:+ path: Path+ content: str+ loaded: bool = True+++@dataclass(frozen=True)+class PromptSourcesEvent(AgentEvent):+ sources: tuple[PromptSource, ...]+++_sources: ContextVar[list[PromptSource] | None] = ContextVar("context_sources", default=None)+++@contextmanager+def capture_sources() -> Generator[list[PromptSource]]:+ """Observe builder reads in one run, including its prompt worker tasks."""+ sources: list[PromptSource] = []+ token = _sources.set(sources)+ try:+ yield sources+ finally:+ _sources.reset(token)+++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))+++def parse_source_receipt(value: object) -> SourceReceipt | None:+ """Validate one persisted file-read fact at the display history boundary."""+ if not isinstance(value, dict):+ return None+ source = cast(dict[str, object], value)+ path, name, tokens = source.get("path"), source.get("name"), source.get("tokens")+ links, loaded = source.get("links"), source.get("loaded")+ if not isinstance(path, str) or not isinstance(name, str):+ return None+ if not isinstance(tokens, int) or isinstance(tokens, bool) or tokens < 0:+ return None+ if not isinstance(loaded, bool) or not isinstance(links, list):+ return None+ if not all(isinstance(link, str) for link in cast(list[object], links)):+ return None+ return {"path": path, "name": name, "tokens": tokens, "links": cast(list[str], links), "loaded": loaded}diff --git a/nanobot/events.py b/nanobot/events.pyindex c2e7c4bea..f3ff8d096 100644--- a/nanobot/events.py+++ b/nanobot/events.py@@ -24,6 +24,7 @@ class ModelRequestEvent(AgentEvent):usage: LLMUsage | None = Noneround_usages: tuple[LLMUsage, ...] = ()context_window_tokens: int | None = None+ request_usage: LLMUsage | None = None@dataclass(frozen=True)diff --git a/nanobot/file_references.py b/nanobot/file_references.pynew file mode 100644index 000000000..cf542aae7--- /dev/null+++ b/nanobot/file_references.py@@ -0,0 +1,112 @@+"""Analyze bounded file reads; syntax support is registered by suffix."""++from __future__ import annotations++from collections import OrderedDict+from collections.abc import Iterator+from pathlib import Path+from threading import Lock+from typing import TYPE_CHECKING, Protocol+from urllib.parse import unquote, urlsplit++from markdown_it import MarkdownIt++from nanobot.context_sources import SourceReceipt+from nanobot.utils.token_encoding import get_token_encoding++if TYPE_CHECKING:+ from tiktoken import Encoding+++class ReferenceParser(Protocol):+ def references(self, content: str) -> Iterator[str]: ...+++class MarkdownReferences:+ def references(self, content: str) -> Iterator[str]:+ for block in MarkdownIt("commonmark").parse(content):+ for token in block.children or ():+ if token.type == "link_open" and (href := token.attrGet("href")):+ if isinstance(href, str):+ yield href+++# Bound retained source text, rather than evicting a normal prompt's working set+# after sixteen files. Results contain unresolved links so directory/symlink+# changes still take effect on every observation.+_ANALYSIS_SOURCE_BYTES = 4 * 1024 * 1024+_ANALYSIS_ENTRIES = 256+_analysis_cache: OrderedDict[+ tuple[str, ReferenceParser | None, Encoding | None],+ tuple[int, tuple[str, ...], int],+] = OrderedDict()+_analysis_bytes = 0+_analysis_lock = Lock()+++def _analyze_source(content: str, parser: ReferenceParser | None) -> tuple[int, tuple[str, ...]]:+ global _analysis_bytes+ encoding = get_token_encoding()+ key = (content, parser, encoding)+ with _analysis_lock:+ if (cached := _analysis_cache.get(key)) is not None:+ _analysis_cache.move_to_end(key)+ return cached[0], cached[1]+ source_bytes = len(content.encode("utf-8"))+ links = tuple(dict.fromkeys(parser.references(content))) if parser else ()+ tokens = source_bytes+ if encoding is not None:+ try:+ tokens = len(encoding.encode_ordinary(content))+ except Exception:+ # Do not cache a transient encoding failure as a successful estimate.+ return tokens, links+ if source_bytes <= _ANALYSIS_SOURCE_BYTES:+ with _analysis_lock:+ # Concurrent observers may have analyzed the same content meanwhile.+ if key not in _analysis_cache:+ while _analysis_cache and (+ _analysis_bytes + source_bytes > _ANALYSIS_SOURCE_BYTES+ or len(_analysis_cache) >= _ANALYSIS_ENTRIES+ ):+ _analysis_bytes -= _analysis_cache.popitem(last=False)[1][2]+ _analysis_cache[key] = (tokens, links, source_bytes)+ _analysis_bytes += source_bytes+ return tokens, links+++REFERENCE_PARSERS: dict[str, ReferenceParser] = {+ ".md": MarkdownReferences(),+ ".markdown": MarkdownReferences(),+}+def source_receipt(path: Path, content: str, *, loaded: bool = True) -> SourceReceipt:+ """Discover links without opening, checking, or fetching their targets."""+ path = path.resolve()+ links: list[str] = []+ parser = REFERENCE_PARSERS.get(path.suffix.lower()) if loaded else None+ tokens, references = _analyze_source(content, parser) if loaded else (0, ())+ if parser:+ seen: set[str] = set()+ for href in references:+ if href in seen:+ continue+ seen.add(href)+ try:+ parsed = urlsplit(href)+ if parsed.scheme or parsed.netloc or not parsed.path:+ continue+ decoded_path = unquote(parsed.path)+ if "\x00" in decoded_path:+ continue+ target = str((path.parent / decoded_path).resolve())+ except (ValueError, OSError, RuntimeError):+ # Link text is untrusted; invalid paths must not break prompt assembly.+ continue+ if target != str(path) and target not in links:+ links.append(target)+ if len(links) >= 128:+ break+ return {"path": str(path), "name": path.parent.name if path.name == "SKILL.md" else path.name, "tokens": tokens,+ "links": links, "loaded": loaded}++diff --git a/nanobot/session/display_history.py b/nanobot/session/display_history.pyindex 498e5f46b..2bd93c660 100644--- a/nanobot/session/display_history.py+++ b/nanobot/session/display_history.py@@ -8,6 +8,8 @@ from enum import StrEnumfrom pathlib import Pathfrom typing import Any, cast+from nanobot.session.history_graph import encode_graph_fields, graph_size_adjustment+MAX_HISTORY_FACT_BYTES = 8 * 1024 * 1024HISTORY_GENERATION_METADATA_KEY = "_history_generation"@@ -40,13 +42,23 @@ class HistoryFact:created_at_ms: int = 0def encode(self) -> str:- record = json.dumps({- "kind": self.kind.value, "content": dict(self.content),+ content = encode_graph_fields(self.content)+ payload = {+ "kind": self.kind.value, "content": content,"turn_id": self.turn_id, "phase": self.phase,"sequence": self.sequence, "created_at_ms": self.created_at_ms,- }, ensure_ascii=False, allow_nan=False, separators=(",", ":"))- if len(record.encode("utf-8")) > MAX_HISTORY_FACT_BYTES:+ }+ record = json.dumps(payload, ensure_ascii=False, allow_nan=False, separators=(",", ":"))+ stored_bytes = len(record.encode("utf-8"))+ adjustment = graph_size_adjustment(content)+ logical_bytes = stored_bytes + adjustment+ if max(stored_bytes, logical_bytes) > MAX_HISTORY_FACT_BYTES:raise ValueError("history fact exceeds the 8 MiB storage limit")+ if adjustment:+ payload["uncompressed_bytes"] = logical_bytes+ record = json.dumps(payload, ensure_ascii=False, allow_nan=False, separators=(",", ":"))+ if len(record.encode("utf-8")) > MAX_HISTORY_FACT_BYTES:+ raise ValueError("history fact exceeds the 8 MiB storage limit")return record@classmethod@@ -116,14 +128,14 @@ class HistoryReader:((HistoryKind.COMPLETION,), "DESC"),((HistoryKind.ANSWER, HistoryKind.ANSWER_SEGMENT, HistoryKind.ANSWER_FRAGMENT), "DESC")):row = self._db.execute(- f"SELECT position, length(CAST(record AS BLOB)) FROM history_entries WHERE {clause} "+ f"SELECT position, coalesce(json_extract(record, '$.uncompressed_bytes'), length(CAST(record AS BLOB))) FROM history_entries WHERE {clause} "f"AND kind IN ({','.join('?' for _ in kinds)}) ORDER BY position {order} LIMIT 1",(*params, *kinds),).fetchone()if row is not None:priorities.append((row[0], row[1]))candidates = self._db.execute(- f"SELECT position, length(CAST(record AS BLOB)) FROM history_entries WHERE {clause} ORDER BY position DESC LIMIT ?",+ f"SELECT position, coalesce(json_extract(record, '$.uncompressed_bytes'), length(CAST(record AS BLOB))) FROM history_entries WHERE {clause} ORDER BY position DESC LIMIT ?",(*params, max_records),)positions: set[int] = set()diff --git a/nanobot/session/history_graph.py b/nanobot/session/history_graph.pynew file mode 100644index 000000000..b16172d14--- /dev/null+++ b/nanobot/session/history_graph.py@@ -0,0 +1,250 @@+"""Self-contained graph values for history facts; encoding runs in the storage worker."""+from __future__ import annotations++import base64+import json+import zlib+from collections.abc import Generator, Mapping+from contextlib import contextmanager+from contextvars import ContextVar+from functools import lru_cache+from typing import Any, cast++from nanobot.context_graph import (+ ContextEdge,+ ContextGraph,+ ContextNode,+ ContextSnapshot,+ parse_context_graph,+)++_PREFIX = "graph-columns-v1:"+_MAX_BYTES = 8 * 1024 * 1024+_CACHEABLE_BYTES = 128 * 1024+++@lru_cache(maxsize=16)+def _compress_small(serialized: str) -> str | None:+ return _compress(serialized)+++def _compress(serialized: str) -> str | None:+ graph = parse_context_graph(json.loads(serialized))+ if graph is None:+ return None+ paths = {node["path"]: index for index, node in enumerate(graph["nodes"])}+ columns = [+ [[node["path"], node["name"], node["tokens"], node["state"]] for node in graph["nodes"]],+ [index for edge in graph["edges"] for index in (paths[edge["source"]], paths[edge["target"]])],+ ]+ raw = json.dumps(columns, ensure_ascii=False, separators=(",", ":")).encode("utf-8")+ return f"{_PREFIX}{len(serialized.encode('utf-8'))}:{len(raw)}:" + base64.b64encode(zlib.compress(raw, level=1)).decode("ascii")+++def encode_graph(value: object) -> object:+ if not isinstance(value, dict):+ return value+ value = cast(dict[str, object], value)+ serialized = json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False)+ size = len(serialized.encode("utf-8"))+ if size > _MAX_BYTES:+ raise ValueError("history graph exceeds the 8 MiB storage limit")+ encoded = _compress_small(serialized) if size <= _CACHEABLE_BYTES else _compress(serialized)+ return encoded if encoded is not None else value+++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"])+ snapshot = result.get("context_snapshot")+ if isinstance(snapshot, dict) and "graph" in snapshot:+ snapshot = cast(dict[str, Any], snapshot)+ result["context_snapshot"] = {**snapshot, "graph": encode_graph(snapshot["graph"])}+ return result+++class GraphDecoder:+ """One projection owns validated shared entities, including changing snapshots."""+ def __init__(self) -> None:+ self.graphs: dict[str, ContextGraph | None] = {}+ self.nodes: dict[tuple[object, ...], ContextNode] = {}+ self.edges: dict[tuple[object, object], ContextEdge] = {}+ self.sizes: dict[int, int] = {}++ def node(self, path: object, name: object, tokens: object, state: object) -> ContextNode | None:+ key = (path, name, type(tokens), tokens, state)+ try:+ cached = self.nodes.get(key)+ except TypeError:+ return None+ if cached is not None:+ return cached+ if not isinstance(path, str) or not isinstance(name, str) or type(tokens) is not int or tokens < 0 or state not in ("loaded", "discovered"):+ return None+ node: ContextNode = {"path": path, "name": name, "tokens": tokens,+ "state": "loaded" if state == "loaded" else "discovered"}+ self.nodes[key] = node+ self.sizes[id(node)] = len(json.dumps(node, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))+ return node++ def edge(self, source: str, target: str) -> ContextEdge:+ key = (source, target)+ if key not in self.edges:+ edge: ContextEdge = {"source": source, "target": target}+ self.edges[key] = edge+ self.sizes[id(edge)] = len(json.dumps(edge, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))+ return self.edges[key]++ def inline(self, value: object) -> ContextGraph | None:+ if not isinstance(value, dict):+ return None+ value = cast(dict[str, object], value)+ raw_nodes, raw_edges = value.get("nodes"), value.get("edges")+ if not isinstance(raw_nodes, list) or not isinstance(raw_edges, list):+ return None+ nodes: list[ContextNode] = []+ for raw in cast(list[object], raw_nodes):+ if not isinstance(raw, dict):+ return None+ row = cast(dict[str, object], raw)+ node = self.node(row.get("path"), row.get("name"), row.get("tokens"), row.get("state"))+ if node is None:+ return None+ nodes.append(node)+ paths = {node["path"] for node in nodes}+ edges: list[ContextEdge] = []+ for raw in cast(list[object], raw_edges):+ if not isinstance(raw, dict):+ return None+ row = cast(dict[str, object], raw)+ source, target = row.get("source"), row.get("target")+ if not isinstance(source, str) or not isinstance(target, str) or source not in paths or target not in paths:+ return None+ edges.append(self.edge(source, target))+ return {"nodes": nodes, "edges": edges}++ def columns(self, value: object, logical_bytes: int) -> ContextGraph | None:+ if not isinstance(value, list) or len(cast(list[object], value)) != 2:+ return None+ rows, indices = cast(list[object], value)+ if not isinstance(rows, list) or not isinstance(indices, list) or len(cast(list[object], indices)) % 2:+ return None+ nodes: list[ContextNode] = []+ for row in cast(list[object], rows):+ if not isinstance(row, list) or len(cast(list[object], row)) != 4:+ return None+ path, name, tokens, state = cast(list[object], row)+ node = self.node(path, name, tokens, state)+ if node is None:+ return None+ nodes.append(node)+ indices = cast(list[object], indices)+ if any(type(index) is not int or not 0 <= index < len(nodes) for index in indices):+ return None+ positions = cast(list[int], indices)+ edges = [self.edge(nodes[positions[i]]["path"], nodes[positions[i + 1]]["path"])+ for i in range(0, len(positions), 2)]+ # Do not trust a small declared logical size to bypass the replay byte budget.+ size = 23 + max(0, len(nodes) - 1) + max(0, len(edges) - 1)+ 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 graph(self, value: object) -> ContextGraph | None:+ if isinstance(value, str):+ key = value+ elif isinstance(value, dict):+ try:+ key = json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False)+ except (ValueError, TypeError):+ return None+ else:+ return None+ if key in self.graphs:+ return self.graphs[key]+ self.graphs[key] = None+ if isinstance(value, str):+ if not value.startswith(_PREFIX) or len(value) > _MAX_BYTES * 2:+ return None+ try:+ logical_text, size_text, encoded = value[len(_PREFIX):].split(":", 2)+ logical_size, size = int(logical_text), int(size_text)+ if not 0 <= logical_size <= _MAX_BYTES or not 0 <= size <= _MAX_BYTES:+ return None+ raw = base64.b64decode(encoded, validate=True)+ inflater = zlib.decompressobj()+ expanded = inflater.decompress(raw, _MAX_BYTES + 1)+ if len(expanded) != size or not inflater.eof or inflater.unused_data:+ return None+ graph = self.columns(json.loads(expanded), logical_size)+ except (ValueError, zlib.error, UnicodeDecodeError):+ return None+ else:+ graph = self.inline(cast(object, value))+ self.graphs[key] = graph+ return graph+++_decoder: ContextVar[GraphDecoder | None] = ContextVar("history_graph_decoder", default=None)+++@contextmanager+def graph_decoding() -> Generator[None]:+ token = _decoder.set(GraphDecoder())+ try:+ yield+ finally:+ _decoder.reset(token)+++def decode_graph(value: object) -> ContextGraph | None:+ return (_decoder.get() or GraphDecoder()).graph(value)+++def decode_snapshot(value: object) -> ContextSnapshot | None:+ if not isinstance(value, dict):+ return None+ snapshot = cast(dict[str, object], value)+ tokens, window = snapshot.get("estimated_tokens"), snapshot.get("context_window_tokens")+ if type(tokens) is not int or tokens < 0 or type(window) is not int or window <= 0:+ return None+ graph = decode_graph(snapshot.get("graph"))+ return {"graph": graph, "estimated_tokens": tokens, "context_window_tokens": window} if graph is not None else None+++def expand_graph_fields(content: Mapping[str, Any]) -> dict[str, Any]:+ result = dict(content)+ for field, decode in (("context_graph", decode_graph), ("context_snapshot", decode_snapshot)):+ if field in result:+ decoded = decode(result[field])+ if decoded is None:+ result.pop(field)+ else:+ result[field] = decoded+ return result+++def graph_size_adjustment(content: Mapping[str, Any]) -> int:+ """Retain the original replay byte budget despite storage compression."""+ values = [content.get("context_graph")]+ snapshot = content.get("context_snapshot")+ if isinstance(snapshot, dict):+ values.append(cast(dict[str, object], snapshot).get("graph"))+ adjustment = 0+ for value in values:+ if isinstance(value, str) and value.startswith(_PREFIX):+ try:+ size = int(value[len(_PREFIX):].split(":", 1)[0])+ except ValueError:+ continue+ if 0 <= size <= _MAX_BYTES:+ adjustment += size - len(value) - 2 # ASCII encoding plus JSON quotes.+ return adjustment+++def history_record_size(record: str) -> int:+ stored = len(record.encode("utf-8"))+ if '"uncompressed_bytes":' not in record:+ return stored+ value = json.loads(record).get("uncompressed_bytes")+ return value if type(value) is int and 0 <= value <= _MAX_BYTES else storeddiff --git a/nanobot/session/sqlite_store.py b/nanobot/session/sqlite_store.pyindex fd8e3b36d..16fb4aaf7 100644--- a/nanobot/session/sqlite_store.py+++ b/nanobot/session/sqlite_store.py@@ -12,6 +12,7 @@ from typing import Any, TypeVar, castfrom nanobot.providers.base import ProviderConversationStatefrom nanobot.session.display_history import HistoryFact, HistoryKind, HistoryReader+from nanobot.session.history_graph import history_record_sizefrom nanobot.session.history_visibility import is_hidden_history_messagefrom nanobot.session.manager import (Session,@@ -428,8 +429,25 @@ class SqliteSessionStore:def append_history(self, key: str, facts: list[HistoryFact], *, expected_generation: str | None,- ) -> None:- encoded = [(fact, fact.encode()) for fact in facts]+ skip_invalid: bool = False,+ ) -> list[str]:+ encoded: list[tuple[HistoryKind, int, str, str]] = []+ errors: list[str] = []+ for fact in facts:+ try:+ record = fact.encode()+ # Freeze all transaction inputs from the encoded snapshot; never+ # revisit mutable content after serialization has completed.+ preview = ""+ if fact.kind in {HistoryKind.INPUT, HistoryKind.ANSWER, HistoryKind.ANSWER_SEGMENT}:+ preview = message_preview_text({"content": json.loads(record)["content"].get("text", "")})+ encoded.append((fact.kind, fact.created_at_ms, record, preview))+ except (ValueError, TypeError) as exc:+ if not skip_invalid:+ raise+ errors.append(str(exc))+ if not encoded and errors:+ return errorswith self.transaction() as db:row = db.execute("SELECT generation FROM sessions WHERE key=?", (key,)).fetchone()if row is None or (expected_generation is not None and row[0] != expected_generation):@@ -441,7 +459,7 @@ class SqliteSessionStore:).fetchone()ordinal, position = (int(tail[0]), int(tail[1])) if tail is not None else (0, 0)completed = tail is not None and bool(tail[2])- for fact, record in encoded:+ for kind, created_at_ms, record, preview in encoded:if completed:ordinal, position = ordinal + 1, 0if position == 0:@@ -449,25 +467,24 @@ class SqliteSessionStore:"INSERT INTO history_turns VALUES (?, ?, 0, 0, 0, 0)", (key, ordinal),)db.execute("INSERT INTO history_entries VALUES (?, ?, ?, ?, ?)", (- key, ordinal, position, fact.kind.value, record,+ key, ordinal, position, kind.value, record,))- completed = fact.kind is HistoryKind.COMPLETION+ completed = kind is HistoryKind.COMPLETIONdb.execute("""UPDATE history_turns SET record_count=record_count+1, byte_count=byte_count+?,user_count=user_count+?, completed=? WHERE session_key=? AND ordinal=?""",- (len(record.encode("utf-8")), int(fact.kind is HistoryKind.INPUT),+ (history_record_size(record), int(kind is HistoryKind.INPUT),int(completed), key, ordinal),)position += 1- if fact.kind in {HistoryKind.INPUT, HistoryKind.ANSWER, HistoryKind.ANSWER_SEGMENT}:- preview = message_preview_text({"content": fact.content.get("text", "")})- if preview:- field = "user_preview" if fact.kind is HistoryKind.INPUT else "preview"- db.execute(f"UPDATE history_heads SET {field}=? WHERE session_key=? AND {field}=''", (preview, key))+ if preview:+ field = "user_preview" if kind is HistoryKind.INPUT else "preview"+ db.execute(f"UPDATE history_heads SET {field}=? WHERE session_key=? AND {field}=''", (preview, key))db.execute("UPDATE history_heads SET updated_at_ms=max(updated_at_ms, ?) WHERE session_key=?",- (fact.created_at_ms, key))+ (created_at_ms, key))if encoded:db.execute("UPDATE history_heads SET revision=revision+1 WHERE session_key=?", (key,))+ return errorsdef copy_history_prefix(self, source_key: str, target: Session, before_input: int) -> bool:"""Copy a display prefix alongside its canonical fork, in the caller's transaction."""diff --git a/nanobot/session/state.py b/nanobot/session/state.pyindex afa10ce3c..041f0a528 100644--- a/nanobot/session/state.py+++ b/nanobot/session/state.py@@ -725,12 +725,14 @@ class SessionState:async def append_history(self, key: str, facts: Sequence[HistoryFact], *, expected_generation: str | None,- ) -> None:- """Append to an existing session; None selects its current generation."""+ skip_invalid: bool = False,+ ) -> list[str]:+ """Serialize owned facts in the worker; None selects the current generation."""records = list(facts)- await self._execute(+ return await self._execute(key,- lambda: self._store.append_history(key, deepcopy(records), expected_generation=expected_generation),+ lambda: self._store.append_history(key, records, expected_generation=expected_generation,+ skip_invalid=skip_invalid),operation_name="append_history",)diff --git a/nanobot/utils/prompt_templates.py b/nanobot/utils/prompt_templates.pyindex 27b12f79e..41cc4862e 100644--- a/nanobot/utils/prompt_templates.py+++ b/nanobot/utils/prompt_templates.py@@ -11,6 +11,8 @@ from typing import Anyfrom jinja2 import Environment, FileSystemLoader+from nanobot.context_sources import record_source+_TEMPLATES_ROOT = Path(__file__).resolve().parent.parent / "templates"@@ -25,11 +27,14 @@ def _environment() -> Environment:)-def render_template(name: str, *, strip: bool = False, **kwargs: Any) -> str:+def render_template(name: str, *, strip: bool = False, track_source: bool = False, **kwargs: Any) -> str:"""Render ``name`` (e.g. ``agent/identity.md``, ``agent/platform_policy.md``) under ``templates/``.Use ``strip=True`` for single-line user-facing strings when the file endswith a trailing newline you do not want preserved."""text = _environment().get_template(name).render(**kwargs)- return text.rstrip() if strip else text+ text = text.rstrip() if strip else text+ if track_source:+ record_source(_TEMPLATES_ROOT / name, text)+ return textdiff --git a/nanobot/webui/client_contract.py b/nanobot/webui/client_contract.pyindex 6df8e0484..3b1b5f6f6 100644--- a/nanobot/webui/client_contract.py+++ b/nanobot/webui/client_contract.py@@ -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,],}diff --git a/nanobot/webui/context_observer.py b/nanobot/webui/context_observer.pynew file mode 100644index 000000000..ca21b171b--- /dev/null+++ b/nanobot/webui/context_observer.py@@ -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()diff --git a/nanobot/webui/context_source_hook.py b/nanobot/webui/context_source_hook.pynew file mode 100644index 000000000..0b28c2046--- /dev/null+++ b/nanobot/webui/context_source_hook.py@@ -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 Nonediff --git a/nanobot/webui/history.py b/nanobot/webui/history.pyindex bfb888604..db93bc4cf 100644--- a/nanobot/webui/history.py+++ b/nanobot/webui/history.py@@ -5,6 +5,7 @@ from typing import Anyfrom nanobot.bus.events import INBOUND_META_LOCAL_MEDIAfrom nanobot.session.display_history import HistoryFact, HistoryKind, HistoryReader+from nanobot.session.history_graph import expand_graph_fieldsfrom 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)]diff --git a/nanobot/webui/outbound_delivery.py b/nanobot/webui/outbound_delivery.pyindex 5a0621953..1c26e5aa0 100644--- a/nanobot/webui/outbound_delivery.py+++ b/nanobot/webui/outbound_delivery.py@@ -1,5 +1,6 @@from __future__ import annotations+import asyncioimport jsonfrom collections.abc import Callable, Mapping, Sequencefrom dataclasses import dataclass@@ -24,6 +25,8 @@ from nanobot.bus.outbound_events import ()from nanobot.bus.queue import MessageBusfrom nanobot.bus.runtime_events import SubagentTaskChanged+from nanobot.context_graph import ContextGraph+from nanobot.context_sources import PromptSourcesEventfrom nanobot.events import ModelRequestEventfrom nanobot.pairing.events import PairingChangedfrom 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 ContextGraphObserverfrom nanobot.webui.media_gateway import WebUIMediaGatewayfrom 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 = transcriptsself._temporary_chats = temporary_chatsself._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 Noneif 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 Nonebody = 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),+ )+ returnif isinstance(event, PairingChanged):await self._fanout(self._transport.webui_recipients("authenticated_webui"),@@ -248,7 +289,7 @@ class WebUIOutboundDelivery:body["provenance"] = event.provenanceawait 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.contentuser_shell = msg.metadata.get(INBOUND_META_USER_SHELL) is Truepayload: 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:diff --git a/nanobot/webui/outbound_wire.py b/nanobot/webui/outbound_wire.pyindex d8997dfcb..753485678 100644--- a/nanobot/webui/outbound_wire.py+++ b/nanobot/webui/outbound_wire.py@@ -11,6 +11,7 @@ from nanobot.bus.outbound_events import (RetryStatusEvent,TurnEndEvent,)+from nanobot.context_graph import ContextGraph, ContextSnapshotfrom nanobot.events import AgentEvent, CompactionReason, ModelRequestEventfrom 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: strrun_id: str@@ -108,6 +111,7 @@ class ModelRequestWirePayload(_ChatWirePayload):class ContextCompactionWirePayload(_ChatWirePayload):+ context_snapshot: NotRequired[ContextSnapshot]event: Literal["context_compaction"]compaction_id: strphase: 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_graphif 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:]]diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.pyindex d3f840e3a..cf89d2ee8 100644--- a/nanobot/webui/transcript.py+++ b/nanobot/webui/transcript.py@@ -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_messagefrom nanobot.session.manager import Session, SessionManagerfrom 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 = 0for 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) + 1return 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 Falsetry:- 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 errorsexcept (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"] = snapshotreason = 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 Noneprojected.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"] = graphlatency_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,*,diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.pyindex 516d5c1f1..5bc602a4c 100644--- a/nanobot/webui/ws_http.py+++ b/nanobot/webui/ws_http.py@@ -18,7 +18,7 @@ import timefrom collections.abc import Awaitable, Callable, Mappingfrom dataclasses import dataclass, fieldfrom pathlib import Path-from typing import TYPE_CHECKING, Any, Protocol, cast+from typing import TYPE_CHECKING, Any, Protocol, TypeVar, castfrom urllib.parse import quote, unquote, urlsplit, urlunsplitfrom loguru import logger@@ -29,6 +29,7 @@ from websockets.http11 import Responsefrom nanobot.agent.subagent import SubagentControlErrorfrom nanobot.agent.subagent_status import SubagentSessionErrorfrom nanobot.command.application import builtin_command_palette+from nanobot.context_graph import ContextGraphfrom nanobot.cron.binding import CronBindingError, binding_revisionfrom nanobot.cron.session_turns import is_bound_cron_jobfrom 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 Noneasync 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 = preparedfinally:active = Falsetimer.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:diff --git a/pyproject.toml b/pyproject.tomlindex a7ebb37e8..cf6f64b39 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -40,6 +40,7 @@ dependencies = ["readability-lxml>=0.8.4,<1.0.0","lxml-html-clean>=0.4.0,<1.0.0","rich>=14.0.0,<15.0.0",+ "markdown-it-py>=3.0.0,<5.0.0","qrcode[pil]>=8.0","pillow>=13.0.0,<14.0.0","croniter>=6.0.0,<7.0.0",diff --git a/tests/agent/test_context_source_hook.py b/tests/agent/test_context_source_hook.pynew file mode 100644index 000000000..22cb06538--- /dev/null+++ b/tests/agent/test_context_source_hook.py@@ -0,0 +1,59 @@+import asyncio++import pytest++from nanobot.events import EventSink+++async def test_prompt_scopes_isolate_parallel_runs_and_cleanup_after_cancel(tmp_path):+ from unittest.mock import MagicMock++ from agent.runner_helpers import make_run_spec+ from nanobot.agent.hook import AgentHook, CompositeHook+ from nanobot.agent.runner import AgentRunner+ from nanobot.context_sources import PromptSourcesEvent, capture_sources, record_source+ from nanobot.providers.base import LLMResponse+ from nanobot.webui.context_source_hook import ContextSourceHook++ entered = asyncio.Event()+ events = []++ async def publish(event):+ if isinstance(event, PromptSourcesEvent):+ events.append(event)++ async def run(name, blocked=False):+ class BuildPrompt(AgentHook):+ async def before_iteration(self, context):+ await asyncio.to_thread(record_source, tmp_path / name, name)++ async def provider_call(**kwargs):+ if blocked:+ entered.set()+ await asyncio.Event().wait()+ return LLMResponse(content="done")++ provider = MagicMock()+ provider.chat_stream_with_retry = provider_call+ tools = MagicMock()+ tools.get_definitions.return_value = []+ with capture_sources() as enclosing:+ hook = CompositeHook([ContextSourceHook(EventSink(publish)), BuildPrompt()])+ try:+ await AgentRunner().run(make_run_spec(+ provider, initial_messages=[{"role": "user", "content": name}],+ tools=tools, hook=hook, model="test", max_iterations=2, max_tool_result_chars=10000,+ ))+ finally:+ record_source(tmp_path / "after.md", "after")+ assert [source.path.name for source in enclosing] == ["after.md"]++ cancelled = asyncio.create_task(run("first.md", blocked=True))+ try:+ await asyncio.wait_for(entered.wait(), 2)+ await run("second.md")+ finally:+ cancelled.cancel()+ with pytest.raises(asyncio.CancelledError):+ await cancelled+ assert [[source.path.name for source in event.sources] for event in events] == [["first.md"], ["second.md"]]diff --git a/tests/agent/test_model_request_events.py b/tests/agent/test_model_request_events.pyindex c42f0843f..5dcac3792 100644--- a/tests/agent/test_model_request_events.py+++ b/tests/agent/test_model_request_events.py@@ -257,3 +257,57 @@ def test_model_requests_are_optional_for_non_webui_channels():for channel in ("telegram", "slack", "cli", "discord"):assert not notification_is_deliverable(ModelRequestEvent, channel=channel, publish_lifecycle=True)assert notification_is_deliverable(ModelRequestEvent, channel="websocket", publish_lifecycle=True)+++async def test_request_without_usage_does_not_reuse_previous_measurement():+ events = []+ usage = LLMUsage.reported(input_tokens=12, output_tokens=3)++ async def publish(event):+ if isinstance(event, ModelRequestEvent):+ events.append(event)++ provider = MagicMock()+ provider.chat_stream_with_retry = AsyncMock(side_effect=[+ LLMResponse(content=None, tool_calls=[ToolCallRequest("c", "tool", {})], usage=usage),+ LLMResponse(content="done"),+ ])+ run_spec = spec(provider, EventSink(publish))+ run_spec.tools.prepare_call.return_value = (None, {}, None)+ run_spec.tools.execute = AsyncMock(return_value="ok")+ await AgentRunner().run(run_spec)+ completed = [event for event in events if event.phase == "completed"]+ assert completed[0].request_usage == usage+ assert completed[1].request_usage is None+ assert completed[1].usage == usage+++async def test_prepared_request_observers_run_before_request_event_and_provider():+ from nanobot.agent.hook import AgentHook, CompositeHook++ order = []+ class Observer(AgentHook):+ async def before_model_request(self):+ order.append("observer")++ class BrokenObserver(AgentHook):+ async def before_model_request(self):+ raise RuntimeError("observation failed")++ async def publish(event):+ if isinstance(event, ModelRequestEvent):+ order.append(event.phase)++ async def provider_call(**kwargs):+ order.append("provider")+ return LLMResponse(content="done")++ provider = MagicMock()+ provider.chat_stream_with_retry = provider_call+ run_spec = spec(provider, EventSink(publish))+ run_spec.hook = CompositeHook([BrokenObserver(), Observer()])+ result = await AgentRunner().run(run_spec)+ assert result.final_content == "done"+ assert order == ["observer", "started", "provider", "completed"]diff --git a/tests/agent/test_runner_progress_events.py b/tests/agent/test_runner_progress_events.pyindex be9096045..700a00b73 100644--- a/tests/agent/test_runner_progress_events.py+++ b/tests/agent/test_runner_progress_events.py@@ -1,4 +1,5 @@import asyncio+from pathlib import Pathfrom unittest.mock import AsyncMock, MagicMockimport pytest@@ -64,6 +65,7 @@ async def test_start_and_finish_events_emitted() -> None:"error": None,"files": [],"embeds": [],+ "working_directory": str(Path.cwd()),}],),(@@ -79,6 +81,7 @@ async def test_start_and_finish_events_emitted() -> None:"error": None,"files": [],"embeds": [],+ "working_directory": str(Path.cwd()),}],),]@@ -140,7 +143,7 @@ async def test_streamed_content_is_not_repeated_before_tool_execution() -> None:assert progress[0] == ("", True, [{"version": 1, "phase": "start", "call_id": "call1", "name": "custom_tool","arguments": {"path": "foo.txt"}, "result": None, "error": None,- "files": [], "embeds": [],+ "files": [], "embeds": [], "working_directory": str(Path.cwd()),}])assert all(item[0] != "I will inspect it." for item in progress)diff --git a/tests/agent/test_skills_loader.py b/tests/agent/test_skills_loader.pyindex 5276d837d..633bf0daa 100644--- a/tests/agent/test_skills_loader.py+++ b/tests/agent/test_skills_loader.py@@ -657,3 +657,25 @@ def test_check_requirements_tolerates_null_requires_and_lists(tmp_path: Path) ->"missing_bins": [],"missing_env": [],}+++def test_context_skills_observe_resolved_alias_and_share_discovery(tmp_path, monkeypatch):+ from nanobot.context_sources import capture_sources++ path = _write_skill(tmp_path / "skills", "canonical", metadata_json={}, body="# Instructions")+ loader = SkillsLoader(tmp_path, builtin_skills_dir=tmp_path / "builtin")+ monkeypatch.setattr(loader, "_skill_aliases", lambda: {"legacy": "canonical"})+ discover = loader._discover_skills+ discoveries = []++ def counted_discovery():+ discoveries.append(True)+ return discover()++ monkeypatch.setattr(loader, "_discover_skills", counted_discovery)+ 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 len(discoveries) == 1diff --git a/tests/command/test_compact_command.py b/tests/command/test_compact_command.pyindex 15f55d937..f5837528c 100644--- a/tests/command/test_compact_command.py+++ b/tests/command/test_compact_command.py@@ -195,10 +195,8 @@ async def test_compacted_session_waits_for_new_input_without_continuation(loop.provider.chat_stream_with_retry.assert_awaited_once()sent = loop.provider.chat_stream_with_retry.call_args.kwargs["messages"]expected_summary = reloaded.metadata["_last_summary"] if summary != "(nothing)" else None- assert sent[0] == {- "role": "system",- "content": loop.context.build_system_prompt(channel="cli", session_summary=expected_summary),- }+ assert sent[0]["role"] == "system"+ assert sent[0]["content"] == loop.context.build_system_prompt(channel="cli", session_summary=expected_summary)assert [message["role"] for message in sent] == ["system", "user"]assert sent[1]["content"].startswith("hi\n\n")assert "File access: no workspace restriction." in sent[1]["content"]diff --git a/tests/session/test_history_graph.py b/tests/session/test_history_graph.pynew file mode 100644index 000000000..83a7d764a--- /dev/null+++ b/tests/session/test_history_graph.py@@ -0,0 +1,173 @@+import base64+import json+import threading+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.manager import SessionManager+from nanobot.webui.history import fact_from_record, record_from_fact+from nanobot.webui.transcript import build_webui_thread_response+++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_codec_roundtrip_is_self_contained_and_preserves_order():+ original = graph()+ fact = fact_from_record({"event": "model_request", "context_graph": original})+ stored = json.loads(fact.encode())+ assert isinstance(stored["content"]["context_graph"], str)+ restored = record_from_fact(HistoryFact.decode(json.dumps(stored)), "websocket:test")+ assert restored["context_graph"] == original+ # Import/fork re-encoding remains self-contained; no reference table is needed.+ copied = HistoryFact.decode(HistoryFact.decode(fact.encode()).encode())+ assert record_from_fact(copied, "websocket:fork")["context_graph"] == original+ assert fact.content["context_graph"] == original++[email protected]("value", ["graph-columns-v1:12:12:not-base64", "graph-columns-v1:2:2:" + base64.b64encode(zlib.compress(b"[]" * 1000)).decode(), "zlib-json-v99:anything"])+def test_invalid_graph_does_not_replace_it_with_a_valid_empty_graph(value):+ event = record_from_fact(HistoryFact(HistoryKind.MODEL_REQUEST, {"request_id": "request", "context_graph": value}), "websocket:test")+ assert event["request_id"] == "request"+ assert "context_graph" not in event+++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()++[email protected]("compressed", [False, True])+def test_each_page_validates_identical_graph_once(monkeypatch, compressed):+ import nanobot.session.history_graph as codec+ value = encode_graph(graph()) if compressed else graph()+ method = "columns" if compressed else "inline"+ original = getattr(codec.GraphDecoder, method)+ calls = 0++ def parse(self, *args):+ nonlocal calls+ calls += 1+ return original(self, *args)++ monkeypatch.setattr(codec.GraphDecoder, method, parse)+ with graph_decoding():+ first = decode_graph(value)+ second = decode_graph(json.loads(json.dumps(value)))+ assert first is second+ assert calls == 1+ first["nodes"].clear()+ with graph_decoding():+ assert len(decode_graph(value)["nodes"]) == 5+ assert calls == 2+++async def test_storage_compresses_off_loop_and_replay_retains_each_request(tmp_path, monkeypatch):+ import nanobot.session.history_graph as codec+ sessions = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")+ session = await sessions.state.get("websocket:graph")+ loop_thread = threading.get_ident()+ compress = codec._compress+ calls = []++ def checked(value):+ calls.append(threading.get_ident())+ assert calls[-1] != loop_thread+ return compress(value)++ codec._compress_small.cache_clear()+ monkeypatch.setattr(codec, "_compress", checked)+ for index in range(3):+ await sessions.state.append_history(session.key, [+ fact_from_record({"event": "user", "text": "Question", "turn_id": str(index)}),+ fact_from_record({"event": "model_request", "turn_id": str(index), "request_id": str(index), "run_id": str(index), "sequence": 2, "phase": "completed", "request_usage": {"context_tokens": 10 + index}, "context_graph": graph()}),+ fact_from_record({"event": "turn_end", "turn_id": str(index)}),+ ], expected_generation=session.generation)+ assert len(calls) == 1+ payload = await sessions.state.project_history(session.key, lambda history: build_webui_thread_response(session.key, history=history, include_model_requests=True))+ requests = [event for event in payload["events"] if event["event"] == "model_request"]+ assert [event["request_id"] for event in requests] == ["0", "1", "2"]+ assert [event["request_usage"]["context_tokens"] for event in requests] == [10, 11, 12]+ assert requests[0]["context_graph"] is requests[1]["context_graph"]+ assert requests[0]["context_graph"] == graph()+ await sessions.state.aclose()+++def test_oversized_compressible_graph_is_rejected_before_persistence(tmp_path):+ sessions = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")+ key = "websocket:oversized"+ sessions.get_or_create(key)+ oversized = graph(1)+ oversized["nodes"][0]["name"] = "a" * (8 * 1024 * 1024)+ with pytest.raises(ValueError, match="8 MiB"):+ sessions.append_history(key, [HistoryFact(HistoryKind.MODEL_REQUEST, {"context_graph": oversized})])+ assert sessions.project_history(key, lambda history: list(history.all_facts())) == []++[email protected]("compressed", [False, True])+def test_growing_snapshots_share_unchanged_entities_but_keep_each_state(compressed):+ initial = graph(2)+ later = graph(3)+ initial["edges"] = [{"source": "/0.md", "target": "/1.md"}]+ later["edges"] = [{"source": "/0.md", "target": "/1.md"}, {"source": "/1.md", "target": "/2.md"}]+ later["nodes"][0]["tokens"] = 20+ with graph_decoding():+ first = decode_graph(encode_graph(initial) if compressed else initial)+ second = decode_graph(encode_graph(later) if compressed else later)+ assert first == initial and second == later+ assert first["nodes"][1] is second["nodes"][1]+ assert first["edges"][0] is second["edges"][0]+ assert first["nodes"][0] is not second["nodes"][0]++[email protected]("indices", [[0, 99], [True, 0], [0]])+def test_compact_graph_rejects_invalid_edge_indices(indices):+ raw = json.dumps([[["/0.md", "0.md", 10, "loaded"]], indices]).encode()+ encoded = f"graph-columns-v1:1000:{len(raw)}:" + base64.b64encode(zlib.compress(raw)).decode()+ assert decode_graph(encoded) is None+++async def test_recorder_batch_encodes_once_off_loop_and_keeps_valid_members(tmp_path, monkeypatch):+ from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY+ from nanobot.webui.transcript import WebUITranscriptRecorder++ sessions = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")+ session = await sessions.state.get("websocket:batch")+ loop_thread = threading.get_ident()+ encode = HistoryFact.encode+ calls = []++ def checked(fact):+ calls.append(fact.kind)+ assert threading.get_ident() != loop_thread+ return encode(fact)++ monkeypatch.setattr(HistoryFact, "encode", checked)+ recorder = WebUITranscriptRecorder(sessions)+ valid = await recorder.append_many("batch", [+ {"event": "user", "text": "question"},+ {"event": "model_request", "request_id": "request", "run_id": "run", "sequence": 1, "phase": "started", "context_graph": graph()},+ {"event": "message", "text": object()},+ ], metadata={HISTORY_GENERATION_METADATA_KEY: session.generation})+ assert valid is False+ assert calls == [HistoryKind.INPUT, HistoryKind.MODEL_REQUEST, HistoryKind.ANSWER]+ records = await sessions.state.project_history(session.key, lambda history: [record_from_fact(fact, session.key) for fact in history.all_facts()])+ assert [record["event"] for record in records] == ["user", "model_request"]+ assert records[1]["context_graph"] == graph()+ await sessions.state.aclose()+++def test_storage_limit_includes_compression_size_metadata(monkeypatch):+ fact = HistoryFact(HistoryKind.MODEL_REQUEST, {"context_graph": graph(1), "text": "answer" * 20})+ encoded = fact.encode()+ raw = json.loads(encoded)+ # Small graphs can expand in storage; the final envelope still obeys the cap.+ assert raw["uncompressed_bytes"] < len(encoded.encode("utf-8")) - 1+ monkeypatch.setattr("nanobot.session.display_history.MAX_HISTORY_FACT_BYTES", len(encoded.encode("utf-8")) - 1)+ with pytest.raises(ValueError, match="8 MiB"):+ fact.encode()diff --git a/tests/test_context_graph.py b/tests/test_context_graph.pynew file mode 100644index 000000000..28e2e88fa--- /dev/null+++ b/tests/test_context_graph.py@@ -0,0 +1,259 @@+from pathlib import Path++import pytest++from nanobot.context_graph import graph_from_sources+from nanobot.context_sources import PromptSourcesEvent, capture_sources+from nanobot.file_references import source_receipt+++def graph_from_observations(sources):+ return graph_from_sources([source_receipt(source.path, source.content, loaded=source.loaded) for source in sources])+++def graph_from_build(build):+ with capture_sources() as sources:+ build()+ return graph_from_observations(sources)+++def test_markdown_discovers_only_real_local_links_without_reading_targets(tmp_path: Path):+ content = """[Guide](references/guide.md#setup)+[Other][ref]++[ref]: other.md++[Site](https://example.com)+[Anchor](#heading)+`[code](not-a-link.md)`+```+[example](also-not-a-link.md)+```+"""+ source = source_receipt(tmp_path / "SKILL.md", content)+ assert source["links"] == [str(tmp_path / "references" / "guide.md"), str(tmp_path / "other.md")]+ graph = graph_from_sources([source])+ assert [node["state"] for node in graph["nodes"]] == ["loaded", "discovered", "discovered"]+++def test_repeated_source_analysis_resolves_links_in_the_current_directory(tmp_path: Path):+ content = "[Guide](guide.md)"+ first = tmp_path / "first"+ second = tmp_path / "second"+ first.mkdir()+ second.mkdir()+ link = first / "guide.md"+ try:+ link.symlink_to(tmp_path / "original.md")+ except OSError as exc:+ if getattr(exc, "winerror", None) == 1314:+ pytest.skip("Windows symlink privilege is unavailable")+ raise+ assert source_receipt(first / "SKILL.md", content)["links"] == [str(tmp_path / "original.md")]+ assert source_receipt(second / "SKILL.md", content)["links"] == [str(second / "guide.md")]+ link.unlink()+ link.symlink_to(tmp_path / "replacement.md")+ assert source_receipt(first / "SKILL.md", content)["links"] == [str(tmp_path / "replacement.md")]+ assert source_receipt(first / "SKILL.md", "[New](new.md)")["links"] == [str(first / "new.md")]+++def test_source_token_estimate_updates_when_tokenizer_becomes_available(tmp_path: Path, monkeypatch):+ import tiktoken++ import nanobot.file_references as context_graph++ content = "Hello world"+ monkeypatch.setattr(context_graph, "get_token_encoding", lambda: None)+ assert source_receipt(tmp_path / "source.txt", content)["tokens"] == len(content.encode())+ encoding = tiktoken.get_encoding("cl100k_base")+ monkeypatch.setattr(context_graph, "get_token_encoding", lambda: encoding)+ assert source_receipt(tmp_path / "source.txt", content)["tokens"] == len(encoding.encode_ordinary(content))+++async def test_prompt_working_set_reuses_analysis_and_invalidates_changed_content(tmp_path: Path, monkeypatch):+ from nanobot.context_sources import PromptSource+ from nanobot.file_references import MarkdownReferences+ from nanobot.webui.context_observer import ContextGraphObserver++ calls = []+ original = MarkdownReferences.references++ def references(self, content):+ calls.append(content)+ yield from original(self, content)++ monkeypatch.setattr(MarkdownReferences, "references", references)+ sources = tuple(PromptSource(tmp_path / f"{index}.md", f"{tmp_path} source {index}\n[Guide](guide.md)\n" + "text " * 1600)+ for index in range(20))+ observer = ContextGraphObserver(None)+ await observer.observe_prompt("chat", sources, {}, persistent=False)+ await observer.observe_prompt("chat", sources, {}, persistent=False)+ assert len(calls) == 20+ moved = tuple(PromptSource(tmp_path / "other" / source.path.name, source.content) for source in sources)+ await observer.observe_prompt("other-chat", moved, {}, persistent=False)+ assert len(calls) == 20+ graph = await observer.snapshot("other-chat", {}, persistent=False)+ assert str(tmp_path / "other" / "guide.md") in {node["path"] for node in graph["nodes"]}+ changed = (PromptSource(sources[0].path, f"{tmp_path}\n[New](new.md)"), *sources[1:])+ await observer.observe_prompt("chat", changed, {}, persistent=False)+ assert len(calls) == 21+ graph = await observer.snapshot("chat", {}, persistent=False)+ assert str(tmp_path / "new.md") in {node["path"] for node in graph["nodes"]}+++def test_source_analysis_evicts_by_budget_and_preserves_recent_results(tmp_path: Path, monkeypatch):+ from collections import OrderedDict++ import nanobot.file_references as references++ calls = []++ class Parser:+ def references(self, content):+ calls.append(content)+ yield content.strip() + ".md"++ monkeypatch.setattr(references, "_analysis_cache", OrderedDict())+ monkeypatch.setattr(references, "_analysis_bytes", 0)+ monkeypatch.setattr(references, "_ANALYSIS_SOURCE_BYTES", 120)+ monkeypatch.setitem(references.REFERENCE_PARSERS, ".budget", Parser())+ source = tmp_path / "source.budget"+ first, second, third = (name.ljust(60) for name in ("first", "second", "third"))+ for content in (first, second, first, third, first):+ assert source_receipt(source, content)["links"] == [str(tmp_path / (content.strip() + ".md"))]+ assert calls == [first, second, third]+ source_receipt(source, second)+ assert calls == [first, second, third, second]+++def test_system_sources_track_actual_injection_and_skill_metadata(tmp_path: Path):+ from nanobot.agent.context import ContextBuilder++ (tmp_path / "SOUL.md").write_text("Be precise", encoding="utf-8")+ skill = tmp_path / "skills" / "example"+ skill.mkdir(parents=True)+ (skill / "SKILL.md").write_text("---\nname: example\ndescription: Example\n---\n[Reference](ref.md)", encoding="utf-8")+ graph = graph_from_build(lambda: ContextBuilder(tmp_path).build_messages([], "Hello"))+ by_path = {node["path"]: node for node in graph["nodes"]}+ assert by_path[str(tmp_path / "SOUL.md")]["state"] == "loaded"+ assert by_path[str(skill / "SKILL.md")]["state"] == "discovered"+ assert str(skill / "ref.md") not in by_path+++def test_default_workspace_files_are_discoverable_without_claiming_loaded(tmp_path: Path):+ from nanobot.agent.context import ContextBuilder+ from nanobot.utils.helpers import load_bundled_template++ (tmp_path / "memory").mkdir()+ for name in ("AGENTS.md", "USER.md", "memory/MEMORY.md"):+ (tmp_path / name).write_text(load_bundled_template(name), encoding="utf-8")+ nodes = graph_from_build(lambda: ContextBuilder(tmp_path).build_messages([], "Hello"))["nodes"]+ for name in ("AGENTS.md", "USER.md", "MEMORY.md"):+ node = next(node for node in nodes if node["name"] == name)+ assert node["state"] == "discovered"+ assert node["tokens"] == 0+++def test_graph_survives_webui_history_boundary(tmp_path: Path):+ from nanobot.webui.history import fact_from_record, record_from_fact+ from nanobot.webui.transcript import _client_projection_event++ content = "Read me"+ graph = graph_from_sources([source_receipt(tmp_path / "guide.md", content)])+ event = {"event": "model_request", "request_id": "request", "run_id": "run",+ "sequence": 1, "phase": "completed", "context_graph": graph}+ restored = record_from_fact(fact_from_record(event), "websocket:context-test")+ projected = _client_projection_event(restored, augment_user_media=None,+ augment_assistant_media=None, augment_assistant_text=None)+ assert projected["context_graph"] == graph+++def test_explicit_skill_sources_in_current_message(tmp_path: Path):+ from nanobot.agent.context import ContextBuilder++ skill = tmp_path / 'skills' / 'example'+ skill.mkdir(parents=True)+ (skill / 'SKILL.md').write_text('---\nname: example\ndescription: Example\n---\n[Guide](references/guide.md)', encoding='utf-8')+ builder = ContextBuilder(tmp_path)+ block = builder.skills.build_explicit_skill_runtime_context('$example')+ assert block is not None+ graph = graph_from_build(lambda: builder.build_current_message('$example', runtime_context_blocks=[block]))+ nodes = {node['path']: node for node in graph['nodes']}+ assert nodes[str(skill / 'SKILL.md')]['state'] == 'loaded'+ assert nodes[str(skill / 'references/guide.md')]['state'] == 'discovered'+ assert graph['edges'] == [{'source': str(skill / 'SKILL.md'), 'target': str(skill / 'references/guide.md')}]+++async def test_queued_skill_sources_reach_the_request(tmp_path: Path):+ import asyncio+ from unittest.mock import AsyncMock, MagicMock++ from nanobot.agent.context import TranscriptInput+ from nanobot.agent.loop import AgentLoop+ from nanobot.agent.tools.context import RequestContext+ from nanobot.bus.events import InboundMessage+ from nanobot.bus.queue import MessageBus+ from nanobot.providers.base import LLMResponse++ skill = tmp_path / 'skills' / 'example'+ skill.mkdir(parents=True)+ (skill / 'SKILL.md').write_text('---\nname: example\ndescription: Example\n---\n[Guide](guide.md)', encoding='utf-8')+ provider = MagicMock()+ provider.get_default_model.return_value = 'test-model'+ provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content='Done', tool_calls=[], usage=None))+ loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model='test-model')+ loop.tools.get_definitions = MagicMock(return_value=[])+ session = await loop.sessions.state.get('websocket:skill-provenance')+ message = InboundMessage(channel='websocket', sender_id='user', chat_id='skill-provenance', content='$example')+ runtime = loop.llm_runtime()+ request = RequestContext(channel='websocket', chat_id='skill-provenance', session_key=session.key,+ runtime=runtime, original_user_text='$example')+ blocks = await loop._resolve_runtime_context_for_request(request, loop.tools)+ assert await loop._persist_user_message_early(message, session, runtime_context_blocks=blocks)+ expected_path = str(skill / 'SKILL.md')+ from nanobot.events import EventSink+ from nanobot.webui.context_source_hook import create_context_source_hook+ events = []+ async def publish(event):+ events.append(event)++ pending = asyncio.Queue()+ await pending.put(message)+ await loop._run_agent_loop(TranscriptInput(history=[{'role': 'user', 'content': 'Initial'}], current_message=None),+ runtime=runtime, session=session, request_context=request, pending_queue=pending,+ events=EventSink(publish), hook_factories=[create_context_source_hook])+ 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])+ 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']+++async def test_read_file_ignores_invalid_markdown_link_targets(tmp_path: Path):+ from nanobot.agent.tools.filesystem import ReadFileTool+ from nanobot.webui.context_observer import read_source++ path = tmp_path / "guide.md"+ path.write_text("[Invalid](foo%00.md)\n[Guide](valid.md)", encoding="utf-8")+ result = await ReadFileTool(workspace=tmp_path).execute(path=str(path))+ assert "[Invalid](foo%00.md)" in str(result)+ source = read_source({"name": "read_file", "phase": "end", "arguments": {"path": str(path)}, "result": result})+ assert source["links"] == [str(tmp_path / "valid.md")]+++def test_image_with_explicit_skill_reports_sources(tmp_path: Path):+ from nanobot.agent.context import ContextBuilder++ skill = tmp_path / "skills" / "example"+ skill.mkdir(parents=True)+ (skill / "SKILL.md").write_text("---\nname: example\ndescription: Example\n---\n[Guide](guide.md)")+ image = tmp_path / "image.png"+ image.write_bytes(bytes.fromhex("89504e470d0a1a0a") + b"image")+ 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)+ assert graph["nodes"][0]["state"] == "loaded"+ assert graph["edges"] == [{"source": str(skill / "SKILL.md"), "target": str(skill / "guide.md")}]diff --git a/tests/utils/test_webui_transcript.py b/tests/utils/test_webui_transcript.pyindex 96f356870..c2d9326f1 100644--- a/tests/utils/test_webui_transcript.py+++ b/tests/utils/test_webui_transcript.py@@ -1255,7 +1255,8 @@ def test_existing_shell_output_uses_canonical_command_identity_not_bang_text(his@pytest.mark.parametrize("phase", ["started", "completed", "failed", "cancelled"])-def test_model_request_persists_through_reconnect_projection(history, tmp_path, phase):[email protected]("measured", [False, True])+def test_model_request_persists_through_reconnect_projection(history, tmp_path, phase, measured):from nanobot.events import ModelRequestEventfrom nanobot.providers.base import LLMUsagefrom nanobot.session.manager import SessionManager@@ -1267,6 +1268,7 @@ def test_model_request_persists_through_reconnect_projection(history, tmp_path,projection = project_notification("requests", ModelRequestEvent(request_id="request", run_id="run", sequence=2, phase=phase,usage=usage, round_usages=(usage,) * 10, context_window_tokens=32000,+ request_usage=usage if measured else None,))assert projection is not Noneassert projection.persistence == "turn_activity"diff --git a/tests/webui/test_context_observer.py b/tests/webui/test_context_observer.pynew file mode 100644index 000000000..68304ed73--- /dev/null+++ b/tests/webui/test_context_observer.py@@ -0,0 +1,166 @@+import asyncio+import threading++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_sources import PromptSource+from nanobot.events import EventSink+from nanobot.file_references import REFERENCE_PARSERS, source_receipt+from nanobot.providers.base import ToolCallRequest+from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY+from nanobot.session.manager import SessionManager+from nanobot.webui.context_observer import ContextGraphObserver, read_source+from nanobot.webui.history import fact_from_record++EMPTY = {"nodes": [], "edges": []}+++def read_event(path, result, *, call_id="read-1", directory=None):+ return {"name": "read_file", "phase": "end", "call_id": call_id,+ "arguments": {"path": str(path)}, "result": result,+ "working_directory": str(directory) if directory is not None else None}+++async def test_observer_uses_only_returned_partial_text(tmp_path):+ path = tmp_path / "guide.md"+ path.write_text("[Visible](shown.md)\n[Hidden](unread.md)\n")+ result = await ReadFileTool(workspace=tmp_path).execute(path="guide.md", limit=1)+ path.unlink() # Observing a result must not depend on today's file contents.+ source = read_source(read_event("guide.md", result, directory=tmp_path))+ assert source["links"] == [str(tmp_path / "shown.md")]+ assert source["tokens"] == source_receipt(path, "[Visible](shown.md)")["tokens"]+++async def test_hook_captures_working_directory_at_start(tmp_path, monkeypatch):+ first, second = tmp_path / "first", tmp_path / "second"+ first.mkdir()+ second.mkdir()+ (first / "loop.py").write_text("print('first')")+ emitted = []++ async def publish(event):+ emitted.append(event)++ monkeypatch.chdir(first)+ hook = AgentProgressHook(EventSink(publish))+ call = ToolCallRequest("read", "read_file", {"path": "loop.py"})+ await hook.on_tool_execution_event(AgentHookContext(0, [], tool_calls=[call]))+ result = await ReadFileTool(workspace=first).execute(path="loop.py")+ monkeypatch.chdir(second)+ await hook.on_tool_execution_event(AgentHookContext(+ 0, [], tool_calls=[call], tool_results=[result], tool_events=[{"status": "ok"}],+ ))+ finished = emitted[-1]+ source = read_source(finished.tool_events[0])+ assert source["path"] == str(first / "loop.py")++[email protected]("prompt", [False, True])+async def test_analysis_runs_off_loop_and_failure_keeps_read_result(tmp_path, monkeypatch, prompt):+ entered = asyncio.Event()+ release = threading.Event()+ loop = asyncio.get_running_loop()++ class BrokenParser:+ def references(self, content):+ loop.call_soon_threadsafe(entered.set)+ assert release.wait(3)+ raise ValueError("bad parser")++ monkeypatch.setitem(REFERENCE_PARSERS, ".md", BrokenParser())+ path = tmp_path / "guide.md"+ path.write_text("[Guide](other.md)")+ # The tool succeeds before any graph parser runs.+ result = await ReadFileTool(workspace=tmp_path).execute(path=str(path))+ assert "1| [Guide](other.md)" in result+ event = read_event(path, result)+ observer = ContextGraphObserver(None)+ task = asyncio.create_task(+ observer.observe_prompt("chat", (PromptSource(path, "[Guide](other.md)"),), {}, persistent=False)+ if prompt else observer.observe_tools("chat", [event], {}, persistent=False)+ )+ try:+ await asyncio.wait_for(entered.wait(), 2)+ assert not task.done()+ finally:+ release.set()+ await task+ assert event["result"] == result+ assert await observer.snapshot("chat", {}, persistent=False) == EMPTY+++async def test_display_history_restores_reads_and_resets_at_compaction(tmp_path):+ sessions = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")+ session = await sessions.state.get("websocket:graph")+ metadata = {HISTORY_GENERATION_METADATA_KEY: session.generation}+ observer = ContextGraphObserver(sessions)++ async def persist(record):+ await sessions.state.append_history(session.key, [fact_from_record(record)], expected_generation=session.generation)++ try:+ event = read_event(tmp_path / "loop.py", "1| print('hello')\n\n(End of file — 1 lines total)")+ await observer.observe_tools("graph", [event], metadata, persistent=True)+ await persist({"event": "message", "kind": "progress", "tool_events": [event]})+ # A read is recoverable even if the run stops before the next model request.+ observer = ContextGraphObserver(sessions)+ initial = graph_from_sources([source_receipt(tmp_path / "SOUL.md", "Be precise")])+ await observer.observe_prompt("graph", (PromptSource(tmp_path / "SOUL.md", "Be precise"),), metadata, persistent=True)+ graph = await observer.snapshot("graph", metadata, persistent=True)+ assert {node["name"] for node in graph["nodes"]} == {"loop.py", "SOUL.md"}+ await persist({"event": "model_request", "context_graph": graph})+ # Repeated initial sources and a process restart do not inflate estimates.+ observer = ContextGraphObserver(sessions)+ assert await observer.snapshot("graph", metadata, persistent=True) == graph+ await observer.reset("graph", metadata, persistent=True)+ await persist({"event": "context_compaction", "phase": "succeeded", "compaction_id": "compact"})+ observer = ContextGraphObserver(sessions)+ await observer.observe_prompt("graph", (PromptSource(tmp_path / "SOUL.md", "Be precise"),), metadata, persistent=True)+ assert await observer.snapshot("graph", metadata, persistent=True) == initial+ finally:+ await sessions.state.aclose()+++async def test_partial_reads_deduplicate_calls_and_isolate_chats(tmp_path):+ observer = ContextGraphObserver(None)+ first = read_event(tmp_path / "loop.py", "1| first", call_id="a")+ second = read_event(tmp_path / "loop.py", "2| second", call_id="b")+ await observer.observe_tools("one", [first, first, second], {}, persistent=False)+ graph = await observer.snapshot("one", {}, persistent=False)+ assert graph["nodes"][0]["tokens"] == first["context_source"]["tokens"] + second["context_source"]["tokens"]+ assert await observer.snapshot("two", {}, persistent=False) == EMPTY+ observer.discard("one")+ assert await observer.snapshot("one", {}, persistent=False) == EMPTY++[email protected]("result,phase", [+ ("[File unchanged since last read: guide.md]", "end"),+ ("Error: File not found: guide.md", "error"),+])+async def test_non_read_results_keep_existing_graph(tmp_path, result, phase):+ observer = ContextGraphObserver(None)+ initial = graph_from_sources([source_receipt(tmp_path / "guide.md", "Original")])+ await observer.observe_prompt("chat", (PromptSource(tmp_path / "guide.md", "Original"),), {}, persistent=False)+ event = {**read_event(tmp_path / "guide.md", result), "phase": phase}+ await observer.observe_tools("chat", [event], {}, persistent=False)+ assert await observer.snapshot("chat", {}, persistent=False) == initial+++async def test_prompt_rebuild_deduplicates_files_and_compaction_refreshes_sources(tmp_path):+ observer = ContextGraphObserver(None)+ source = PromptSource(tmp_path / "AGENTS.md", "[Rules](rules.md)")+ await observer.observe_prompt("chat", (source, source), {}, persistent=False)+ expected = graph_from_sources([source_receipt(source.path, source.content)])+ assert await observer.snapshot("chat", {}, persistent=False) == expected+ await observer.observe_prompt("chat", (source,), {}, persistent=False)+ assert await observer.snapshot("chat", {}, persistent=False) == expected+ await observer.reset("chat", {}, persistent=False)+ refreshed = PromptSource(source.path, "[New rules](new.md)")+ await observer.observe_prompt("chat", (refreshed,), {}, persistent=False)+ assert await observer.snapshot("chat", {}, persistent=False) == graph_from_sources([+ source_receipt(refreshed.path, refreshed.content),+ ])diff --git a/webui/browser/context-graph-fixture.tsx b/webui/browser/context-graph-fixture.tsxnew file mode 100644index 000000000..99a15e9d5--- /dev/null+++ b/webui/browser/context-graph-fixture.tsx@@ -0,0 +1,39 @@+import { useState } from "react";+import { createRoot } from "react-dom/client";+import { ContextInspector } from "@/components/thread/ContextInspector";+import { ComposerUsagePopover } from "@/components/thread/ComposerUsagePopover";+import { TooltipProvider } from "@/components/ui/tooltip";+import { initializeI18n } from "@/i18n";+import type { ContextSnapshot } from "@/lib/types";+import "../src/globals.css";++const snapshots: ContextSnapshot[] = [+ { id: "first", contextWindowTokens: 10000, usage: { prompt_tokens: 1000 }, graph: {+ nodes: [{ path: "/a.md", name: "a.md", state: "loaded", tokens: 100 }], edges: [],+ } },+ { id: "second", contextWindowTokens: 10000, usage: { prompt_tokens: 2000 }, graph: {+ nodes: [{ path: "/a.md", name: "a.md", state: "loaded", tokens: 100 }, { path: "/b.md", name: "b.md", state: "discovered", tokens: 0 }],+ edges: [{ source: "/a.md", target: "/b.md" }],+ } },+];+const largeNodes = Array.from({ length: 500 }, (_, index) => ({ path: `/file-${index}.md`, name: `file-${index}.md`, state: "loaded" as const, tokens: 100 }));+const large: ContextSnapshot[] = [{ id: "large", contextWindowTokens: 100000, usage: { prompt_tokens: 50000 }, graph: {+ nodes: largeNodes, edges: largeNodes.slice(1).map((node, index) => ({ source: largeNodes[Math.floor(index / 2)].path, target: node.path })),+} }];+function Fixture() {+ const [showLarge, setShowLarge] = useState(false);+ const [pythonLoaded, setPythonLoaded] = useState(false);+ const frames = new URLSearchParams(location.search).has("single") ? snapshots.map((snapshot) => ({ ...snapshot, graph: snapshots[0].graph })) : snapshots;+ const inspectedFrames = pythonLoaded ? [...frames, { ...frames[1], id: "python", graph: {+ nodes: [...frames[1].graph.nodes, { path: "/worker.py", name: "worker.py", state: "loaded" as const, tokens: 200 }], edges: frames[1].graph.edges,+ } }] : frames;+ const [opened, setOpened] = useState("");+ const [sidebarHost, setSidebarHost] = useState<HTMLElement | null>(null);+ if (new URLSearchParams(location.search).has("drawer")) return <main ref={setSidebarHost} className="relative" style={{ height: "100dvh" }}>+ <ComposerUsagePopover sidebarHost={sidebarHost} context={null} rounds={[]} snapshots={frames} onOpenFile={setOpened} />+ <output>{opened}</output>+ </main>;+ return <main className="mx-auto max-w-2xl p-4"><ContextInspector context={null} rounds={[]} snapshots={showLarge ? large : inspectedFrames} onOpenFile={setOpened} /><output>{opened}</output>{new URLSearchParams(location.search).has("pair") && <section aria-label="Second graph"><ContextInspector context={null} rounds={[]} snapshots={frames} /></section>}<button onClick={() => setShowLarge(true)}>Load 500 nodes</button><button onClick={() => setPythonLoaded(true)}>Read Python file</button></main>;+}+await initializeI18n();+createRoot(document.getElementById("root")!).render(<TooltipProvider><Fixture /></TooltipProvider>);diff --git a/webui/browser/context-graph.html b/webui/browser/context-graph.htmlnew file mode 100644index 000000000..bd81f9e4e--- /dev/null+++ b/webui/browser/context-graph.html@@ -0,0 +1 @@+<!doctype html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width,initial-scale=1" /><title>Context graph interaction</title></head><body><div id="root"></div><script type="module" src="/browser/context-graph-fixture.tsx"></script></body></html>diff --git a/webui/browser/context-graph.spec.ts b/webui/browser/context-graph.spec.tsnew file mode 100644index 000000000..03ceb370b--- /dev/null+++ b/webui/browser/context-graph.spec.ts@@ -0,0 +1,205 @@+import { expect, test, type Locator } from "@playwright/test";++test.use({ reducedMotion: "reduce" });+async function dotWidth(canvas: Locator, x: number, y: number) {+ return canvas.evaluate((element: HTMLCanvasElement, point) => {+ const scale = element.width / element.getBoundingClientRect().width;+ const pixels = element.getContext("2d")!.getImageData(Math.round((point.x - 15) * scale), Math.round(point.y * scale), Math.round(30 * scale), 1).data;+ let painted = 0;+ for (let index = 3; index < pixels.length; index += 4) if (pixels[index] > 0) painted++;+ return painted / scale;+ }, { x, y });+}++test("graph keyboard controls, pointer hit targets, pixels and replay agree", async ({ page }) => {+ await page.goto("/browser/context-graph.html?single");+ const node = page.getByRole("button", { name: "a.md", exact: true });+ await expect(node).toBeAttached();+ await node.focus();+ await page.keyboard.press("Enter");+ await expect(page.getByText("About 100 tokens")).toBeVisible();+ await page.getByRole("button", { name: "Open file" }).click();+ await expect(page.locator("output")).toHaveText("/a.md");+ await page.keyboard.press("Escape");+ await expect(node).toBeFocused();+ await page.keyboard.press("Space");+ await expect(page.getByText("About 100 tokens")).toBeVisible();+ await page.keyboard.press("Escape");+ const canvas = page.locator("canvas");+ const box = (await canvas.boundingBox())!;+ let x = box.x + box.width / 2;+ const y = box.y + box.height / 2;+ await expect.poll(() => dotWidth(canvas, box.width / 2, box.height / 2)).toBeGreaterThan(0);+ const radiusBefore = await dotWidth(canvas, box.width / 2, box.height / 2);+ await page.mouse.move(x + 40, y);+ await page.mouse.wheel(0, -400);+ x += 40 - 40 * Math.exp(0.8);+ await expect.poll(() => dotWidth(canvas, x - box.x, box.height / 2)).toBeGreaterThan(0);+ expect(Math.abs(await dotWidth(canvas, x - box.x, box.height / 2) - radiusBefore)).toBeLessThanOrEqual(1);+ await page.mouse.click(x + 11, y);+ await expect(page.getByText("About 100 tokens")).toBeVisible();+ await page.keyboard.press("Escape");+ await page.mouse.click(x + 15, y);+ await expect(page.getByText("About 100 tokens")).toHaveCount(0);+ await page.mouse.move(x, y); await page.mouse.down();+ await page.mouse.move(x + 50, y + 30, { steps: 5 }); await page.mouse.up();+ await expect(page.getByText("About 100 tokens")).toHaveCount(0);+ await expect.poll(() => dotWidth(canvas, x - box.x + 50, box.height / 2 + 30)).toBeGreaterThan(0);+ const replay = page.getByRole("button", { name: "Play context history" });+ await replay.click();+ await expect(page.getByRole("progressbar")).toHaveAttribute("aria-valuenow", "10");+ await expect(replay).toBeDisabled();+ await expect(replay).toBeEnabled();+ await expect(page.getByRole("progressbar")).toHaveAttribute("aria-valuenow", "20");+});++test.describe("touch graph", () => {+ test.use({ viewport: { width: 390, height: 740 }, hasTouch: true });+ test("recovers batched drawer visibility, replays and opens a file by touch", async ({ page }) => {+ await page.addInitScript(() => {+ const NativeObserver = window.IntersectionObserver;+ window.IntersectionObserver = class extends NativeObserver {+ constructor(callback: IntersectionObserverCallback, options?: IntersectionObserverInit) {+ super((entries, observer) => {+ // Captured on a real drawer entrance under CPU throttling: the+ // offscreen record and subsequent onscreen record share a callback.+ const latest = entries[entries.length - 1];+ callback(latest.isIntersecting+ ? [{ ...latest, isIntersecting: false }, ...entries]+ : entries, observer);+ }, options);+ }+ };+ });+ await page.goto("/browser/context-graph.html?single&drawer");+ await page.getByTestId("composer-context-usage").tap();+ const canvas = page.locator("canvas");+ const box = (await canvas.boundingBox())!;+ await expect.poll(() => dotWidth(canvas, box.width / 2, box.height / 2)).toBeGreaterThan(0);+ const replay = page.getByRole("button", { name: "Play context history" });+ await replay.click();+ await expect(page.getByRole("progressbar")).toHaveAttribute("aria-valuenow", "10");+ await expect(replay).toBeEnabled();+ await expect(page.getByRole("progressbar")).toHaveAttribute("aria-valuenow", "20");+ const settledBox = (await canvas.boundingBox())!;+ await page.touchscreen.tap(settledBox.x + settledBox.width / 2, settledBox.y + settledBox.height / 2);+ const openFile = page.getByRole("button", { name: "Open file", exact: true });+ await expect(openFile).toBeVisible();+ await openFile.tap();+ await expect(page.locator("output")).toHaveText("/a.md");+ await expect(page.getByTestId("context-sidebar")).toHaveCount(0);+ });+ test("keeps a 44px touch target and redraws on theme changes", async ({ page }) => {+ await page.goto("/browser/context-graph.html?single");+ const node = page.getByRole("button", { name: "a.md", exact: true });+ await expect(node).toBeAttached();+ const canvas = page.locator("canvas");+ const box = (await canvas.boundingBox())!;+ await expect.poll(() => dotWidth(canvas, box.width / 2, box.height / 2)).toBeGreaterThan(0);+ const color = () => canvas.evaluate((element: HTMLCanvasElement) => Array.from(element.getContext("2d")!.getImageData(element.width / 2, element.height / 2, 1, 1).data));+ const before = await color();+ await page.evaluate(() => document.documentElement.classList.add("dark"));+ await expect.poll(color).not.toEqual(before);+ const x = box.x + box.width / 2, y = box.y + box.height / 2;+ await page.touchscreen.tap(x + 21, y);+ await expect(page.getByText("About 100 tokens")).toBeVisible();+ await page.getByRole("button", { name: "Open file" }).focus();+ await page.keyboard.press("Escape");+ await expect(node).toBeFocused();+ await page.touchscreen.tap(x + 23, y);+ await expect(page.getByText("About 100 tokens")).toHaveCount(0);+ });+});+++declare global {+ interface Window {+ graphDrawTrace: { arcs: number; frames: number; maxTask: number; start: number };+ pythonLabelPaints: number[];+ }+}++test.describe("normal-motion file loading", () => {+ test.use({ reducedMotion: "no-preference" });+ test("introduces a loaded Python filename after idle and again during fast history replay", async ({ page }) => {+ await page.addInitScript(() => {+ window.pythonLabelPaints = [];+ const fillText = CanvasRenderingContext2D.prototype.fillText;+ CanvasRenderingContext2D.prototype.fillText = function (...args) {+ if (args[0] === "worker.py") window.pythonLabelPaints.push(this.globalAlpha);+ return fillText.apply(this, args);+ };+ });+ await page.goto("/browser/context-graph.html?single");+ await expect(page.getByRole("button", { name: "a.md", exact: true })).toBeAttached();+ // Let the existing labels finish, then leave the stopped animation clock idle.+ await page.waitForTimeout(6500);+ await page.getByRole("button", { name: "Read Python file" }).click();+ await expect(page.getByRole("button", { name: "worker.py", exact: true })).toBeAttached();+ await expect.poll(() => page.evaluate(() => window.pythonLabelPaints.some((alpha) => alpha > 0.9))).toBe(true);+ await expect.poll(() => page.evaluate(() => {+ const alpha = window.pythonLabelPaints.at(-1) ?? 1;+ return alpha > 0 && alpha < 0.3;+ })).toBe(true);+ await page.waitForTimeout(700);+ const paints = await page.evaluate(() => window.pythonLabelPaints.length);+ await page.waitForTimeout(200);+ expect(await page.evaluate(() => window.pythonLabelPaints.length)).toBe(paints);+ await page.evaluate(() => { window.pythonLabelPaints = []; });+ await page.getByRole("button", { name: "Play context history" }).click();+ await expect.poll(() => page.evaluate(() => window.pythonLabelPaints.some((alpha) => alpha > 0.9))).toBe(true);+ });+});++test("500 reduced-motion nodes settle over multiple frames and are all painted", async ({ page }) => {+ await page.addInitScript(() => {+ window.graphDrawTrace = { arcs: 0, frames: 0, maxTask: 0, start: Infinity };+ const clear = CanvasRenderingContext2D.prototype.clearRect;+ CanvasRenderingContext2D.prototype.clearRect = function (...args) { window.graphDrawTrace.arcs = 0; return clear.apply(this, args); };+ const arc = CanvasRenderingContext2D.prototype.arc;+ CanvasRenderingContext2D.prototype.arc = function (...args) { window.graphDrawTrace.arcs++; return arc.apply(this, args); };+ const count = () => { window.graphDrawTrace.frames++; requestAnimationFrame(count); };+ requestAnimationFrame(count);+ new PerformanceObserver((entries) => {+ for (const entry of entries.getEntries()) if (entry.startTime >= window.graphDrawTrace.start) window.graphDrawTrace.maxTask = Math.max(window.graphDrawTrace.maxTask, entry.duration);+ }).observe({ entryTypes: ["longtask"] });+ });+ await page.goto("/browser/context-graph.html");+ await expect(page.getByRole("button", { name: "a.md", exact: true })).toBeAttached();+ await page.evaluate(() => { window.graphDrawTrace = { arcs: 0, frames: 0, maxTask: 0, start: performance.now() }; });+ await page.getByRole("button", { name: "Load 500 nodes" }).click();+ await expect(page.getByRole("button", { name: /^file-\d+\.md$/ })).toHaveCount(500);+ await expect.poll(() => page.evaluate(() => window.graphDrawTrace.arcs), { timeout: 15000 }).toBe(500);+ const trace = await page.evaluate(() => window.graphDrawTrace);+ expect(trace.frames).toBeGreaterThan(2);+ expect(trace.maxTask).toBeLessThan(100);+});+++test("node details do not pan their graph and dismiss when another graph is clicked", async ({ page }) => {+ await page.goto("/browser/context-graph.html?single&pair");+ const firstNode = page.getByRole("button", { name: "a.md", exact: true }).first();+ const firstCanvas = page.locator("canvas").first();+ const box = (await firstCanvas.boundingBox())!;+ await expect.poll(() => dotWidth(firstCanvas, box.width / 2, box.height / 2)).toBeGreaterThan(0);+ await page.mouse.move(box.x + 8, box.y + 8); await page.mouse.down();+ await page.mouse.move(box.x + 58, box.y + 8); await page.mouse.up();+ await expect.poll(() => dotWidth(firstCanvas, box.width / 2 + 50, box.height / 2)).toBeGreaterThan(0);+ await firstNode.focus();+ await page.keyboard.press("Enter");+ const details = page.getByText("About 100 tokens");+ await expect(details).toBeVisible();+ await details.click();+ await expect(details).toBeVisible();+ await details.dblclick();+ await expect(details).toBeVisible();+ expect(await dotWidth(firstCanvas, box.width / 2 + 50, box.height / 2)).toBeGreaterThan(0);+ const secondCanvas = page.getByRole("region", { name: "Second graph" }).locator("canvas");+ await secondCanvas.click({ position: { x: 8, y: 8 } });+ await expect(details).toHaveCount(0);+ await firstNode.focus();+ await page.keyboard.press("Enter");+ await expect(details).toBeVisible();+ await page.keyboard.press("Enter");+ await expect(details).toHaveCount(0);+});diff --git a/webui/browser/history-boundary.spec.ts b/webui/browser/history-boundary.spec.tsindex 2f5aa9cf3..713181255 100644--- a/webui/browser/history-boundary.spec.ts+++ b/webui/browser/history-boundary.spec.ts@@ -715,8 +715,8 @@ for (const elapsedMs of [0, 80]) test(`fast responses reclaim completed slots anawait completePrepend(history, body, "Question 16", "Question 28", nextHeld.anchorTop);await expect(body.locator(".thread-history-slot")).toHaveCount(0);expect(history.reads).toEqual([- "?limit=120&before=40&include_model_requests=1",- "?limit=120&before=28&include_model_requests=1",+ "?limit=120&before=40&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=120&before=28&include_model_requests=1&context_graph_encoding=references-v1",]);});@@ -924,10 +924,10 @@ test("navigation-window loading and errors remain visible and retry uses the navawait positionAtTop(body);await expect(page.locator('.thread-history-status[data-state="loading"]')).toHaveCount(0);expect(history.reads).toEqual([- "?limit=24&after=38&include_model_requests=1",- "?limit=24&after=50&include_model_requests=1",- "?limit=24&before=38&include_model_requests=1",- "?limit=24&before=38&include_model_requests=1",+ "?limit=24&after=38&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=24&after=50&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=24&before=38&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=24&before=38&include_model_requests=1&context_graph_encoding=references-v1",]);});@@ -972,8 +972,8 @@ test("failed Blocks animate without visible error text; pulling retries once andexpect((await historyGeometry(body, "Question 40")).slotBeforeKey).toBe("u40");await expectCoordinates(body, "Question 40", held);expect(history.reads).toEqual([- "?limit=120&before=40&include_model_requests=1",- "?limit=120&before=40&include_model_requests=1",+ "?limit=120&before=40&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=120&before=40&include_model_requests=1&context_graph_encoding=references-v1",]);history.complete();@@ -1015,9 +1015,9 @@ test("cross-path unloaded rail jump has visible navigation feedback outside a scawait expect.poll(() => history.reads.length).toBe(3);await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeInViewport();expect(history.reads).toEqual([- "?limit=120&before=40&include_model_requests=1",- "?limit=24&after=10&include_model_requests=1",- "?limit=24&after=10&include_model_requests=1",+ "?limit=120&before=40&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=24&after=10&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=24&after=10&include_model_requests=1&context_graph_encoding=references-v1",]);history.complete();await expect(body.getByText("Question 10", { exact: true })).toBeInViewport();@@ -1060,10 +1060,10 @@ test("cross-path newer has visible navigation feedback and forward input retriesawait expect.poll(() => history.reads.length).toBe(4);await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeInViewport();expect(history.reads).toEqual([- "?limit=24&after=10&include_model_requests=1",- "?limit=24&before=10&include_model_requests=1",- "?limit=24&after=22&include_model_requests=1",- "?limit=24&after=22&include_model_requests=1",+ "?limit=24&after=10&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=24&before=10&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=24&after=22&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=24&after=22&include_model_requests=1&context_graph_encoding=references-v1",]);history.complete();await expect(body.getByText("Question 33", { exact: true })).toBeAttached();@@ -1109,8 +1109,8 @@ test("cross-path older errors never float after latest or a loaded rail jump, buawait retry.click();await expect.poll(() => history.reads.length).toBe(initialReads + 2);expect(history.reads.slice(initialReads)).toEqual([- "?limit=120&before=40&include_model_requests=1",- "?limit=120&before=40&include_model_requests=1",+ "?limit=120&before=40&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=120&before=40&include_model_requests=1&context_graph_encoding=references-v1",]);history.complete();await expect(body.getByText("Question 28", { exact: true })).toBeAttached();@@ -1202,9 +1202,9 @@ test("bounded navigation retains three pages and reclaims each completed wheel oawait expectAnchorCoordinate(body, "Question 26", secondHeld.anchorTop);expect((await historyGeometry(body, "Question 26")).slotBeforeKey).toBeNull();expect(history.reads).toEqual([- "?limit=24&after=38&include_model_requests=1",- "?limit=24&before=38&include_model_requests=1",- "?limit=24&before=26&include_model_requests=1",+ "?limit=24&after=38&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=24&before=38&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=24&before=26&include_model_requests=1&context_graph_encoding=references-v1",]);const atNewHead = await approachNextHead("Question 14");@@ -1229,10 +1229,10 @@ test("bounded navigation retains three pages and reclaims each completed wheel oawait expect(header).toHaveCount(0);await expect(page.getByText("No earlier messages", { exact: true })).toHaveCount(0);expect(history.reads).toEqual([- "?limit=24&after=38&include_model_requests=1",- "?limit=24&before=38&include_model_requests=1",- "?limit=24&before=26&include_model_requests=1",- "?limit=24&before=14&include_model_requests=1",+ "?limit=24&after=38&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=24&before=38&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=24&before=26&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=24&before=14&include_model_requests=1&context_graph_encoding=references-v1",]);const atKeyboardHead = await approachNextHead("Question 2");@@ -1261,11 +1261,11 @@ test("bounded navigation retains three pages and reclaims each completed wheel oawait expect(body.getByText("Question 26", { exact: true })).toHaveCount(0);await expect(body.locator('[data-thread-display-unit^="u"]')).toHaveCount(26);expect(history.reads).toEqual([- "?limit=24&after=38&include_model_requests=1",- "?limit=24&before=38&include_model_requests=1",- "?limit=24&before=26&include_model_requests=1",- "?limit=24&before=14&include_model_requests=1",- "?limit=24&before=2&include_model_requests=1",+ "?limit=24&after=38&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=24&before=38&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=24&before=26&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=24&before=14&include_model_requests=1&context_graph_encoding=references-v1",+ "?limit=24&before=2&include_model_requests=1&context_graph_encoding=references-v1",]);});diff --git a/webui/browser/mobile-chat-layout.spec.ts b/webui/browser/mobile-chat-layout.spec.tsindex 5fda9927c..6cc7832b4 100644--- a/webui/browser/mobile-chat-layout.spec.ts+++ b/webui/browser/mobile-chat-layout.spec.ts@@ -26,7 +26,7 @@ for (const { width, dark } of [{ width: 360, dark: false }, { width: 314, dark:await usage.click();const details = page.getByRole("dialog", { name: "Context usage" });- await expect(details.getByRole("progressbar", { name: "Context 22%" })).toHaveAttribute("aria-valuenow", "22");+ await expect(details.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "22");await page.keyboard.press("Escape");await expect(usage).toBeFocused();diff --git a/webui/browser/prompt-rail.spec.ts b/webui/browser/prompt-rail.spec.tsindex 2d11bb04e..755a4f74b 100644--- a/webui/browser/prompt-rail.spec.ts+++ b/webui/browser/prompt-rail.spec.ts@@ -52,21 +52,21 @@ test("complete rail scrolls independently, jumps to unloaded history and returnsawait expect(first).toBeFocused();await first.press("Enter");await expect(body.getByText("Question 0", { exact: true })).toBeInViewport();- expect(reads).toEqual(["?limit=24&after=0&include_model_requests=1"]);+ expect(reads).toEqual(["?limit=24&after=0&include_model_requests=1&context_graph_encoding=references-v1"]);await expect(body.getByText("Question 1999", { exact: true })).toHaveCount(0);// Force input-before-scroll ordering instead of relying on compositor timing.await body.evaluate((node) => node.addEventListener("wheel", () => undefined, { passive: false }));for (const after of [10, 20, 30, 40]) {await body.hover();await page.mouse.wheel(0, 10000);- await expect.poll(() => reads.some((query) => query === `?limit=24&after=${after}&include_model_requests=1`)).toBe(true);+ await expect.poll(() => reads.some((query) => query === `?limit=24&after=${after}&include_model_requests=1&context_graph_encoding=references-v1`)).toBe(true);await expect(body.getByText(`Question ${after + 9}`, { exact: true })).toBeAttached();}expect(await body.locator("[data-user-prompt-id]").count()).toBeLessThanOrEqual(30);await body.hover();await page.mouse.wheel(0, -100000);await expect.poll(() => reads.some((query) => (- query.startsWith("?limit=24&before=") && query.endsWith("&include_model_requests=1")+ query.startsWith("?limit=24&before=") && query.endsWith("&include_model_requests=1&context_graph_encoding=references-v1")))).toBe(true);await page.getByRole("button", { name: "Scroll to bottom" }).click();await expect(body.getByText("Question 1999", { exact: true })).toBeVisible();diff --git a/webui/browser/skeleton-additions-fixture.tsx b/webui/browser/skeleton-additions-fixture.tsxindex 02315c9c5..6f59f655b 100644--- a/webui/browser/skeleton-additions-fixture.tsx+++ b/webui/browser/skeleton-additions-fixture.tsx@@ -137,7 +137,7 @@ function SkeletonSurface() {: surface === "automations" ? <AutomationsSettings payload={empty ? null : { jobs }} loading={loading} filter="all" actionKey={null} error={state === "error" ? "Preview read failed" : null}onFilterChange={noop} onAction={noop} onRequestEdit={noop} onRequestDelete={noop} />: surface === "skill-detail" ? <SkillsCatalogSettings skills={[skill]} />- : surface === "session-jobs" ? <SessionInfoPopoverView title="Project review" jobs={empty ? [] : jobs} loading={loading} loadFailed={state === "error"} now={now}+ : surface === "session-jobs" ? <SessionInfoPopoverView jobs={empty ? [] : jobs} loading={loading} loadFailed={state === "error"} now={now}onAction={async () => jobs} onEdit={async () => jobs} />: surface === "linear-members" ? <LinearMemberAccessView snapshot={{ payload: empty ? null : members, loading, error: state === "error" ? "Preview read failed" : null, saves: {} }} onLoad={noop} onSetAllowed={noop} /> : null}</main>}diff --git a/webui/browser/skeleton-layout.spec.ts b/webui/browser/skeleton-layout.spec.tsindex e66842c2c..d51d7b852 100644--- a/webui/browser/skeleton-layout.spec.ts+++ b/webui/browser/skeleton-layout.spec.ts@@ -202,7 +202,7 @@ for (const width of [390, 1440]) {await page.goto(fixture("file", true));sameBox(await box(status(page).locator(".font-mono")), source);const line = await box(status(page).locator(".font-mono > div > :last-child").first());- expect(line.x).toBe(code.x);+ expect(line.x).toBeCloseTo(code.x, 1);await noOverflow(page);await page.goto(fixture("markdown"));const heading = await box(page.getByRole("heading", { name: "Project overview" }));@@ -216,7 +216,7 @@ for (const width of [390, 1440]) {await noOverflow(page);await page.goto(fixture("markdown"));await expect(page.getByRole("heading", { name: "Project overview" })).toBeVisible();- await page.getByTestId("file-preview-panel").locator(".segmented-control button").nth(1).click();+ await page.getByTestId("file-preview-panel").getByRole("button", { name: locale === "en" ? "Source" : "原文", exact: true }).click();await expect(page.getByTestId("viewport-code-rows")).toBeVisible();const markdownSource = await box(page.locator("pre"));await page.getByTestId("reload-preview").click();diff --git a/webui/browser/theme-toggle-fixture.tsx b/webui/browser/theme-toggle-fixture.tsxindex 11db63275..149de612f 100644--- a/webui/browser/theme-toggle-fixture.tsx+++ b/webui/browser/theme-toggle-fixture.tsx@@ -62,7 +62,7 @@ function ThemeChatFixture({ theme, toggle }: { theme: "light" | "dark"; toggle:<ThreadViewport messages={messages} isStreaming={false} conversationKey={activeKey}navigationFrame={context.navigationFrame} composer={null} /><ThreadHistoryStatus loading={false} error={null} exhausted onRetry={noop} />- {context.composerPortalTarget && createPortal(composer, context.composerPortalTarget)}+ {context.composerPortalTarget && createPortal(<div data-active-composer>{composer}</div>, context.composerPortalTarget)}</div>} /></div></main>;diff --git a/webui/browser/typography.spec.ts b/webui/browser/typography.spec.tsindex b60f2834b..2a0bae282 100644--- a/webui/browser/typography.spec.ts+++ b/webui/browser/typography.spec.ts@@ -66,7 +66,16 @@ for (const narrow of [false, true]) {for (const selector of ["table", "th", "td"]) {expect((await metrics(page.locator(`.markdown-content ${selector}`).first())).size).toBeCloseTo(bodySize * 0.875);}- expect(await tables.first().evaluate(node => node.scrollWidth <= node.clientWidth + 1)).toBe(true);+ // Wide tables scroll within their wrapper instead of squeezing words into single letters.+ const textTable = tables.first();+ await expect(textTable).toHaveCSS("overflow-x", "auto");+ await textTable.evaluate(node => { node.scrollLeft = node.scrollWidth; });+ expect(await textTable.evaluate(node => {+ const bounds = node.getBoundingClientRect();+ const lastCell = node.querySelector("tbody td:last-child")!.getBoundingClientRect();+ return lastCell.right <= bounds.right + 1 && lastCell.right > bounds.left;+ })).toBe(true);+ await textTable.evaluate(node => { node.scrollLeft = 0; });await expect.poll(() => formulaTable.locator(".katex-html > .base").evaluateAll((nodes) => nodes.every((node) => {const formula = node.getBoundingClientRect();const cell = node.closest("th, td")!;diff --git a/webui/bun.lock b/webui/bun.lockindex 6869922a7..2d75ce8cb 100644--- a/webui/bun.lock+++ b/webui/bun.lock@@ -16,6 +16,7 @@"class-variance-authority": "^0.7.1","clsx": "^2.1.1","css-tree": "3.1.0",+ "d3-force": "^3.0.1","diff": "^9.0.0","i18next": "^26.0.6","lucide-react": "^0.469.0",@@ -48,6 +49,7 @@"@testing-library/react": "^16.1.0","@testing-library/user-event": "^14.5.2","@types/css-tree": "^2.3.10",+ "@types/d3-force": "^3.0.10","@types/mdast": "^4.0.4","@types/node": "^24.0.0","@types/qrcode": "^1.5.6",@@ -370,6 +372,8 @@"@types/css-tree": ["@types/[email protected]", "", {}, "sha512-aEokibJOI77uIlqoBOkVbaQGC9zII0A+JH1kcTNKW2CwyYWD8KM6qdo+4c77wD3wZOQfJuNWAr9M4hdk+YhDIg=="],+ "@types/d3-force": ["@types/[email protected]", "", {}, "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw=="],+"@types/debug": ["@types/[email protected]", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="],"@types/esrecurse": ["@types/[email protected]", "", {}, "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw=="],@@ -530,6 +534,14 @@"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],+ "d3-dispatch": ["[email protected]", "", {}, "sha512-sAzH4Y4nsLo8eSqw5jKiZt+LU2wZmL/qS+OkxQGjhwazB/D7TY34R/QK1eshfGr7cZEKymKZ/Haem7m+lu98Sg=="],++ "d3-force": ["[email protected]", "", { "dependencies": { "d3-dispatch": "1 - 3", "d3-quadtree": "1 - 3", "d3-timer": "1 - 3" } }, "sha512-kAaaHLFebBYwgi5cYBXAI8vKrQFMCD2MEswj2QuPKKbdU1wYLc8WXtS7O8F/b6POCIe3gJjY6hkDstHi1yMETQ=="],++ "d3-quadtree": ["[email protected]", "", {}, "sha512-9Lu9mqJKRbIk0d6mKDjpvPURaPdwHVK5CYbcdd0/4vBgz4ldz/7TIOse3kNERsByGNfld58KEco507AztJWyTQ=="],++ "d3-timer": ["[email protected]", "", {}, "sha512-1Il1aliroVSErrv5aulRBxAY+7+DnaoLIWGd1C6SsBTWDeobWiP/V69vwb8vT6abR1kKwaNe1196pmaQ1fK90A=="],+"debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],"decamelize": ["[email protected]", "", {}, "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA=="],diff --git a/webui/package-lock.json b/webui/package-lock.jsonindex deb489574..12ba0e19d 100644--- a/webui/package-lock.json+++ b/webui/package-lock.json@@ -19,6 +19,7 @@"class-variance-authority": "^0.7.1","clsx": "^2.1.1","css-tree": "3.1.0",+ "d3-force": "^3.0.1","diff": "^9.0.0","i18next": "^26.0.6","lucide-react": "^0.469.0",@@ -51,6 +52,7 @@"@testing-library/react": "^16.1.0","@testing-library/user-event": "^14.5.2","@types/css-tree": "^2.3.10",+ "@types/d3-force": "^3.0.10","@types/mdast": "^4.0.4","@types/node": "^24.0.0","@types/qrcode": "^1.5.6",@@ -2519,6 +2521,13 @@"dev": true,"license": "MIT"},+ "node_modules/@types/d3-force": {+ "version": "3.0.10",+ "resolved": "https://registry.npmjs.org/@types/d3-force/-/d3-force-3.0.10.tgz",+ "integrity": "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/debug": {"version": "4.1.13","license": "MIT",@@ -3532,6 +3541,47 @@"devOptional": true,"license": "MIT"},+ "node_modules/d3-dispatch": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.2.tgz",+ "integrity": "sha512-sAzH4Y4nsLo8eSqw5jKiZt+LU2wZmL/qS+OkxQGjhwazB/D7TY34R/QK1eshfGr7cZEKymKZ/Haem7m+lu98Sg==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-force": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-force/-/d3-force-3.0.1.tgz",+ "integrity": "sha512-kAaaHLFebBYwgi5cYBXAI8vKrQFMCD2MEswj2QuPKKbdU1wYLc8WXtS7O8F/b6POCIe3gJjY6hkDstHi1yMETQ==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-quadtree": "1 - 3",+ "d3-timer": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-quadtree": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-3.0.2.tgz",+ "integrity": "sha512-9Lu9mqJKRbIk0d6mKDjpvPURaPdwHVK5CYbcdd0/4vBgz4ldz/7TIOse3kNERsByGNfld58KEco507AztJWyTQ==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-timer": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.2.tgz",+ "integrity": "sha512-1Il1aliroVSErrv5aulRBxAY+7+DnaoLIWGd1C6SsBTWDeobWiP/V69vwb8vT6abR1kKwaNe1196pmaQ1fK90A==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/debug": {"version": "4.4.3","license": "MIT",diff --git a/webui/package.json b/webui/package.jsonindex 330a2fa7f..4bf433bab 100644--- a/webui/package.json+++ b/webui/package.json@@ -29,6 +29,7 @@"class-variance-authority": "^0.7.1","clsx": "^2.1.1","css-tree": "3.1.0",+ "d3-force": "^3.0.1","diff": "^9.0.0","i18next": "^26.0.6","lucide-react": "^0.469.0",@@ -61,6 +62,7 @@"@testing-library/react": "^16.1.0","@testing-library/user-event": "^14.5.2","@types/css-tree": "^2.3.10",+ "@types/d3-force": "^3.0.10","@types/node": "^24.0.0","@types/mdast": "^4.0.4","@types/qrcode": "^1.5.6",diff --git a/webui/src/components/CodeBlock.tsx b/webui/src/components/CodeBlock.tsxindex 4326e282c..af4538910 100644--- a/webui/src/components/CodeBlock.tsx+++ b/webui/src/components/CodeBlock.tsx@@ -59,7 +59,7 @@ const LazyHighlightedCode = lazy(async () => {customStyle={{background: "transparent",margin: 0,- padding: chrome === "none" ? "0.75rem 1rem" : "1rem 3.5rem 1rem 1.25rem",+ padding: viewportHighlight ? "0.75rem 1rem 0.75rem 0.5rem" : chrome === "none" ? "0.75rem 1rem" : "1rem 3.5rem 1rem 1.25rem",fontFamily: "inherit",fontSize: "inherit",lineHeight: "inherit",@@ -134,7 +134,7 @@ function CodeTextBlock({showLineNumbers ? "whitespace-pre" : "whitespace-pre-wrap",chrome === "default"? "py-4 pl-5 pr-14"- : compact ? "px-4 py-3" : "p-3",+ : compact ? "py-3 pl-2 pr-4" : "p-3",className,)}data-testid={testId}@@ -143,7 +143,7 @@ function CodeTextBlock({{showLineNumbers && compact ? (<span className="flex min-w-max"><span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground"- style={{ minWidth: "4.25em" }}>{lines.map((_, index) => index + 1).join("\n")}</span>+ style={{ minWidth: `calc(${String(lines.length).length}ch + 1.15rem)` }}>{lines.map((_, index) => index + 1).join("\n")}</span><span>{renderText(code)}</span></span>) : showLineNumbers ? (diff --git a/webui/src/components/FilePreviewPanelView.tsx b/webui/src/components/FilePreviewPanelView.tsxindex 5dc7de6d2..b2d9422b2 100644--- a/webui/src/components/FilePreviewPanelView.tsx+++ b/webui/src/components/FilePreviewPanelView.tsx@@ -1,10 +1,12 @@-import { useState } from "react";+import { surfaceFocusProps } from "@/lib/surface-focus";+import { useContext, useState } from "react";+import { createPortal } from "react-dom";+import { SidebarPanelActionsContext } from "@/components/ui/sidebar-panel";import { useTranslation } from "react-i18next";import { AlertCircle } from "lucide-react";import { CodeBlock } from "@/components/CodeBlock";import { MarkdownText } from "@/components/MarkdownText";-import { SegmentedControl } from "@/components/ui/segmented-control";import { ImageLightbox } from "@/components/ImageLightbox";import { fileKindForPath, splitFilePath } from "@/components/FileReferenceChip";import type { FilePreviewPayload } from "@/lib/types";@@ -23,6 +25,7 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChangeonOpenFilePreview?: (path: string) => void;}) {const { t } = useTranslation();+ const actionsHost = useContext(SidebarPanelActionsContext);const [mode, setMode] = useState<"preview" | "source">("preview");const previewKind = fileKindForPath(path);const markdown = state.status === "ready" && state.payload.kind !== "image"@@ -38,17 +41,18 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange: state.message ?? t("filePreview.failed", { defaultValue: "Could not preview this file." })): null;+ const modeLabel = t(mode === "preview" ? "filePreview.source" : "filePreview.preview");+ const modeControl = <button type="button" onClick={() => setMode(value => value === "preview" ? "source" : "preview")}+ className="touch-target inline-flex h-8 items-center justify-center rounded-control px-3 text-xs text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ {modeLabel}+ </button>;+return (<section aria-label={t("filePreview.aria")} data-testid="file-preview-panel" className="flex min-h-0 flex-1 flex-col">- {markdown ? (- <div className="flex shrink-0 items-center justify-end px-4 py-2">- <SegmentedControl value={mode} onChange={setMode} ariaLabel={t("filePreview.displayMode")}- options={[{ value: "preview", label: t("filePreview.preview") }, { value: "source", label: t("filePreview.source") }]}- itemClassName="px-3 [@media(pointer:coarse)]:min-h-9" />- </div>- ) : null}+ {markdown && (actionsHost ? createPortal(modeControl, actionsHost) : <div className="flex shrink-0 justify-end px-4 py-2">{modeControl}</div>)}<div key={mode} data-file-preview-scroll tabIndex={0}- className="min-h-0 flex-1 overflow-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/60">+ {...surfaceFocusProps}+ className="min-h-0 flex-1 overflow-auto outline-none data-[keyboard-focus]:ring-2 data-[keyboard-focus]:ring-inset data-[keyboard-focus]:ring-ring/60">{state.status === "loading" ? (<div role="status" aria-label={t("filePreview.loading", { defaultValue: "Loading preview..." })}className="h-full" aria-busy="true">@@ -57,9 +61,9 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange{previewKind === "image" ? <div className="flex h-full items-center justify-center p-4"><div className="aspect-[8/5] w-full max-w-sm rounded-compact bg-muted/40" /></div> : <>- {previewKind === "markdown" ? <div className="flex justify-end px-4 py-2">- <div className="inline-flex min-h-8 items-center gap-1 rounded-full bg-muted/40 p-1 text-ui-label">- {[t("filePreview.preview"), t("filePreview.source")].map((label) => <span key={label} className="invisible px-3 py-1 [@media(pointer:coarse)]:min-h-9">{label}</span>)}+ {previewKind === "markdown" && !actionsHost ? <div className="flex justify-end px-4 py-2">+ <div className="touch-target inline-flex h-8 items-center rounded-control bg-muted/40 px-3 text-xs">+ <span className="invisible">{modeLabel}</span></div></div> : null}{previewKind === "markdown" && mode === "preview" ? <div className="markdown-content px-5 pb-6 pt-1 sm:px-6">@@ -67,10 +71,10 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange{["w-full", "w-5/6", "w-3/4"].map((width) => <div key={width} className="mt-4 flex h-[1lh] items-center"><div className={`h-3 rounded bg-muted/40 ${width}`} /></div>)}- </div> : <div className="px-4 py-3 font-mono text-code">+ </div> : <div className="py-3 pl-2 pr-4 font-mono text-code">{["w-2/3", "w-full", "w-5/6", "w-3/4", "w-1/2", "w-3/5"].map((width) => <div key={width} className="flex h-[1lh] items-center">- <div className="w-[4.25em] shrink-0 pr-[1.15rem]"><div className="ml-auto h-3 w-2 rounded bg-muted/40" /></div>- <div className={`h-3 max-w-[calc(100%-4.25em)] rounded bg-muted/40 ${width}`} />+ <div className="w-[calc(1ch+1.15rem)] shrink-0 pr-[1.15rem]"><div className="ml-auto h-3 w-2 rounded bg-muted/40" /></div>+ <div className={`h-3 max-w-[calc(100%-1ch-1.15rem)] rounded bg-muted/40 ${width}`} /></div>)}</div>}</>}diff --git a/webui/src/components/MarkdownTextRenderer.tsx b/webui/src/components/MarkdownTextRenderer.tsxindex fab55ea69..7384ffa66 100644--- a/webui/src/components/MarkdownTextRenderer.tsx+++ b/webui/src/components/MarkdownTextRenderer.tsx@@ -1,3 +1,4 @@+import { surfaceFocusProps } from "@/lib/surface-focus";import {Children,isValidElement,@@ -686,7 +687,7 @@ export default function MarkdownTextRenderer({void _node;return (<div- data-testid="markdown-data-table"+ data-testid="markdown-data-table" {...surfaceFocusProps}data-table-kind="data"role="region"tabIndex={0}@@ -694,7 +695,7 @@ export default function MarkdownTextRenderer({className={cn("not-prose mb-5 mt-3 w-full max-w-full overflow-x-auto rounded-lg","border border-border/65 bg-muted/20",- "overscroll-x-contain focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ "overscroll-x-contain outline-none data-[keyboard-focus]:ring-2 data-[keyboard-focus]:ring-ring",)}><table@@ -703,9 +704,9 @@ export default function MarkdownTextRenderer({"[&_thead]:bg-muted/45 [&_thead]:text-muted-foreground","[&_th]:border-b [&_th]:border-border/65 [&_th]:px-3 [&_th]:py-2","[&_th]:text-left [&_th]:font-medium [&_th]:whitespace-normal",- "[&_th]:[overflow-wrap:anywhere]",+ "[&_th]:[overflow-wrap:normal]","[&_td]:border-b [&_td]:border-border/55 [&_td]:px-3 [&_td]:py-2",- "[&_td]:whitespace-normal [&_td]:[overflow-wrap:anywhere]",+ "[&_td]:whitespace-normal [&_td]:[overflow-wrap:normal]","[&_th:not(:last-child)]:border-r [&_th:not(:last-child)]:border-border/45","[&_td:not(:last-child)]:border-r [&_td:not(:last-child)]:border-border/45","[&_tbody_tr:last-child_td]:border-b-0",diff --git a/webui/src/components/MessageBubble.tsx b/webui/src/components/MessageBubble.tsxindex 1cdf852a9..322b6fdab 100644--- a/webui/src/components/MessageBubble.tsx+++ b/webui/src/components/MessageBubble.tsx@@ -503,7 +503,7 @@ export function MessageBubble({"text-left text-reading whitespace-pre-wrap [overflow-wrap:anywhere]",temporary? "border border-dashed border-muted-foreground/40 bg-transparent"- : "bg-secondary/70",+ : "user-message-surface bg-secondary/70",)}>{messageText}diff --git a/webui/src/components/PreviewPane.tsx b/webui/src/components/PreviewPane.tsxindex add566d98..777f19509 100644--- a/webui/src/components/PreviewPane.tsx+++ b/webui/src/components/PreviewPane.tsx@@ -1,4 +1,6 @@-import { useEffect, useId, useRef, useState, type CSSProperties, type PointerEvent, type ReactNode } from "react";+import { surfaceFocusProps } from "@/lib/surface-focus";+import { useEffect, useId, useRef, type PointerEvent, type ReactNode } from "react";+import { SidebarPanel } from "@/components/ui/sidebar-panel";import { PanelRightClose, X } from "lucide-react";import { useTranslation } from "react-i18next";import { FileReferenceIcon, fileKindForPath, splitFilePath } from "@/components/FileReferenceChip";@@ -6,6 +8,7 @@ import { FileActions } from "@/components/FileActions";import { SidebarSelectionHighlight, SIDEBAR_SELECTION_ITEM_CLASS } from "@/components/SidebarSelectionHighlight";import type { PreviewTab } from "@/hooks/useFilePreviewState";import { cn } from "@/lib/utils";+import { sidePanelSurfaceClassName } from "@/components/ui/floating-surface";/** One stable sidebar shell: switching targets never replays its opening animation. */export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onCloseTab, onClose, onResizeStart, children }: {@@ -21,14 +24,9 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos}) {const { t } = useTranslation();const id = useId();- const [entered, setEntered] = useState(false);const buttons = useRef(new Map<string, HTMLButtonElement>());const tabList = useRef<HTMLDivElement>(null);const pendingFocus = useRef<string | null>(null);- useEffect(() => {- const frame = requestAnimationFrame(() => setEntered(true));- return () => cancelAnimationFrame(frame);- }, []);useEffect(() => {const revealActiveTab = () => buttons.current.get(activeId)?.parentElement?.scrollIntoView?.({ block: "nearest", inline: "nearest" });revealActiveTab();@@ -48,29 +46,18 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClosonCloseTab(tab.id);};const iconButton = "touch-target inline-flex size-8 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";- return <aside aria-label={t("previewTabs.title")} data-testid="preview-pane" data-file-preview-panel- style={{- "--file-preview-width": `${width}px`,- "--file-preview-slot-width": !entered || isClosing ? "0px" : `${width}px`,- "--file-preview-mobile-width": !entered || isClosing ? "0px" : "100%",- } as CSSProperties}- className={cn("file-preview-pane absolute inset-y-0 right-0 z-30 w-[var(--file-preview-mobile-width)] overflow-hidden transition-[width] duration-300 ease-out motion-reduce:transition-none", isClosing && "pointer-events-none")}- >- <div className={cn("file-preview-content absolute inset-y-0 right-0 flex w-[100cqw] flex-col border-l border-border/60 bg-background pb-[env(safe-area-inset-bottom)] transition-opacity duration-200 motion-reduce:transition-none", !entered || isClosing ? "opacity-0" : "opacity-100")}>- <button type="button" aria-label={t("filePreview.resize")} onPointerDown={onResizeStart}- className="file-preview-resize group absolute inset-y-0 left-0 z-20 hidden w-2 cursor-col-resize touch-none justify-start focus-visible:outline-none">- <span aria-hidden className="h-full w-px bg-foreground/25 opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100" />- </button>- <div className="flex min-h-10 shrink-0 items-center gap-1 border-b border-border/40 px-2">+ return <SidebarPanel aria-label={t("previewTabs.title")} data-testid="preview-pane" data-file-preview-panel+ width={width} isClosing={isClosing} contentClassName={sidePanelSurfaceClassName}+ header={<><div ref={tabList} role="tablist" aria-label={t("previewTabs.title")} className="min-w-0 flex-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"><SidebarSelectionHighlight activeId={activeId} scope="preview-tabs" targetSelector="[data-preview-tab-active]"className="relative isolate flex w-max min-w-full items-center gap-1"- highlightClassName="rounded-compact">+ highlightClassName="rounded-none rounded-t-2xl">{tabs.map((tab, index) => {const selected = tab.id === activeId;const name = splitFilePath(tab.value).name;const item = <div key={tab.id} role="presentation" data-preview-tab-active={selected ? "" : undefined}- className={cn(SIDEBAR_SELECTION_ITEM_CLASS, "group flex min-h-8 max-w-56 shrink-0 items-center rounded-compact", selected ? "text-foreground" : "text-muted-foreground hover:bg-muted/50 hover:text-foreground")}>+ className={cn(SIDEBAR_SELECTION_ITEM_CLASS, "group flex min-h-8 max-w-56 shrink-0 items-center rounded-t-2xl", selected ? "text-foreground" : "text-muted-foreground hover:bg-muted/50 hover:text-foreground")}><button type="button" role="tab" id={`${id}-tab-${index}`} aria-selected={selected} aria-controls={`${id}-panel`}tabIndex={selected ? 0 : -1} title={tab.value}ref={(node) => { if (node) buttons.current.set(tab.id, node); else buttons.current.delete(tab.id); }}@@ -87,7 +74,7 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClosonSelect(tabs[next].id);buttons.current.get(tabs[next].id)?.focus();}}- className="touch-target flex h-8 min-w-0 items-center gap-1.5 rounded-compact pl-2.5 pr-1.5 text-[12.5px] font-medium leading-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">+ className="touch-target flex h-8 min-w-0 items-center gap-1.5 rounded-t-2xl pl-2.5 pr-1.5 text-[12.5px] font-medium leading-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"><span aria-hidden className="flex size-3.5 shrink-0 items-center justify-center text-muted-foreground"><FileReferenceIcon kind={fileKindForPath(tab.value)} className="size-3.5" /></span>@@ -106,11 +93,14 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos{tabs.length > 1 ? <button type="button" className={iconButton} onClick={onClose} aria-label={t("previewTabs.closeAll")} title={t("previewTabs.closeAll")}><PanelRightClose className="size-4" aria-hidden /></button> : null}- </div>- <div role="tabpanel" id={`${id}-panel`} aria-labelledby={`${id}-tab-${tabs.findIndex((tab) => tab.id === activeId)}`} tabIndex={0}- className="flex min-h-0 flex-1 flex-col focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">+ </>}>+ <button type="button" aria-label={t("filePreview.resize")} onPointerDown={onResizeStart}+ className="file-preview-resize group absolute inset-y-0 left-0 z-20 hidden w-2 cursor-col-resize touch-none justify-start focus-visible:outline-none">+ <span aria-hidden className="h-full w-px bg-foreground/25 opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100" />+ </button>+ <div role="tabpanel" {...surfaceFocusProps} id={`${id}-panel`} aria-labelledby={`${id}-tab-${tabs.findIndex((tab) => tab.id === activeId)}`} tabIndex={0}+ className="flex min-h-0 flex-1 flex-col outline-none data-[keyboard-focus]:ring-2 data-[keyboard-focus]:ring-inset data-[keyboard-focus]:ring-ring">{children}</div>- </div>- </aside>;+ </SidebarPanel>;}diff --git a/webui/src/components/ViewportCodeRows.tsx b/webui/src/components/ViewportCodeRows.tsxindex e2581607e..b53f4225e 100644--- a/webui/src/components/ViewportCodeRows.tsx+++ b/webui/src/components/ViewportCodeRows.tsx@@ -10,15 +10,16 @@ function textOf(node: Row): string {return node.type === "text" ? String(node.value ?? "") : (node.children ?? []).map(textOf).join("");}-const CodeChunk = memo(function CodeChunk({ rows, text, start, stylesheet, useInlineStyles, highlighted }: RowsProps & {+const CodeChunk = memo(function CodeChunk({ rows, text, start, stylesheet, useInlineStyles, highlighted, lineNumberWidth }: RowsProps & {text: string;start: number;highlighted: boolean;+ lineNumberWidth: string;}) {return (<span data-code-chunk={start / CHUNK_LINES} className="flex min-w-max"><span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground"- style={{ minWidth: "4.25em" }}>+ style={{ minWidth: lineNumberWidth }}>{rows.map((_, index) => start + index + 1).join("\n")}</span><span data-highlighted={highlighted}>@@ -78,7 +79,8 @@ export function ViewportCodeRows({ rows, stylesheet, useInlineStyles }: RowsPropreturn (<span ref={rootRef} className="block min-w-max" data-testid="viewport-code-rows">{chunks.map((chunk, index) => <CodeChunk key={chunk.start} {...chunk}- stylesheet={tokenStyles} useInlineStyles={useInlineStyles} highlighted={visible.has(index)} />)}+ stylesheet={tokenStyles} useInlineStyles={useInlineStyles} highlighted={visible.has(index)}+ lineNumberWidth={`calc(${String(rows.length).length}ch + 1.15rem)`} />)}</span>);}diff --git a/webui/src/components/settings/SkillsCatalogSettings.tsx b/webui/src/components/settings/SkillsCatalogSettings.tsxindex 5e1cbd113..86bf37cb9 100644--- a/webui/src/components/settings/SkillsCatalogSettings.tsx+++ b/webui/src/components/settings/SkillsCatalogSettings.tsx@@ -388,8 +388,8 @@ function SkillDetailSheet({"sm:right-3 sm:top-3",)}className={cn(- "w-full max-w-none gap-0 overflow-hidden border-l-0 p-0",- "sm:w-[min(34rem,calc(100vw-1rem))] sm:max-w-none sm:border-l",+ "w-[calc(100vw-1rem)] max-w-none gap-0 p-0",+ "sm:w-[min(34rem,calc(100vw-1rem))] sm:max-w-none",)}><divdiff --git a/webui/src/components/thread/ComposerUsagePopover.tsx b/webui/src/components/thread/ComposerUsagePopover.tsxindex 8f07d066e..775e0c446 100644--- a/webui/src/components/thread/ComposerUsagePopover.tsx+++ b/webui/src/components/thread/ComposerUsagePopover.tsx@@ -1,82 +1,72 @@-import { Fragment, useCallback, useMemo, useRef, useState, type PointerEvent, type ReactNode } from "react";+import { useEffect, useId, useRef, useState, type KeyboardEvent } from "react";+import { createPortal } from "react-dom";import { useTranslation } from "react-i18next";--import {- Popover,- PopoverContent,- PopoverTrigger,-} from "@/components/ui/popover";-import { Sheet, SheetContent, SheetTitle, SheetTrigger } from "@/components/ui/sheet";-import { FloatingPortalContext } from "@/components/ui/floating-portal";-import {- Tooltip,- TooltipContent,- TooltipProvider,- TooltipTrigger,-} from "@/components/ui/tooltip";-import { formatCompactTokenCount } from "@/lib/format";-import { formatTurnLatency } from "@/lib/format-time";+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";+import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";+import { SidebarPanel } from "@/components/ui/sidebar-panel";+import { ContextInspector } from "./ContextInspector";+import type { ContextSnapshot } from "@/lib/types";import { cn } from "@/lib/utils";export interface ComposerContextUsage {+ estimated?: boolean;contextTokens: number;contextWindowTokens?: number;}export interface ComposerRoundUsage {- id: string;- timestamp: number;inputTokens: number;- outputTokens?: number;cachedTokens?: number;- estimatedTokens?: number;generationMs?: number;}-interface NormalizedRoundUsage extends ComposerRoundUsage {- cachedTokens?: number;- outputTokens: number;-}--function normalizeRounds(- rounds: readonly ComposerRoundUsage[],-): NormalizedRoundUsage[] {- return rounds- .filter((round) => Number.isFinite(round.inputTokens) && round.inputTokens > 0)- .map((round) => ({- ...round,- inputTokens: Math.max(0, round.inputTokens),- outputTokens: Number.isFinite(round.outputTokens)- ? Math.max(0, round.outputTokens ?? 0)- : 0,- ...(Number.isFinite(round.cachedTokens)- ? { cachedTokens: Math.min(round.inputTokens, Math.max(0, round.cachedTokens ?? 0)) }- : {}),- }));-}-export function ComposerUsagePopover({context,rounds,+ snapshots = [],+ onOpenFile,showLabel = false,compactLabel = false,- bottomSheet = false,+ sidebarHost,+ triggerHost,+ open: controlledOpen,+ onOpenChange,}: {context: ComposerContextUsage | null;rounds: readonly ComposerRoundUsage[];+ snapshots?: readonly ContextSnapshot[];+ onOpenFile?: (path: string) => void;showLabel?: boolean;compactLabel?: boolean;- bottomSheet?: boolean;+ sidebarHost?: HTMLElement | null;+ triggerHost?: HTMLElement | null;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;}) {- const { t, i18n } = useTranslation();- const [open, setOpen] = useState(false);- const normalizedRounds = useMemo(() => normalizeRounds(rounds), [rounds]);+ const { t } = useTranslation();+ const [localOpen, setLocalOpen] = useState(false);+ const open = controlledOpen ?? localOpen;+ const interactedOutside = useRef(false);+ const setOpen = (next: boolean) => { if (next) interactedOutside.current = false; setLocalOpen(next); onOpenChange?.(next); };+ const triggerRef = useRef<HTMLButtonElement>(null);+ const panelId = useId();+ const [narrow, setNarrow] = useState(false);+ useEffect(() => {+ const measure = () => setNarrow((sidebarHost?.clientWidth ?? window.innerWidth) < 780);+ measure();+ const observer = new ResizeObserver(measure);+ if (sidebarHost) observer.observe(sidebarHost);+ window.addEventListener("resize", measure);+ return () => { observer.disconnect(); window.removeEventListener("resize", measure); };+ }, [sidebarHost]);+ const close = () => { setOpen(false); requestAnimationFrame(() => triggerRef.current?.focus()); };+ const hasRounds = rounds.some((round) => Number.isFinite(round.inputTokens) && round.inputTokens > 0);const hasContext = !!context&& Number.isFinite(context.contextTokens)&& context.contextTokens >= 0&& Number.isFinite(context.contextWindowTokens)&& (context.contextWindowTokens ?? 0) > 0;- if (!hasContext && normalizedRounds.length === 0) {+ if (!open && !hasContext && !hasRounds && !snapshots.length) {return null;}@@ -99,37 +89,21 @@ export function ComposerUsagePopover({? detailsLabel: t("thread.composer.context.tooltip", {defaultValue: "Context {{percent}}%",- percent: contextPercentage,+ percent: `${context?.estimated ? "≈" : ""}${contextPercentage}`,});const triggerLabel = contextPercentage === null? detailsLabel: `${contextDescription}. ${detailsLabel}`;const ringCircumference = 2 * Math.PI * 6;const ringLength = ringCircumference * meterPercentage / 100;- const maxInputTokens = Math.max(0, ...normalizedRounds.map((round) => round.inputTokens));- const numberFormatter = new Intl.NumberFormat(i18n.language);- const percentageFormatter = new Intl.NumberFormat(i18n.language, {- style: "percent",- maximumFractionDigits: 0,- });- const roundDateFormatter = new Intl.DateTimeFormat(i18n.language, {- month: "short",- day: "numeric",- hour: "2-digit",- minute: "2-digit",- });-- const Root = bottomSheet ? Sheet : Popover;- const Trigger = bottomSheet ? SheetTrigger : PopoverTrigger;- const RoundRoot = bottomSheet ? Popover : Tooltip;- const RoundTrigger = bottomSheet ? PopoverTrigger : TooltipTrigger;- const RoundContent = bottomSheet ? PopoverContent : TooltipContent;- const RoundBar = bottomSheet ? "button" : "span";const showTextLabel = showLabel && (!compactLabel || contextPercentage !== null);const trigger = (- <Trigger asChild><buttontype="button"+ ref={triggerRef}+ onClick={() => setOpen(!open)}+ aria-expanded={open}+ aria-controls={open ? panelId : undefined}data-testid="composer-context-usage"aria-label={triggerLabel}className={cn(@@ -184,372 +158,43 @@ export function ComposerUsagePopover({)}{showTextLabel ? (<span aria-hidden className="whitespace-nowrap tabular-nums">- {compactLabel && contextPercentage !== null ? `${contextPercentage}%` : contextDescription}+ {compactLabel && contextPercentage !== null ? `${context?.estimated ? "≈" : ""}${contextPercentage}%` : contextDescription}</span>) : null}</button>- </Trigger>);- return (- <Root open={open} onOpenChange={setOpen}>- <TooltipProvider>- {bottomSheet ? trigger : (- <Tooltip>- <TooltipTrigger asChild>{trigger}</TooltipTrigger>- <TooltipContent- side="top"- align="center"- sideOffset={8}- className="w-fit max-w-[calc(100vw-2rem)] rounded-full border-border/70 px-2.5 py-1 text-xs font-medium shadow-[0_8px_24px_rgba(15,23,42,0.13)]"- >- <span className="whitespace-nowrap tabular-nums">{contextDescription}</span>- </TooltipContent>- </Tooltip>- )}-- <UsagePanel bottomSheet={bottomSheet} onDismiss={() => setOpen(false)}>- <div className="px-4 pb-4 pt-3.5">- {contextPercentage !== null ? (- <>- <div className="flex items-baseline justify-between gap-3">- <div className="flex min-w-0 items-baseline gap-2">- <span className={cn("shrink-0 font-medium text-foreground", bottomSheet ? "text-sm" : "text-[12px]")}>- {t("thread.composer.context.contextTitle", {- defaultValue: "Context",- })}- </span>- <span className={cn("truncate tabular-nums text-muted-foreground", bottomSheet ? "text-xs" : "text-[11px]")}>- {formatCompactTokenCount(context!.contextTokens)} / {formatCompactTokenCount(- context!.contextWindowTokens!,- )}- </span>- </div>- <span className={cn("shrink-0 tabular-nums text-muted-foreground", bottomSheet ? "text-xs" : "text-[11px]")}>- {contextPercentage}%- </span>- </div>- <div- role="progressbar"- aria-label={contextDescription}- aria-valuemin={0}- aria-valuemax={100}- aria-valuenow={contextPercentage}- className="mt-2 h-1 overflow-hidden rounded-full bg-muted"- >- <div- className={cn(- "h-full rounded-full",- status === "critical" && "bg-destructive",- status === "caution" && "bg-amber-500",- status === "normal" && "bg-foreground/45",- )}- style={{ width: `${contextPercentage}%` }}- />- </div>- </>- ) : null}-- {normalizedRounds.length > 0 ? (- <>- <div className={cn(- "flex items-baseline justify-between gap-3",- contextPercentage === null ? "mt-0" : "mt-5",- )}>- <span className={cn("font-medium text-foreground", bottomSheet ? "text-sm" : "text-[12px]")}>- {t("thread.composer.context.recentRounds", {- defaultValue: "Recent rounds",- })}- </span>- <span className={cn("text-muted-foreground", bottomSheet ? "text-xs" : "text-[11px]")}>- {t("thread.composer.context.inputTrend", {- defaultValue: "Input tokens",- })}- </span>- </div>- <div- role="group"- aria-label={t("thread.composer.context.inputTrend", {- defaultValue: "Input tokens",- })}- className="mt-2 flex h-28 items-end gap-1.5 border-b border-border/60"- >- {normalizedRounds.map((round, index) => {- const cachedKnown = typeof round.cachedTokens === "number";- const cachedTokens = round.cachedTokens ?? 0;- const notReusedTokens = Math.max(0, round.inputTokens - cachedTokens);- const cacheHitRate = cachedKnown- ? percentageFormatter.format(cachedTokens / round.inputTokens)- : null;- const cachedHeight = cachedKnown- ? cachedTokens / round.inputTokens * 100- : 0;- const barHeight = round.inputTokens / maxInputTokens * 108;- const timestampLabel = roundDateFormatter.format(round.timestamp);- const detailRows = [- {- key: "input",- label: t("thread.composer.context.input", {- defaultValue: "Input tokens",- }),- value: numberFormatter.format(round.inputTokens),- },- cachedKnown- ? {- key: "cache-hit-rate",- label: t("thread.composer.context.cacheHitRate", {- defaultValue: "KV cache hit rate",- }),- value: cacheHitRate!,- }- : null,- {- key: "output",- label: t("thread.composer.context.output", {- defaultValue: "Output tokens",- }),- value: numberFormatter.format(round.outputTokens),- },- typeof round.generationMs === "number"- ? {- key: "duration",- label: t("thread.composer.context.duration", {- defaultValue: "Generation time",- }),- value: formatTurnLatency(round.generationMs, i18n.language),- }- : null,- ].filter((row): row is NonNullable<typeof row> => !!row);- const detailNote = (round.estimatedTokens ?? 0) > 0- ? t("message.usage.estimated", {- defaultValue: "Includes estimated usage",- })- : null;- const detailLabel = [- timestampLabel,- ...detailRows.map((row) => `${row.label} ${row.value}`),- detailNote,- ].filter((part): part is string => !!part).join(". ");-- return (- <span- key={round.id}- className={cn(- "flex h-full min-w-0 flex-1 items-end justify-center rounded-sm",- bottomSheet && "relative",- "opacity-70 transition-opacity hover:opacity-100",- index === 0 && "justify-start",- normalizedRounds.length > 1- && index === normalizedRounds.length - 1- && "justify-end",- index === normalizedRounds.length - 1 && "opacity-100",- )}- >- <RoundRoot>- <RoundTrigger asChild>- <RoundBar- type={bottomSheet ? "button" : undefined}- role={bottomSheet ? undefined : "img"}- tabIndex={0}- aria-label={detailLabel}- data-testid="round-usage-bar"- className={cn(- "flex w-full max-w-7 flex-col overflow-hidden rounded-t-[3px] bg-muted",- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",- // Let touch users hit the entire column, even when a- // round's proportional bar is less than a pixel high.- bottomSheet && "before:absolute before:inset-0 before:content-[''] data-[state=open]:ring-2 data-[state=open]:ring-foreground/20",- )}- style={{ height: `${barHeight}px` }}- >- {cachedKnown ? (- <>- {notReusedTokens > 0 ? (- <span- className="kv-cache-not-reused block w-full"- style={{ height: `${100 - cachedHeight}%` }}- />- ) : null}- {cachedTokens > 0 ? (- <span- className="kv-cache-reused block w-full"- style={{ height: `${cachedHeight}%` }}- />- ) : null}- </>- ) : (- <span className="block h-full w-full bg-muted-foreground/25" />- )}- </RoundBar>- </RoundTrigger>- <RoundContent- side="top"- align="center"- className="max-w-72 px-3 py-2 text-[11px]"- {...(bottomSheet ? {- "aria-label": timestampLabel,- onOpenAutoFocus: (event: Event) => event.preventDefault(),- } : {})}- >- <span- className="block font-medium text-foreground"- >- {timestampLabel}- </span>- <span className="mt-1 grid grid-cols-[max-content_max-content] gap-x-3 gap-y-0.5">- {detailRows.map((row) => (- <Fragment key={row.key}>- <span className="text-muted-foreground">- {row.label}- </span>- <span className="text-end tabular-nums text-foreground">- {row.value}- </span>- </Fragment>- ))}- </span>- {detailNote ? (- <span- className="mt-1 block text-muted-foreground"- >- {detailNote}- </span>- ) : null}- </RoundContent>- </RoundRoot>- </span>- );- })}- </div>- </>- ) : null}-- </div>- </UsagePanel>- </TooltipProvider>- </Root>- );-}--function UsagePanel({ bottomSheet, onDismiss, children }: {- bottomSheet: boolean;- onDismiss: () => void;- children: ReactNode;-}) {- const { t } = useTranslation();- const panelRef = useRef<HTMLDivElement | null>(null);- const [panelNode, setPanelNode] = useState<HTMLDivElement | null>(null);- const sheetRef = useCallback((node: HTMLDivElement | null) => {- panelRef.current = node;- setPanelNode(node);- }, []);- const gesture = useRef<{ pointerId: number; x: number; y: number; time: number } | null>(null);- const suppressClick = useRef(false);- const [offset, setOffset] = useState(0);- const [dragging, setDragging] = useState(false);- const title = t("thread.composer.context.panelTitle", { defaultValue: "Context usage" });- const focusPanel = (event: Event) => {- event.preventDefault();- gesture.current = null;- suppressClick.current = false;- setOffset(0);- setDragging(false);- panelRef.current?.focus({ preventScroll: true });- };- const cancelDrag = (event: PointerEvent<HTMLButtonElement>) => {- if (gesture.current?.pointerId !== event.pointerId) return;- gesture.current = null;- suppressClick.current = true;- setDragging(false);- setOffset(0);+ const triggerWithTooltip = <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>{trigger}</TooltipTrigger>+ <TooltipContent side="top" className="text-xs">{contextDescription}</TooltipContent>+ </Tooltip>+ </TooltipProvider>;++ const inspector = <ContextInspector sidebar expandable={!narrow} context={context} rounds={rounds} snapshots={snapshots}+ onOpenFile={onOpenFile ? (path) => { setOpen(false); onOpenFile(path); } : undefined} />;+ const onPanelKeyDown = (event: KeyboardEvent<HTMLElement>) => {+ if (event.key === "Escape" && !event.defaultPrevented) { event.preventDefault(); close(); }};- if (bottomSheet) {- return (- <SheetContent- ref={sheetRef}- side="bottom"- aria-describedby={undefined}- showCloseButton={false}- onOpenAutoFocus={focusPanel}- style={{ translate: `0 ${offset}px`, ...(dragging ? { transition: "none" } : {}) }}- className={cn(- "mx-auto max-h-[60dvh] w-full max-w-md gap-0 rounded-t-3xl border-t border-border/60 p-0 shadow-xl outline-none",- "transition-[translate]",- "data-[state=open]:duration-300 data-[state=open]:ease-out data-[state=closed]:duration-200 data-[state=closed]:ease-in",- )}- >- <button- type="button"- aria-label={t("common.close")}- className="mx-auto flex h-11 w-24 shrink-0 touch-none select-none items-center justify-center rounded-full cursor-grab active:cursor-grabbing focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- onPointerDown={(event) => {- if (event.button !== 0 || !event.isPrimary || gesture.current) return;- event.currentTarget.setPointerCapture(event.pointerId);- gesture.current = { pointerId: event.pointerId, x: event.clientX, y: event.clientY, time: event.timeStamp };- suppressClick.current = false;- setDragging(true);- }}- onPointerMove={(event) => {- const start = gesture.current;- if (!start || start.pointerId !== event.pointerId) return;- const dy = event.clientY - start.y;- const dx = event.clientX - start.x;- if (Math.abs(dy) > 5 || Math.abs(dx) > 5) suppressClick.current = true;- setOffset(Math.max(0, dy));- }}- onPointerUp={(event) => {- const start = gesture.current;- if (!start || start.pointerId !== event.pointerId) return;- gesture.current = null;- const dy = Math.max(0, event.clientY - start.y);- const dx = Math.abs(event.clientX - start.x);- const threshold = Math.max(48, Math.min(96, (panelRef.current?.offsetHeight ?? 320) * 0.3));- const elapsed = Math.max(1, event.timeStamp - start.time);- const dismiss = dy > dx && (dy >= threshold || (dy > 20 && dy / elapsed > 0.5));- suppressClick.current ||= dy > 5 || dx > 5;- event.currentTarget.releasePointerCapture(event.pointerId);- setDragging(false);- if (dismiss) onDismiss();- else setOffset(0);- }}- onPointerCancel={cancelDrag}- onLostPointerCapture={cancelDrag}- onClick={(event) => {- // A completed drag also emits a click; don't close after a snap-back.- if (suppressClick.current && event.detail !== 0) {- event.preventDefault();- suppressClick.current = false;- return;- }- onDismiss();- }}- >- <span aria-hidden="true" className="h-1 w-8 rounded-full bg-foreground/15" />- </button>- <div className="shrink-0 px-5 pb-2">- <SheetTitle className="text-base font-medium">{title}</SheetTitle>- </div>- <div className="min-h-0 overflow-y-auto overscroll-contain px-1 pb-[max(0.75rem,env(safe-area-inset-bottom))]">- <FloatingPortalContext.Provider value={panelNode}>- {children}- </FloatingPortalContext.Provider>- </div>- </SheetContent>- );- }-- return (- <PopoverContent- ref={panelRef}- side="top"- align="end"- sideOffset={10}- onOpenAutoFocus={focusPanel}- aria-label={title}- className="w-[min(22rem,calc(100vw-1.5rem))] p-0"- >- {children}- </PopoverContent>- );+ return <>+ {triggerHost === undefined ? triggerWithTooltip : triggerHost && createPortal(triggerWithTooltip, triggerHost)}+ {narrow ? <Dialog open={open} onOpenChange={setOpen} modal={!sidebarHost}>+ <DialogContent portalContainer={sidebarHost} placement="bottom" id={panelId} aria-describedby={undefined}+ data-testid="context-sidebar"+ overlayClassName={cn("context-drawer-backdrop", sidebarHost && "absolute bg-black/25 backdrop-blur-[8px] sm:bg-transparent sm:backdrop-blur-none")}+ className="context-drawer-panel flex h-[85%] min-h-0 max-w-none flex-col gap-2 p-4 pt-5 pb-[max(1rem,env(safe-area-inset-bottom))]"+ onCloseAutoFocus={(event) => { event.preventDefault(); if (!interactedOutside.current) triggerRef.current?.focus({ preventScroll: true }); }}+ onInteractOutside={(event) => {+ if (event.target instanceof Node && triggerRef.current?.contains(event.target)) event.preventDefault();+ else interactedOutside.current = true;+ }}>+ <DialogTitle className="sr-only">{t("thread.composer.context.panelTitle")}</DialogTitle>+ {inspector}+ </DialogContent>+ </Dialog> : createPortal(<SidebarPanel open={open} width={420} floating={!sidebarHost} id={panelId}+ aria-label={t("thread.composer.context.panelTitle")} data-testid="context-sidebar" onKeyDown={onPanelKeyDown}>+ {inspector}+ </SidebarPanel>, sidebarHost ?? document.body)}+ </>;}diff --git a/webui/src/components/thread/ContextGraphScene.tsx b/webui/src/components/thread/ContextGraphScene.tsxnew file mode 100644index 000000000..7a282ca58--- /dev/null+++ b/webui/src/components/thread/ContextGraphScene.tsx@@ -0,0 +1,294 @@+import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";+import { useReducedMotion } from "motion/react";+import { Maximize2, Minimize2 } from "lucide-react";+import { useTranslation } from "react-i18next";+import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";+import { cn } from "@/lib/utils";+import { formatCompactTokenCount } from "@/lib/format";+import { createGraphSimulation, updateGraphSimulation, advanceGraphSimulation, startGraphSettlement, type GraphParticle, type GraphPosition } from "@/lib/context-graph-layout";+import type { ContextGraph } from "@/lib/types";+import { createGraphPresentation } from "./graph-presentation";+import { paintGraph, readGraphPalette, type GraphPalette } from "./graph-canvas";++const surface = "context-inspector-surface select-none rounded-[20px] bg-card";++export const ContextGraphScene = memo(function ContextGraphScene({ graph, epoch, expanded, onExpand, onOpenFile, onReady, sidebar = false }: {+ graph: ContextGraph; epoch?: string; expanded: boolean; onExpand?: () => void; onOpenFile?: (path: string) => void; onReady?: (graph: ContextGraph) => void; sidebar?: boolean;+}) {+ const { t } = useTranslation();+ const container = useRef<HTMLDivElement>(null);+ const canvas = useRef<HTMLCanvasElement>(null);+ const paletteProbe = useRef<HTMLSpanElement>(null);+ const palette = useRef<GraphPalette>();+ const nodeElements = useRef(new Map<string, HTMLButtonElement>());+ const focused = useRef<string | null>(null);+ const positions = useRef(new Map<string, GraphPosition>());+ const particles = useRef(new Map<string, GraphParticle>());+ const simulation = useRef<ReturnType<typeof createGraphSimulation>>();+ const settlement = useRef<ReturnType<typeof startGraphSettlement> | null>(null);+ const paintedGraph = useRef<ContextGraph>();+ const [presentation] = useState(createGraphPresentation);+ const [frame, setFrame] = useState(presentation.frame);+ const [size, setSize] = useState({ width: 550, height: 300 });+ const [active, setActive] = useState<string | null>(null);+ const [hovered, setHovered] = useState<string | null>(null);+ const currentNodes = useMemo(() => new Map(graph.nodes.map((node) => [node.path, node])), [graph]);+ const discovered = useMemo(() => new Set(graph.nodes.filter((node) => node.state === "discovered").map((node) => node.path)), [graph]);+ const selected = active ? currentNodes.get(active) : undefined;+ const candidate = active ?? hovered;+ const highlighted = candidate && currentNodes.has(candidate) ? candidate : null;+ const reducedMotion = !!useReducedMotion();+ const clock = useRef({ frame: 0, previous: 0, visible: true, geometry: true });+ const draw = useRef<(time: number) => void>(() => {});+ const view = useRef({ x: 0, y: 0, k: 1 });+ const interacted = useRef(false);+ const fittedSize = useRef("");+ const layoutKey = useRef("");+ const pruneEpoch = useRef(false);+ const previousEpoch = useRef(epoch);+ const pan = useRef<{ id: number; x: number; y: number } | null>(null);+ const dragging = useRef<{ id: number; path: string; x: number; y: number; moved: boolean } | null>(null);+ const restoreNodeFocus = useRef(false);+ const schedule = useCallback(() => {+ if (!clock.current.frame && clock.current.visible && !document.hidden) clock.current.frame = requestAnimationFrame((time) => draw.current(time));+ }, []);+ const setView = useCallback((next: typeof view.current) => {+ view.current = next;+ schedule();+ }, [schedule]);+ draw.current = (time) => {+ const state = clock.current;+ state.frame = 0;+ if (!state.visible || document.hidden) return;+ const elapsed = state.previous ? time - state.previous : 1000 / 60;+ state.previous = time;+ const sim = simulation.current;+ if (settlement.current) {+ if (!settlement.current()) { schedule(); return; }+ settlement.current = null; state.geometry = true;+ }+ const running = !!sim && (sim.alpha() > sim.alphaMin() || sim.alphaTarget() > 0);+ if (sim && running && !reducedMotion) { advanceGraphSimulation(sim, elapsed); state.geometry = true; }+ const change = presentation.advance(elapsed, reducedMotion);+ if (change.removed) {+ setFrame(presentation.frame);+ if (pruneEpoch.current) {+ const retained = new Set(presentation.frame.nodes.map((node) => node.path));+ for (const path of positions.current.keys()) if (!retained.has(path)) positions.current.delete(path);+ }+ }+ if (!change.moving) pruneEpoch.current = false;+ if (state.geometry && sim) for (const particle of sim.nodes()) {+ const point = positions.current.get(particle.path);+ if (point) { point.x = particle.x; point.y = particle.y; }+ else positions.current.set(particle.path, { x: particle.x, y: particle.y });+ }+ const bitmap = canvas.current;+ const context = bitmap?.getContext("2d");+ if (bitmap && context && palette.current) {+ // Keep motion within a pixel budget; the final stationary paint restores+ // native resolution for crisp labels without paying that cost every frame.+ const ratio = running || change.moving+ ? Math.min(window.devicePixelRatio || 1, 1.5, Math.sqrt(1_000_000 / (size.width * size.height)))+ : window.devicePixelRatio || 1;+ const width = Math.round(size.width * ratio), height = Math.round(size.height * ratio);+ if (bitmap.width !== width || bitmap.height !== height) { bitmap.width = width; bitmap.height = height; }+ paintGraph(context, presentation.frame, positions.current, view.current, palette.current, highlighted, focused.current,+ size.width, size.height, ratio, discovered);+ if (paintedGraph.current !== graph) { paintedGraph.current = graph; onReady?.(graph); }+ }+ state.geometry = false;+ if (change.moving || (running && !reducedMotion)) schedule();+ // The next animation starts a new clock; idle time must not consume its labels.+ else state.previous = 0;+ };+ useEffect(() => {+ if (previousEpoch.current === epoch) return;+ previousEpoch.current = epoch;+ pruneEpoch.current = true;+ palette.current?.labels.clear();+ const retained = new Set(graph.nodes.map((node) => node.path));+ for (const node of presentation.frame.nodes) retained.add(node.path);+ for (const path of positions.current.keys()) if (!retained.has(path)) positions.current.delete(path);+ }, [epoch, graph, presentation]);+ useEffect(() => {+ const element = container.current;+ if (!element) return;+ const observer = new ResizeObserver(([entry]) => setSize({ width: entry.contentRect.width, height: entry.contentRect.height }));+ observer.observe(element);+ const visibility = () => { clock.current.previous = 0; if (document.hidden) { cancelAnimationFrame(clock.current.frame); clock.current.frame = 0; } else schedule(); };+ document.addEventListener("visibilitychange", visibility);+ window.addEventListener("resize", schedule);+ const intersection = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver((entries) => {+ // Drawer entry can batch offscreen and onscreen records together. The+ // newest record owns visibility; the first can leave painting suspended.+ const entry = entries[entries.length - 1];+ clock.current.visible = entry.isIntersecting;+ if (entry.isIntersecting) { clock.current.previous = 0; schedule(); }+ else { cancelAnimationFrame(clock.current.frame); clock.current.frame = 0; clock.current.previous = 0; }+ });+ intersection?.observe(element);+ return () => { observer.disconnect(); intersection?.disconnect(); document.removeEventListener("visibilitychange", visibility); window.removeEventListener("resize", schedule); cancelAnimationFrame(clock.current.frame); clock.current.frame = 0; simulation.current?.stop(); };+ }, [schedule]);+ useEffect(() => {+ const sim = simulation.current ?? createGraphSimulation(graph, positions.current, size.width, size.height);+ if (simulation.current) updateGraphSimulation(sim, graph, positions.current, size.width, size.height);+ simulation.current = sim.stop();+ particles.current = new Map(sim.nodes().map((node) => [node.path, node]));+ const nextLayout = JSON.stringify([graph.nodes.map((node) => node.path), graph.edges, size]);+ settlement.current = reducedMotion && (layoutKey.current !== nextLayout || sim.alpha() > sim.alphaMin()) ? startGraphSettlement(sim) : null;+ if (!reducedMotion && layoutKey.current !== nextLayout) sim.alpha(Math.max(sim.alpha(), 0.3));+ layoutKey.current = nextLayout;+ clock.current.geometry = true;+ const key = `${size.width}:${size.height}`;+ if (!interacted.current && graph.nodes.length && fittedSize.current !== key) {+ const radius = Math.sqrt(graph.nodes.length * (60 * 0.36) ** 2 / Math.PI);+ const k = Math.max(0.01, Math.min(1, (size.width - 100) / Math.max(1, radius * 6), (size.height - 80) / Math.max(1, radius * 6)));+ setView({ k, x: size.width / 2 * (1 - k), y: size.height / 2 * (1 - k) });+ fittedSize.current = key;+ }+ schedule();+ }, [graph, size, reducedMotion, schedule, setView]);+ useEffect(() => {+ setActive((path) => path && currentNodes.has(path) ? path : null);+ setHovered((path) => path && currentNodes.has(path) ? path : null);+ }, [currentNodes]);+ useEffect(() => {+ setFrame(presentation.update(graph, highlighted));+ schedule();+ }, [graph, highlighted, presentation, schedule]);+ useLayoutEffect(() => { clock.current.geometry = true; schedule(); }, [frame, schedule]);+ useEffect(() => {+ const element = container.current;+ if (!element) return;+ const wheel = (event: WheelEvent) => {+ event.preventDefault(); interacted.current = true;+ const rect = element.getBoundingClientRect();+ const x = event.clientX - rect.left, y = event.clientY - rect.top, old = view.current;+ const k = Math.max(0.25, Math.min(4, old.k * Math.exp(-event.deltaY * 0.002)));+ setView({ k, x: x - (x - old.x) * k / old.k, y: y - (y - old.y) * k / old.k });+ setActive(null);+ };+ element.addEventListener("wheel", wheel, { passive: false });+ return () => element.removeEventListener("wheel", wheel);+ }, [setView]);+ const anchor = useRef({ getBoundingClientRect: () => new DOMRect() });+ anchor.current.getBoundingClientRect = () => {+ const rect = container.current?.getBoundingClientRect(), point = active ? positions.current.get(active) : undefined;+ return new DOMRect((rect?.x ?? 0) + (point?.x ?? 0) * view.current.k + view.current.x - 22,+ (rect?.y ?? 0) + (point?.y ?? 0) * view.current.k + view.current.y - 22, 44, 44);+ };+ const endDrag = (id: number, cancelled: boolean) => {+ const drag = dragging.current;+ if (!drag || drag.id !== id) return;+ const particle = particles.current.get(drag.path);+ if (particle) {+ if (particle.fx != null) particle.x = particle.fx;+ if (particle.fy != null) particle.y = particle.fy;+ particle.fx = null; particle.fy = null;+ clock.current.geometry = true;+ }+ simulation.current?.alphaTarget(0);+ if (!cancelled && !drag.moved) setActive((path) => path === drag.path ? null : drag.path);+ dragging.current = null;+ schedule();+ };+ const nodeAt = (clientX: number, clientY: number, radius: number) => {+ const rect = container.current?.getBoundingClientRect();+ if (!rect) return null;+ const x = clientX - rect.left, y = clientY - rect.top;+ let closest: string | null = null;+ let distance = Infinity;+ for (let index = presentation.frame.nodes.length - 1; index >= 0; index--) {+ const node = presentation.frame.nodes[index], point = positions.current.get(node.path);+ if (!point || !currentNodes.has(node.path)) continue;+ const candidateDistance = Math.hypot(point.x * view.current.k + view.current.x - x, point.y * view.current.k + view.current.y - y);+ if (candidateDistance <= Math.max(radius, node.radius) && candidateDistance < distance) { closest = node.path; distance = candidateDistance; }+ }+ return closest;+ };+ useLayoutEffect(() => {+ const update = () => { if (paletteProbe.current) palette.current = readGraphPalette(paletteProbe.current); schedule(); };+ update();+ const observer = new MutationObserver(update);+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "style"] });+ return () => observer.disconnect();+ }, [schedule]);+ const controls = useMemo(() => (<div className="sr-only">+ {graph.nodes.map((node) => <button key={node.path} type="button" data-context-node={node.path} aria-label={node.name} aria-expanded={active === node.path} aria-haspopup="dialog"+ ref={(element) => { if (element) nodeElements.current.set(node.path, element); else nodeElements.current.delete(node.path); }}+ onFocus={(e) => { focused.current = e.currentTarget.matches(":focus-visible") ? node.path : null; setHovered(node.path); schedule(); }}+ onKeyDown={() => { focused.current = node.path; schedule(); }}+ onBlur={() => { focused.current = null; setHovered(null); schedule(); }}+ onClick={() => setActive((path) => path === node.path ? null : node.path)}>{node.name}</button>)}+ </div>), [graph.nodes, active, schedule]);+ return <div ref={container} className={cn(surface, "relative isolate overflow-clip touch-none cursor-grab active:cursor-grabbing", sidebar ? "min-h-0 flex-1" : expanded ? "h-[min(65dvh,600px)]" : "h-[300px]")}+ onPointerDown={(e) => {+ if (!(e.target instanceof Node) || !e.currentTarget.contains(e.target)) return;+ if (e.button !== 0 || !e.isPrimary || (e.target instanceof Element && e.target.closest("button"))) return;+ // Keep the node's managed focus. Touch compatibility mouse events would+ // otherwise focus the drawer and immediately dismiss its node popover.+ e.preventDefault();+ interacted.current = true;+ const path = nodeAt(e.clientX, e.clientY, e.pointerType === "mouse" ? 12 : 22);+ if (path) {+ nodeElements.current.get(path)?.focus({ preventScroll: true });+ dragging.current = { id: e.pointerId, path, x: e.clientX, y: e.clientY, moved: false };+ pan.current = null;+ } else { pan.current = { id: e.pointerId, x: e.clientX, y: e.clientY }; setActive(null); }+ e.currentTarget.setPointerCapture(e.pointerId);+ }}+ onPointerMove={(e) => {+ if (!(e.target instanceof Node) || !e.currentTarget.contains(e.target)) return;+ const drag = dragging.current;+ if (drag && drag.id === e.pointerId) {+ const dx = e.clientX - drag.x, dy = e.clientY - drag.y;+ if (!drag.moved && Math.hypot(dx, dy) < 5) return;+ drag.moved = true; drag.x = e.clientX; drag.y = e.clientY; setActive(null); setHovered(drag.path);+ const particle = particles.current.get(drag.path);+ if (particle) {+ particle.fx = (particle.fx ?? particle.x) + dx / view.current.k; particle.fy = (particle.fy ?? particle.y) + dy / view.current.k;+ if (reducedMotion) { particle.x = particle.fx; particle.y = particle.fy; clock.current.geometry = true; }+ else simulation.current?.alphaTarget(0.25);+ schedule();+ }+ } else if (pan.current?.id === e.pointerId) {+ const old = view.current, previous = pan.current;+ setView({ ...old, x: old.x + e.clientX - previous.x, y: old.y + e.clientY - previous.y });+ pan.current = { id: e.pointerId, x: e.clientX, y: e.clientY };+ } else if (e.pointerType === "mouse") setHovered(nodeAt(e.clientX, e.clientY, 12));+ }}+ onPointerLeave={() => { if (!dragging.current) setHovered(null); }}+ onPointerUp={(e) => { endDrag(e.pointerId, false); if (pan.current?.id === e.pointerId) pan.current = null; }}+ onPointerCancel={(e) => { endDrag(e.pointerId, true); if (pan.current?.id === e.pointerId) pan.current = null; }}+ onLostPointerCapture={(e) => { endDrag(e.pointerId, true); if (pan.current?.id === e.pointerId) pan.current = null; }}+ onDoubleClick={(e) => {+ if (!(e.target instanceof Node) || !e.currentTarget.contains(e.target)) return;+ if ((e.target instanceof Element && e.target.closest("button")) || nodeAt(e.clientX, e.clientY, 22)) return;+ const points = [...particles.current.values()];+ if (!points.length) return;+ const xs = points.map((p) => p.x), ys = points.map((p) => p.y);+ const left = Math.min(...xs), right = Math.max(...xs), top = Math.min(...ys), bottom = Math.max(...ys);+ const k = Math.max(0.01, Math.min(1, (size.width - 140) / Math.max(1, right - left), (size.height - 110) / Math.max(1, bottom - top)));+ interacted.current = false; setView({ k, x: size.width / 2 - (left + right) / 2 * k, y: (size.height + 22) / 2 - (top + bottom) / 2 * k });+ }}>+ <span ref={paletteProbe} aria-hidden className="invisible absolute bg-background text-muted-foreground" />+ {onExpand && <button type="button" onClick={onExpand} aria-label={t(expanded ? "thread.composer.context.collapse" : "thread.composer.context.expand")}+ className="absolute right-2 top-2 z-10 flex size-9 items-center justify-center rounded-full bg-background/90 text-muted-foreground hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ {expanded ? <Minimize2 size={15} /> : <Maximize2 size={15} />}+ </button>}+ {!graph.nodes.length && !frame.nodes.length && <p className="absolute inset-0 flex items-center justify-center px-6 text-center text-xs text-muted-foreground">{t("thread.composer.context.noFiles")}</p>}+ <canvas ref={canvas} aria-hidden="true" className="absolute inset-0 size-full" />+ {controls}+ <Popover open={!!selected} onOpenChange={(open) => { if (!open) setActive(null); }}>+ <PopoverAnchor virtualRef={anchor} />+ {selected && <PopoverContent updatePositionStrategy="always" side="bottom" sideOffset={12} collisionPadding={12} onOpenAutoFocus={(e) => e.preventDefault()}+ onEscapeKeyDown={() => { restoreNodeFocus.current = true; }}+ onCloseAutoFocus={(e) => { e.preventDefault(); if (restoreNodeFocus.current) nodeElements.current.get(selected.path)?.focus(); restoreNodeFocus.current = false; }} onInteractOutside={(e) => { if (e.target instanceof Element && container.current?.contains(e.target) && e.target.closest("[data-context-node],canvas")) e.preventDefault(); }} className="flex w-auto select-none items-center gap-4 rounded-xl px-3 py-2.5 font-sans text-ui-label">+ <span className="text-muted-foreground">{t(selected.state === "loaded" ? "thread.composer.context.loaded" : "thread.composer.context.unloaded")}</span>+ {selected.state === "loaded" && <span className="tabular-nums text-muted-foreground">{t("thread.composer.context.estimatedNodeTokens", { value: formatCompactTokenCount(selected.tokens) })}</span>}+ {onOpenFile && <button type="button" className="min-h-8 font-sans text-ui-label text-orange-600 dark:text-orange-400 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" onClick={() => onOpenFile(selected.path)}>{t("thread.composer.context.openFile")}</button>}+ </PopoverContent>}+ </Popover>+ </div>;+});diff --git a/webui/src/components/thread/ContextInspector.tsx b/webui/src/components/thread/ContextInspector.tsxnew file mode 100644index 000000000..bd03b14cd--- /dev/null+++ b/webui/src/components/thread/ContextInspector.tsx@@ -0,0 +1,99 @@+import { lazy, Suspense, useCallback, useEffect, useId, useRef, useState } from "react";+import { LayoutGroup, motion, useReducedMotion } from "motion/react";+import { useTranslation } from "react-i18next";+import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";+import { cn } from "@/lib/utils";+import { formatTurnLatency } from "@/lib/format-time";+import type { ContextGraph, ContextSnapshot } from "@/lib/types";+import type { ComposerContextUsage, ComposerRoundUsage } from "./ComposerUsagePopover";++import { ContextReplayButton } from "./ContextReplayButton";++const ContextGraphScene = lazy(() => import("./ContextGraphScene").then(module => ({ default: module.ContextGraphScene })));++const EMPTY_GRAPH: ContextGraph = { nodes: [], edges: [] };+const surface = "context-inspector-surface select-none rounded-[20px] bg-card";++export function ContextInspector({ context, rounds, snapshots, onOpenFile, sidebar = false, expandable = true }: {+ context: ComposerContextUsage | null; rounds: readonly ComposerRoundUsage[];+ snapshots: readonly ContextSnapshot[]; onOpenFile?: (path: string) => void; sidebar?: boolean; expandable?: boolean;+}) {+ const { t, i18n } = useTranslation();+ const layoutId = useId();+ const reducedMotion = useReducedMotion();+ const [expanded, setExpanded] = useState(false);+ const [replay, setReplay] = useState<{ frames: readonly ContextSnapshot[]; index: number; startedAt: number; interval: number } | null>(null);+ const [readyGraph, setReadyGraph] = useState<ContextGraph | null>(null);+ const [meterHover, setMeterHover] = useState(false);+ const epoch = snapshots[0]?.id;+ useEffect(() => { setReplay(null); }, [epoch]);+ useEffect(() => {+ if (!replay || readyGraph !== replay.frames[replay.index].graph) return;+ // Keep a shared timeline instead of adding rendering time to every step.+ // Advance only after painting each snapshot, even when catching up.+ const remaining = replay.startedAt + (replay.index + 1) * replay.interval - performance.now();+ const timer = window.setTimeout(() => setReplay((current) => current && current.index + 1 < current.frames.length+ ? { ...current, index: current.index + 1 } : null), Math.max(0, remaining));+ return () => window.clearTimeout(timer);+ }, [replay, readyGraph]);+ const snapshot = replay ? replay.frames[replay.index] : snapshots.at(-1);+ const latestRound = rounds.at(-1);+ const tokens = snapshot ? snapshot.estimatedTokens ?? snapshot.usage?.context_tokens ?? snapshot.usage?.prompt_tokens : context?.contextTokens;+ const estimated = snapshot?.estimatedTokens !== undefined || (!snapshot?.usage && context?.estimated);+ const windowTokens = snapshot?.contextWindowTokens ?? context?.contextWindowTokens;+ const tokenNumbers = new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 1 });+ const hasTokenUsage = tokens !== undefined || !!windowTokens;+ const used = tokens !== undefined && windowTokens ? Math.min(100, tokens / windowTokens * 100) : null;+ const cached = snapshot ? snapshot.usage?.cached_tokens : latestRound?.cachedTokens;+ const input = snapshot ? snapshot.usage?.prompt_tokens : latestRound?.inputTokens;+ const cachedWidth = cached !== undefined && windowTokens ? Math.min(used ?? 0, cached / windowTokens * 100) : 0;+ const duration = snapshot ? snapshot.usage?.generation_ms : latestRound?.generationMs;+ const toggleExpanded = useCallback(() => setExpanded((value) => !value), []);+ const openFileCallback = useRef(onOpenFile);+ openFileCallback.current = onOpenFile;+ const openFile = useCallback((path: string) => { setExpanded(false); openFileCallback.current?.(path); }, []);+ const content = (large: boolean) => <motion.div layoutId={layoutId} transition={{ duration: reducedMotion ? 0 : 0.25, ease: [0.2, 0, 0, 1] }} className={cn("flex flex-col gap-3", sidebar && !large && "h-full min-h-0")}>+ <Suspense fallback={<div aria-busy="true" className={cn(surface, "min-h-[300px]", sidebar && !large && "min-h-0 flex-1")} />}>+ <ContextGraphScene graph={snapshot?.graph ?? EMPTY_GRAPH} epoch={epoch} onReady={setReadyGraph} expanded={large} sidebar={sidebar && !large} onExpand={expandable ? toggleExpanded : undefined} onOpenFile={onOpenFile ? openFile : undefined} />+ </Suspense>+ <div className="flex shrink-0 items-center gap-3">+ <div onPointerEnter={() => setMeterHover(true)} onPointerLeave={() => setMeterHover(false)} className={cn(surface, "relative flex h-14 min-w-0 flex-1 items-center gap-4 px-4 transition-transform duration-150 ease-out motion-reduce:transition-none", meterHover && "scale-[1.015]")}>+ <div className="flex h-11 flex-1 items-center">+ <div role="progressbar" aria-label={t("thread.composer.context.contextTitle")} aria-valuemin={0} aria-valuemax={100} aria-valuenow={used === null ? undefined : Math.round(used)} className="relative h-1.5 w-full overflow-hidden rounded-full bg-muted">+ <span className="absolute inset-y-0 left-0 rounded-full bg-muted-foreground/45 transition-[width] duration-150 ease-out motion-reduce:transition-none" style={{ width: `${used ?? 0}%` }} />+ <span className="absolute inset-y-0 left-0 rounded-full bg-orange-500 transition-[width] duration-150 ease-out motion-reduce:transition-none" style={{ width: `${cachedWidth}%` }} />+ </div>+ </div>+ <span className="text-sm tabular-nums">{used === null ? "—" : `${estimated ? "≈" : ""}${Math.round(used)}%`}</span>+ {meterHover && (hasTokenUsage || cached !== undefined || duration !== undefined || replay !== null) && <div className="pointer-events-none absolute bottom-full right-0 z-20 mb-2 min-w-48 rounded-xl bg-popover px-3 py-2.5 font-sans text-xs font-normal leading-5 shadow-lg">+ <dl className="grid grid-cols-[auto_auto] items-baseline gap-x-6 gap-y-1">+ {hasTokenUsage && <><dt className="whitespace-nowrap text-muted-foreground">{t("thread.composer.context.panelTitle")}</dt><dd className="whitespace-nowrap text-right tabular-nums text-popover-foreground">{t("thread.composer.context.tokenUsage", {+ used: tokens === undefined ? "—" : `${estimated ? "≈" : ""}${tokenNumbers.format(tokens / 1000)}k`,+ limit: windowTokens ? `${tokenNumbers.format(windowTokens / 1000)}k` : "—",+ })}</dd></>}+ {cached !== undefined && !!input && <><dt className="text-muted-foreground">{t("thread.composer.context.cacheHitRate")}</dt><dd className="whitespace-nowrap text-right tabular-nums text-popover-foreground">{Math.round(cached / input * 100)}%</dd></>}+ {duration !== undefined && <><dt className="text-muted-foreground">{t("thread.composer.context.duration")}</dt><dd className="whitespace-nowrap text-right tabular-nums text-popover-foreground">{formatTurnLatency(duration)}</dd></>}+ {replay && <><dt className="text-muted-foreground">{t("thread.composer.context.history")}</dt>+ <dd className="text-right tabular-nums text-muted-foreground">{replay.index + 1}/{replay.frames.length}</dd></>}+ </dl>+ </div>}+ </div>+ <ContextReplayButton disabled={replay !== null || snapshots.length < 2}+ onPlay={() => {+ setMeterHover(false);+ // Scale by request count: our replay unit is a snapshot, not a graph edge.+ const stepsPerSecond = Math.min(20, Math.max(5, 0.5 * Math.sqrt(snapshots.length)));+ setReplay({ frames: [...snapshots], index: 0, startedAt: performance.now(), interval: 1000 / stepsPerSecond });+ }} />+ </div>+ </motion.div>;+ return <LayoutGroup>+ {!expanded && content(false)}+ <Dialog open={expanded} onOpenChange={setExpanded}>+ <DialogContent showCloseButton={false} aria-describedby={undefined} overlayClassName="context-expanded-overlay bg-background/30 backdrop-blur-md" className="w-[min(960px,calc(100vw-2rem))] max-w-none border-0 bg-transparent p-0 shadow-none !animate-none">+ <DialogTitle className="sr-only">{t("thread.composer.context.panelTitle")}</DialogTitle>+ {content(true)}+ </DialogContent>+ </Dialog>+ </LayoutGroup>;+}diff --git a/webui/src/components/thread/ContextReplayButton.tsx b/webui/src/components/thread/ContextReplayButton.tsxnew file mode 100644index 000000000..642e901fd--- /dev/null+++ b/webui/src/components/thread/ContextReplayButton.tsx@@ -0,0 +1,12 @@+import { RotateCcw } from "lucide-react";+import { useTranslation } from "react-i18next";+import { HoverHint } from "@/components/ui/tooltip";++export function ContextReplayButton({ disabled, onPlay }: { disabled: boolean; onPlay: () => void }) {+ const { t } = useTranslation();+ const label = t("thread.composer.context.playHistory");+ return <HoverHint content={label} side="top" enabled={!disabled}><button type="button" aria-label={label} disabled={disabled} onClick={onPlay}+ className="context-inspector-surface grid size-14 shrink-0 place-items-center rounded-[20px] bg-card text-foreground/80 transition-colors enabled:hover:bg-muted enabled:hover:text-orange-500 disabled:cursor-default disabled:text-foreground/45 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <RotateCcw className="size-[18px]" strokeWidth={2.25} aria-hidden="true" />+ </button></HoverHint>;+}diff --git a/webui/src/components/thread/PromptNavigator.tsx b/webui/src/components/thread/PromptNavigator.tsxindex afe4a5bb8..32ed49f67 100644--- a/webui/src/components/thread/PromptNavigator.tsx+++ b/webui/src/components/thread/PromptNavigator.tsx@@ -1,17 +1,12 @@import {PromptNavigationIcon,} from "@/components/icons/product-icons";-import { useMemo, useRef, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import { Search } from "lucide-react";import { useTranslation } from "react-i18next";import { Button } from "@/components/ui/button";-import { SearchInput } from "@/components/ui/input";-import {- Sheet,- SheetContent,- SheetTitle,-} from "@/components/ui/sheet";+import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";import {type PromptAnchor,userPromptAnchors,@@ -24,14 +19,16 @@ interface PromptNavigatorProps {messages: UIMessage[];prompts?: PromptAnchor[];onJumpToPrompt: (promptId: string) => void;+ shortcutEnabled?: boolean;}-const ROW_HEIGHT = 88;+const ROW_HEIGHT = 64;export function PromptNavigator({messages,prompts: suppliedPrompts,onJumpToPrompt,+ shortcutEnabled = true,}: PromptNavigatorProps) {const { i18n, t } = useTranslation();const prompts = useMemo(() => suppliedPrompts ?? userPromptAnchors(messages), [suppliedPrompts, messages]);@@ -39,6 +36,23 @@ export function PromptNavigator({const [query, setQuery] = useState("");const listRef = useRef<HTMLDivElement>(null);const [listTop, setListTop] = useState(0);+ const [highlighted, setHighlighted] = useState(0);+ const inputRef = useRef<HTMLInputElement>(null);+ const triggerRef = useRef<HTMLButtonElement>(null);++ useEffect(() => {+ const keyDown = (event: KeyboardEvent) => {+ if (!shortcutEnabled || !prompts.length || event.defaultPrevented || event.repeat || event.isComposing+ || event.altKey || event.shiftKey || !(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "f") return;+ if (!open && (triggerRef.current?.closest("[hidden], [aria-hidden=true]") || document.querySelector("[role=dialog][data-state=open]"))) return;+ event.preventDefault();+ setListTop(0); setOpen(true);+ inputRef.current?.focus(); inputRef.current?.select();+ };+ window.addEventListener("keydown", keyDown);+ return () => window.removeEventListener("keydown", keyDown);+ }, [shortcutEnabled, prompts.length, open]);+ useEffect(() => { if (open) { setQuery(""); setHighlighted(0); setListTop(0); } }, [open]);const filteredPrompts = useMemo(() => {const needle = query.trim().toLocaleLowerCase();@@ -60,6 +74,7 @@ export function PromptNavigator({return (<><Button+ ref={triggerRef}type="button"variant="ghost"size="icon"@@ -68,41 +83,53 @@ export function PromptNavigator({"hover:text-foreground",)}aria-label={t("thread.promptNavigator.open")}+ aria-keyshortcuts="Control+F Meta+F"onClick={() => { setListTop(0); setOpen(true); }}><PromptNavigationIcon className="h-4 w-4" /></Button>- <Sheet open={open} onOpenChange={setOpen}>- <SheetContent- side="right"+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent+ showCloseButton={false}aria-describedby={undefined}- className="w-[min(92vw,24rem)] gap-0 p-0 sm:max-w-[24rem]"+ onOpenAutoFocus={(event) => { event.preventDefault(); inputRef.current?.focus(); }}+ onCloseAutoFocus={(event) => { event.preventDefault(); triggerRef.current?.focus(); }}+ className="session-search-dialog flex max-h-[min(40rem,100%)] w-[calc(100vw-2rem)] max-w-[42rem] flex-col gap-0 overflow-hidden p-0">- <div className="border-b px-5 pb-4 pt-5">- <SheetTitle className="text-base font-medium">+ <DialogTitle className="sr-only">{t("thread.promptNavigator.title")}- </SheetTitle>- <div className="relative mt-4">+ </DialogTitle>+ <div className="session-search-input flex h-[62px] shrink-0 items-center gap-3 border-b border-border px-[18px]"><Searcharia-hidden- className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"+ className="h-[18px] w-[18px] shrink-0 text-muted-foreground"/>- <SearchInput+ <input+ ref={inputRef}value={query}onChange={(event) => {setQuery(event.target.value);setListTop(0);+ setHighlighted(0);if (listRef.current) listRef.current.scrollTop = 0;}}aria-label={t("thread.promptNavigator.search")}placeholder={t("thread.promptNavigator.search")}- className="h-10 rounded-full border-border bg-background pl-9 pr-3 text-sm transition-colors"+ onKeyDown={(event) => {+ if (event.key === "Enter" && filteredPrompts[highlighted]) { event.preventDefault(); jump(filteredPrompts[highlighted].id); }+ if ((event.key === "ArrowDown" || event.key === "ArrowUp") && filteredPrompts.length) {+ event.preventDefault();+ const next = (highlighted + (event.key === "ArrowDown" ? 1 : -1) + filteredPrompts.length) % filteredPrompts.length;+ setHighlighted(next);+ if (listRef.current) { listRef.current.scrollTop = next * ROW_HEIGHT; setListTop(next * ROW_HEIGHT); }+ }+ }}+ className="h-full min-w-0 flex-1 bg-transparent text-[19px] font-normal leading-none text-foreground outline-none placeholder:text-muted-foreground"/></div>- </div>- <div ref={listRef} className="min-h-0 flex-1 overflow-y-auto px-2 py-2"+ <div ref={listRef} className="min-h-0 flex-1 overflow-y-auto overscroll-contain p-2.5 scrollbar-thin scrollbar-track-transparent"onScroll={(event) => setListTop(event.currentTarget.scrollTop)}onKeyDown={(event) => {const button = (event.target as HTMLElement).closest<HTMLButtonElement>("[data-prompt-row]");@@ -125,6 +152,8 @@ export function PromptNavigator({<PromptNavigatorRowkey={prompt.id}row={firstRow + offset}+ highlighted={highlighted === firstRow + offset}+ onHighlight={() => setHighlighted(firstRow + offset)}locale={i18n.resolvedLanguage || i18n.language}prompt={prompt}onJump={jump}@@ -137,8 +166,8 @@ export function PromptNavigator({</div>)}</div>- </SheetContent>- </Sheet>+ </DialogContent>+ </Dialog></>);}@@ -148,6 +177,8 @@ interface PromptNavigatorRowProps {locale: string;onJump: (promptId: string) => void;prompt: PromptAnchor;+ highlighted: boolean;+ onHighlight: () => void;}function PromptNavigatorRow({@@ -155,6 +186,8 @@ function PromptNavigatorRow({locale,onJump,prompt,+ highlighted,+ onHighlight,}: PromptNavigatorRowProps) {const { t } = useTranslation();const timestamp = fmtDateTime(prompt.createdAt, locale);@@ -163,17 +196,19 @@ function PromptNavigatorRow({type="button"data-prompt-row={row}className={cn(- "h-[88px] w-full overflow-hidden rounded-control px-3 py-3 text-left transition",- "hover:bg-accent focus-visible:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30",+ "h-16 w-full overflow-hidden rounded-control px-3 py-2 text-left transition-colors",+ "hover:bg-muted focus-visible:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30",+ highlighted && "bg-muted",)}aria-label={t("thread.promptNavigator.jumpTo", { label: prompt.label })}onClick={() => onJump(prompt.id)}+ onMouseEnter={onHighlight}>- <div className="line-clamp-2 whitespace-pre-wrap break-words text-sm leading-5 text-foreground">+ <div className="truncate text-[14px] font-medium leading-5 text-foreground">{prompt.preview}</div>{timestamp ? (- <div className="mt-1 text-[10px] leading-4 text-muted-foreground/75">+ <div className="mt-1 text-[12px] leading-4 text-muted-foreground">{timestamp}</div>) : null}diff --git a/webui/src/components/thread/SessionInfoPopover.tsx b/webui/src/components/thread/SessionInfoPopover.tsxindex 851eb9e15..695bdb59f 100644--- a/webui/src/components/thread/SessionInfoPopover.tsx+++ b/webui/src/components/thread/SessionInfoPopover.tsx@@ -11,16 +11,15 @@ interface SessionInfoPopoverProps {client: WebUIMutationTransport;sessionKey: string;token: string;- title: string;}-export function SessionInfoPopover({ client, sessionKey, token, title }: SessionInfoPopoverProps) {+export function SessionInfoPopover({ client, sessionKey, token }: SessionInfoPopoverProps) {const [surfacesOpen, setSurfacesOpen] = useState(false);const { jobs, loading, loadFailed, now } = useSessionAutomationJobs(surfacesOpen, token, sessionKey);const act = useCallback(async (action: AutomationAction, job: SessionAutomationJob) =>(await runAutomationAction(client, action, job.id)).jobs, [client]);const edit = useCallback(async (job: SessionAutomationJob, values: AutomationUpdatePayload) =>(await updateAutomation(client, job.id, values)).jobs, [client]);- return <SessionInfoPopoverView title={title} jobs={jobs} loading={loading} loadFailed={loadFailed} now={now}+ return <SessionInfoPopoverView jobs={jobs} loading={loading} loadFailed={loadFailed} now={now}onAction={act} onEdit={edit} onSurfacesOpenChange={setSurfacesOpen} calendarHref="#/automations" />;}diff --git a/webui/src/components/thread/SessionInfoPopoverView.tsx b/webui/src/components/thread/SessionInfoPopoverView.tsxindex 5a42d7377..535d85997 100644--- a/webui/src/components/thread/SessionInfoPopoverView.tsx+++ b/webui/src/components/thread/SessionInfoPopoverView.tsx@@ -49,9 +49,8 @@ const RELATIVE_THRESHOLDS: [number, Intl.RelativeTimeFormatUnit][] = [[Number.POSITIVE_INFINITY, "year"],];-export function SessionInfoPopoverView({ title, jobs, loading, loadFailed, now, onAction, onEdit,+export function SessionInfoPopoverView({ jobs, loading, loadFailed, now, onAction, onEdit,onSurfacesOpenChange, calendarHref, onOpenCalendar }: {- title: string;jobs: SessionAutomationJob[];loading: boolean;loadFailed: boolean;@@ -201,16 +200,7 @@ export function SessionInfoPopoverView({ title, jobs, loading, loadFailed, now,><div className="flex max-h-[min(var(--radix-popover-content-available-height),32rem)] flex-col"><div className="px-4 pb-3 pt-3.5">- <div className="min-w-0">- <div className="text-[12px] font-normal text-muted-foreground/75">- {t("thread.sessionInfo.title")}- </div>- <div className="mt-0.5 truncate text-[14px] font-medium text-foreground">- {title || t("thread.sessionInfo.untitled")}- </div>- </div>-- <div className="mt-3 flex items-center justify-between gap-3 border-t border-border/45 pt-3">+ <div className="flex items-center justify-between gap-3"><span className="truncate text-[13px] font-medium text-foreground">{t("thread.sessionInfo.automations")}</span>diff --git a/webui/src/components/thread/SubagentTasks.tsx b/webui/src/components/thread/SubagentTasks.tsxindex 2e5da3410..5392c5961 100644--- a/webui/src/components/thread/SubagentTasks.tsx+++ b/webui/src/components/thread/SubagentTasks.tsx@@ -157,8 +157,7 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live{children}<Sheet open={!!selected} onOpenChange={(open) => { if (!open) setSelectedId(null); }}><SheetContent ref={detailPanel} tabIndex={-1}- className="w-full gap-0 overflow-hidden border-l p-0 outline-none sm:w-[min(32rem,calc(100vw-1rem))] sm:max-w-none"- overlayClassName="bg-black/20 backdrop-blur-[8px]"+ className="w-[calc(100vw-1rem)] gap-0 p-0 sm:w-[min(32rem,calc(100vw-1rem))] sm:max-w-none"closeButtonClassName="right-2 top-2 grid h-11 w-11 place-items-center rounded-full sm:right-3 sm:top-3 sm:h-9 sm:w-9"onOpenAutoFocus={(event) => {event.preventDefault();diff --git a/webui/src/components/thread/ThreadComposer.tsx b/webui/src/components/thread/ThreadComposer.tsxindex aa8c8e994..fef7614a7 100644--- a/webui/src/components/thread/ThreadComposer.tsx+++ b/webui/src/components/thread/ThreadComposer.tsx@@ -241,6 +241,11 @@ interface ThreadComposerProps {onManageModels?: () => void;contextUsage?: ComposerContextUsage | null;recentRoundUsage?: readonly ComposerRoundUsage[];+ contextSnapshots?: readonly import("@/lib/types").ContextSnapshot[];+ onOpenContextFile?: (path: string) => void;+ contextSidebarHost?: HTMLElement | null;+ contextSidebarOpen?: boolean;+ onContextSidebarOpenChange?: (open: boolean) => void;variant?: "thread" | "hero";slashCommands?: SlashCommand[];onMentionSearch?: () => void;@@ -1080,6 +1085,11 @@ export function ThreadComposer({onManageModels,contextUsage = null,recentRoundUsage = [],+ contextSnapshots = [],+ onOpenContextFile,+ contextSidebarHost,+ contextSidebarOpen,+ onContextSidebarOpenChange,variant = "thread",slashCommands = [],onMentionSearch,@@ -1169,6 +1179,7 @@ export function ThreadComposer({const formRef = useRef<HTMLFormElement>(null);const tabFocusRequested = useRef(false);const [compactControls, setCompactControls] = useState(false);+ const [usageTriggerHost, setUsageTriggerHost] = useState<HTMLSpanElement | null>(null);useEffect(() => {// Automatic session focus should not open the hint; keyboard navigation should.@@ -2588,8 +2599,8 @@ export function ThreadComposer({/>) : null;const usageInMeta = mobileWorkspaceControls || compactControls;- const usageControl = !voiceRecorder.isRecording && (contextUsage || recentRoundUsage.length) ? (- <ComposerUsagePopover context={contextUsage} rounds={recentRoundUsage} showLabel={usageInMeta} compactLabel={mobileWorkspaceControls} bottomSheet={usageInMeta} />+ const usageControl = !voiceRecorder.isRecording && (contextUsage || recentRoundUsage.length || contextSnapshots.length) ? (+ <ComposerUsagePopover triggerHost={usageTriggerHost} context={contextUsage} rounds={recentRoundUsage} snapshots={contextSnapshots} onOpenFile={onOpenContextFile} showLabel={usageInMeta} compactLabel={mobileWorkspaceControls} sidebarHost={contextSidebarHost} open={contextSidebarOpen} onOpenChange={onContextSidebarOpenChange} />) : null;const inputTextClasses = cn(// Keep the overlay's CJK/Latin spacing aligned with the native textarea caret.@@ -2904,7 +2915,7 @@ export function ThreadComposer({)}>{modelControl}- {!usageInMeta ? usageControl : null}+ {!usageInMeta && usageControl ? <span className="contents" ref={setUsageTriggerHost} /> : null}<TooltipProvider><Tooltip><TooltipTrigger asChild>@@ -2981,12 +2992,13 @@ export function ThreadComposer({</div>{usageInMeta && usageControl || mobileWorkspaceControls && accessControl ? (<div className={cn("ml-auto flex shrink-0 items-center gap-1", mobileWorkspaceControls && "h-11 max-w-[calc(100%-3rem)]")}>- {usageInMeta ? usageControl : null}+ {usageInMeta && usageControl ? <span className="contents" ref={setUsageTriggerHost} /> : null}{mobileWorkspaceControls ? accessControl : null}</div>) : null}</div>) : null}+ {usageControl}</form>);}diff --git a/webui/src/components/thread/ThreadMessages.tsx b/webui/src/components/thread/ThreadMessages.tsxindex 717a6166f..9c5cb4104 100644--- a/webui/src/components/thread/ThreadMessages.tsx+++ b/webui/src/components/thread/ThreadMessages.tsx@@ -466,7 +466,7 @@ function MessageBlockMenu({data-message-block-menu data-message-mobile-sheet data-message-context-menu-block={contextBlockKey}className="gap-2 p-4 pt-5 pb-[max(1rem,env(safe-area-inset-bottom))] outline-none"onCloseAutoFocus={(event) => { if (activity?.expanded) event.preventDefault(); }}>- <DialogTitle className="px-2 pb-2 pe-10 text-sm font-medium text-muted-foreground">{label}</DialogTitle>+ <DialogTitle className="px-2 pb-2 text-sm font-medium text-muted-foreground">{label}</DialogTitle>{actions}</DialogContent></Dialog>diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsxindex 7756e94a2..4459e242c 100644--- a/webui/src/components/thread/ThreadShell.tsx+++ b/webui/src/components/thread/ThreadShell.tsx@@ -1,5 +1,5 @@import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";-import type { PointerEvent as ReactPointerEvent, ReactNode } from "react";+import type { CSSProperties, PointerEvent as ReactPointerEvent, ReactNode } from "react";import { createPortal } from "react-dom";import { useTranslation } from "react-i18next";import { composerUsageSnapshots, type ComposerUsageSnapshot } from "@/lib/model-request";@@ -76,13 +76,16 @@ import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";import { ThreadMessageCache } from "@/lib/thread-message-cache";import { providerDisplayLabel } from "@/lib/provider-brand";import { cn } from "@/lib/utils";+import { composerContextSnapshots } from "@/lib/context-graph";import { useClient } from "@/providers/ClientProvider";function latestComposerContextUsage(messages: ComposerUsageSnapshot[]): ComposerContextUsage | null {for (let index = messages.length - 1; index >= 0; index -= 1) {const message = messages[index];if (message.compacted) {- return null;+ return message.estimatedContextTokens !== undefined+ ? { contextTokens: message.estimatedContextTokens, contextWindowTokens: message.contextWindowTokens, estimated: true }+ : null;}const contextTokens = message.usage?.context_tokens;if (@@ -107,6 +110,7 @@ function recentComposerRoundUsage(messages: ComposerUsageSnapshot[]): ComposerRoconst seenTurns = new Set<string>();for (let index = messages.length - 1; index >= 0 && recent.length < 8; index -= 1) {const message = messages[index];+ if (message.compacted) break;const turnKey = message.turnId || message.id;if (seenTurns.has(turnKey)) {continue;@@ -126,23 +130,13 @@ function recentComposerRoundUsage(messages: ComposerUsageSnapshot[]): ComposerRo) {continue;}- const outputTokens = round.completion_tokens;const cachedTokens = round.cached_tokens;- const estimatedTokens = round.estimated_tokens;const generationMs = round.generation_ms;recent.push({- id: `${turnKey}:${roundIndex}`,- timestamp: message.completedAt ?? message.createdAt,inputTokens,- ...(typeof outputTokens === "number" && Number.isFinite(outputTokens)- ? { outputTokens }- : {}),...(typeof cachedTokens === "number" && Number.isFinite(cachedTokens)? { cachedTokens }: {}),- ...(typeof estimatedTokens === "number" && Number.isFinite(estimatedTokens)- ? { estimatedTokens }- : {}),...(typeof generationMs === "number" && Number.isFinite(generationMs)? { generationMs }: {}),@@ -540,11 +534,36 @@ export function ThreadShell({const [submittedViewportTurnId, setSubmittedViewportTurnId] = useState<string | null>(null);const { state: previewState, openFile, resolveFile, selectTab, closeTab, close: closePreview, setWidth: setFilePreviewWidth } =useFilePreviewState(previewSessionKey, filePreviewStore);+ const [contextSidebarOpen, setContextSidebarOpen] = useState(false);+ const [sidebarEnterWidth, setSidebarEnterWidth] = useState(0);+ const [contextSidebarHost, setContextSidebarHost] = useState<HTMLElement | null>(null);+ const setSidebarHost = useCallback((node: HTMLElement | null) => { shellRef.current = node; setContextSidebarHost(node); }, []);const [closingPreview, setClosingPreview] = useState<{ key: string; state: FilePreviewState } | null>(null);const filePreviewClosing = closingPreview?.key === previewSessionKey;const visiblePreview = filePreviewClosing ? closingPreview.state : previewState;const activePreview = visiblePreview.tabs.find((tab) => tab.id === visiblePreview.activeId);const previewOpen = Boolean(activePreview);+ const sidebarOpen = previewOpen || contextSidebarOpen;+ const [localComposerHost, setLocalComposerHost] = useState<HTMLDivElement | null>(null);+ const [composerMount] = useState(() => document.createElement("div"));+ const inlineComposer = composerPortalTarget === undefined || (sidebarOpen && composerActive);+ const composerDestination = inlineComposer ? localComposerHost : composerPortalTarget;+ useLayoutEffect(() => {+ // The inline host ref arrives on the next render. Keep the focused input+ // attached until that destination is ready.+ if (!composerDestination) { if (!inlineComposer) composerMount.remove(); return; }+ if (composerMount.parentElement === composerDestination) return;+ // Move the host, not the React subtree: drafts, graph replay and exit presence survive.+ const focused = document.activeElement instanceof HTMLElement && composerMount.contains(document.activeElement)+ ? document.activeElement : null;+ const selection = document.getSelection();+ const range = focused && selection?.rangeCount && composerMount.contains(selection.getRangeAt(0).commonAncestorContainer)+ ? selection.getRangeAt(0).cloneRange() : null;+ composerDestination.appendChild(composerMount);+ focused?.focus({ preventScroll: true });+ if (range && selection) { selection.removeAllRanges(); selection.addRange(range); }+ }, [composerDestination, composerMount, inlineComposer]);+ useLayoutEffect(() => () => composerMount.remove(), [composerMount]);const [filePreviewMaxWidth, setFilePreviewMaxWidth] = useState(FILE_PREVIEW_MAX_WIDTH);const filePreviewWidth = clampFilePreviewWidth(previewState.width, filePreviewMaxWidth);const draftKey = session?.key ?? (temporaryChatEnabled ? "new:temporary" : "new:chat");@@ -560,6 +579,23 @@ export function ThreadShell({const shellRef = useRef<HTMLElement | null>(null);const [conversationElement, setConversationElement] = useState<HTMLDivElement | null>(null);const composerSurfaceRef = useRef<HTMLDivElement | null>(null);+ useLayoutEffect(() => {+ const shell = contextSidebarHost;+ const surface = composerSurfaceRef.current;+ if (!sidebarOpen || !inlineComposer || !shell || !surface) return;+ // Metadata can wrap below the input card. Align sidebars to the visible+ // surface, rather than assuming a fixed composer/footer padding.+ const alignSidebar = () => {+ const inset = shell.getBoundingClientRect().bottom - surface.getBoundingClientRect().bottom;+ shell.style.setProperty("--sidebar-bottom-inset", `${Math.max(0, inset)}px`);+ };+ alignSidebar();+ const observer = new ResizeObserver(alignSidebar);+ observer.observe(shell);+ observer.observe(composerMount);+ observer.observe(surface);+ return () => observer.disconnect();+ }, [contextSidebarHost, sidebarOpen, inlineComposer, composerDestination, composerMount]);const filePreviewWidthRef = useRef(FILE_PREVIEW_DEFAULT_WIDTH);const filePreviewCloseTimerRef = useRef<number | null>(null);const filePreviewResizeCleanupRef = useRef<(() => void) | null>(null);@@ -704,6 +740,9 @@ export function ThreadShell({() => recentComposerRoundUsage(usageSnapshots),[usageSnapshots],);+ const contextGraphSnapshots = useMemo(+ () => composerContextSnapshots(messages, modelRequests), [messages, modelRequests],+ );const currentGoalState = messagesReady ? goalState : undefined;// Recovery decisions gate queued input, not the ledger-owned run state.const recoveryNeedsDecision = recoveryState?.status === "awaiting_user"@@ -1132,10 +1171,20 @@ export function ThreadShell({}, []);const handleOpenFilePreview = useCallback((path: string) => {+ setSidebarEnterWidth(shellRef.current?.querySelector(".file-preview-pane")?.getBoundingClientRect().width ?? 0);+ setContextSidebarOpen(false);cancelPreviewClose();openFile(path);}, [cancelPreviewClose, openFile]);+ const handleContextSidebarOpenChange = useCallback((open: boolean) => {+ if (open) {+ setSidebarEnterWidth(previewOpen ? filePreviewWidth : 0);+ cancelPreviewClose(); closePreview();+ }+ setContextSidebarOpen(open);+ }, [previewOpen, filePreviewWidth, cancelPreviewClose, closePreview]);+const handleClosePreviewTab = useCallback((id: string) => {if (previewState.tabs.length === 1) handleCloseFilePreview();else {@@ -1325,7 +1374,13 @@ export function ThreadShell({onManageModels={onOpenModelSettings}contextUsage={composerContextUsage}recentRoundUsage={composerRoundUsage}+ contextSnapshots={contextGraphSnapshots}+ onOpenContextFile={handleOpenFilePreview}+ contextSidebarHost={contextSidebarHost}+ contextSidebarOpen={contextSidebarOpen}+ onContextSidebarOpenChange={handleContextSidebarOpenChange}variant={composerVariant}+ surfaceRef={composerSurfaceRef}slashCommands={availableSlashCommands}onMentionSearch={requestMentionCatalogs}cliApps={cliApps}@@ -1379,6 +1434,11 @@ export function ThreadShell({onManageModels={onOpenModelSettings}contextUsage={composerContextUsage}recentRoundUsage={composerRoundUsage}+ contextSnapshots={contextGraphSnapshots}+ onOpenContextFile={handleOpenFilePreview}+ contextSidebarHost={contextSidebarHost}+ contextSidebarOpen={contextSidebarOpen}+ onContextSidebarOpenChange={handleContextSidebarOpenChange}variant="hero"slashCommands={availableSlashCommands}onMentionSearch={requestMentionCatalogs}@@ -1420,10 +1480,11 @@ export function ThreadShell({</div>);const sessionInfoAction = historyKey ? (- <SessionInfoPopover client={client} sessionKey={historyKey} token={token} title={title} />+ <SessionInfoPopover client={client} sessionKey={historyKey} token={token} />) : undefined;const promptNavigatorAction = historyKey ? (<PromptNavigator+ shortcutEnabled={composerActive}messages={displayMessages}prompts={promptNavigation.prompts}onJumpToPrompt={(promptId) => viewportRef.current?.jumpToUserPrompt(promptId)}@@ -1460,7 +1521,7 @@ export function ThreadShell({historyEnabled={webuiCapabilities.includes("webui.subagents.history.v1")}active={composerActive}enabled={!temporary && !!session?.key.startsWith("websocket:") && webuiCapabilities.includes("webui.subagents.v1")}>- <section ref={shellRef} data-preview-open={previewOpen || undefined} className="thread-preview-layout relative flex min-h-0 flex-1 overflow-hidden">+ <section ref={setSidebarHost} style={{ "--sidebar-enter-width": `${sidebarEnterWidth}px`, "--sidebar-enter-mobile-width": sidebarEnterWidth ? "100%" : "0px" } as CSSProperties} data-preview-open={sidebarOpen || undefined} className="thread-preview-layout relative flex min-h-0 flex-1 overflow-hidden"><div ref={setConversationElement} className={cn("thread-conversation relative flex min-w-0 flex-1 flex-col overflow-hidden",headerPortalTarget === undefined && !hideHeader && "thread-workspace",@@ -1496,7 +1557,7 @@ export function ThreadShell({retryStatus={retryStatus}emptyState={emptyState}initialLoading={initialHistoryLoading}- composer={composerPortalTarget === undefined ? composer : null}+ composer={inlineComposer ? <div ref={setLocalComposerHost} /> : null}activeTurnId={viewportTurnId}activeTurnStartedHere={activeTurnStartedHere}conversationKey={historyKey}@@ -1523,16 +1584,17 @@ export function ThreadShell({{headerPortalTarget && headerActive? createPortal(threadHeader, headerPortalTarget): null}- {composerPortalTarget ? createPortal(+ {createPortal(<divhidden={!composerActive}aria-hidden={!composerActive}data-testid={composerActive ? "active-pane-composer" : undefined}+ data-active-composer={composerActive || undefined}>{composer}</div>,- composerPortalTarget,- ) : null}+ composerMount,+ )}{activePreview && previewSessionKey ? (<FileActionsProvider key={previewSessionKey} value={fileActions}><PreviewPanediff --git a/webui/src/components/thread/WorkspaceControls.tsx b/webui/src/components/thread/WorkspaceControls.tsxindex 30785b17b..cf35ebf76 100644--- a/webui/src/components/thread/WorkspaceControls.tsx+++ b/webui/src/components/thread/WorkspaceControls.tsx@@ -1,3 +1,4 @@+import { surfaceFocusProps } from "@/lib/surface-focus";import { FullAccessIcon, RestrictedAccessIcon, WorkspaceIcon } from "@/components/icons/product-icons";import type { HTMLAttributes, ReactElement, RefObject } from "react";import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";@@ -636,8 +637,8 @@ export function WorkspaceProjectPicker({ disabled, scope, defaultScope, controls</nav>}<div className={cn("mr-[var(--picker-toolbar-inset)] flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-[var(--picker-field-radius)] bg-[#fcfcfc] dark:bg-muted", compact && showLocations && canBrowse && "hidden")}><div ref={attachColumns} data-workspace-columns className="sidebar-scrollbar flex flex-1 min-h-0 min-w-0 overflow-x-auto overscroll-x-contain">- {columns.map((column, columnIndex) => (!compact || columnIndex === currentColumnIndex) && <WorkspaceDirectoryColumn key={columnIndex} options={column.options} selectedPath={column.selectedPath} initialScrollTop={previewingPath ? 0 : currentVisit.scrollTops[columnIndex] ?? 0} visitRevision={history.revision} activeIndex={highlightActive && columnIndex === activeColumn ? activeOption : null}- id={`${optionsId}-${columnIndex}`} data-workspace-column={columnIndex} data-current-directory={columnIndex === currentColumnIndex ? "" : undefined} role="listbox" tabIndex={0} aria-activedescendant={highlightActive && columnIndex === activeColumn && column.options.length ? `${optionsId}-${columnIndex}-${activeOption}` : undefined} aria-label={column.path || t("thread.composer.workspace.projectAria")} aria-busy={columnIndex === currentColumnIndex && loading} style={{ width: `${compact ? 100 : 100 / columnCount}%` }} className="sidebar-scrollbar relative min-w-0 shrink-0 overflow-x-hidden overflow-y-auto px-2 outline-none [scrollbar-gutter:stable] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/50"+ {columns.map((column, columnIndex) => (!compact || columnIndex === currentColumnIndex) && <WorkspaceDirectoryColumn key={columnIndex} {...surfaceFocusProps} options={column.options} selectedPath={column.selectedPath} initialScrollTop={previewingPath ? 0 : currentVisit.scrollTops[columnIndex] ?? 0} visitRevision={history.revision} activeIndex={highlightActive && columnIndex === activeColumn ? activeOption : null}+ id={`${optionsId}-${columnIndex}`} data-workspace-column={columnIndex} data-current-directory={columnIndex === currentColumnIndex ? "" : undefined} role="listbox" tabIndex={0} aria-activedescendant={highlightActive && columnIndex === activeColumn && column.options.length ? `${optionsId}-${columnIndex}-${activeOption}` : undefined} aria-label={column.path || t("thread.composer.workspace.projectAria")} aria-busy={columnIndex === currentColumnIndex && loading} style={{ width: `${compact ? 100 : 100 / columnCount}%` }} className="sidebar-scrollbar relative min-w-0 shrink-0 overflow-x-hidden overflow-y-auto px-2 outline-none [scrollbar-gutter:stable] data-[keyboard-focus]:ring-2 data-[keyboard-focus]:ring-inset data-[keyboard-focus]:ring-ring/50"onFocus={event => { if (event.target === event.currentTarget) { setActiveColumn(columnIndex); setActiveIndex(0); } }}onKeyDown={event => {if (event.target !== event.currentTarget || event.altKey || event.metaKey || event.ctrlKey || pickingFolder) return;diff --git a/webui/src/components/thread/graph-canvas.ts b/webui/src/components/thread/graph-canvas.tsnew file mode 100644index 000000000..f616f7208--- /dev/null+++ b/webui/src/components/thread/graph-canvas.ts@@ -0,0 +1,94 @@+import type { GraphPosition } from "@/lib/context-graph-layout";+import type { GraphPresentation } from "./graph-presentation";++type RGB = readonly [number, number, number];+export interface GraphPalette { background: RGB; foreground: string; muted: RGB; font: string; labels: Map<string, string> }+interface GraphCamera { x: number; y: number; k: number }+const orange: RGB = [249, 115, 22];+const blend = (a: RGB, b: RGB, amount: number): RGB => [a[0] + (b[0] - a[0]) * amount, a[1] + (b[1] - a[1]) * amount, a[2] + (b[2] - a[2]) * amount];+const rgb = (value: RGB) => `rgb(${value.map(Math.round).join(" ")})`;+export function readGraphPalette(element: HTMLElement): GraphPalette {+ const style = getComputedStyle(element);+ const parse = (color: string): RGB => {+ const values = color.match(/[\d.]+/g)?.map(Number) ?? [];+ return [values[0] ?? 0, values[1] ?? 0, values[2] ?? 0];+ };+ return { background: parse(style.backgroundColor), muted: parse(style.color), foreground: getComputedStyle(element.parentElement!).color, font: `10px ${style.fontFamily}`, labels: new Map() };+}++export function fitGraphLabel(name: string, measure: (text: string) => number, maxWidth = 128): string {+ if (measure(name) <= maxWidth) return name;+ const characters = Array.from(name);+ let start = 0, end = characters.length;+ while (start < end) {+ const middle = Math.ceil((start + end) / 2);+ if (measure(`${characters.slice(0, middle).join("")}…`) <= maxWidth) start = middle;+ else end = middle - 1;+ }+ return `${characters.slice(0, start).join("")}…`;+}++/** One bitmap paint; neither force ticks nor camera movement mutate per-node DOM. */+export function paintGraph(context: CanvasRenderingContext2D, frame: GraphPresentation, positions: ReadonlyMap<string, GraphPosition>,+ view: GraphCamera, palette: GraphPalette, highlighted: string | null, focused: string | null,+ width: number, height: number, pixelRatio: number, discovered: ReadonlySet<string>) {+ context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);+ context.clearRect(0, 0, width, height);+ const groups = new Map<string, { opacity: number; dashed: boolean; edges: GraphPresentation["edges"] }>();+ for (const edge of frame.edges) {+ const opacity = edge.presence * edge.emphasis * 0.7;+ const dashed = discovered.has(edge.target);+ const key = `${opacity}:${dashed}`;+ let group = groups.get(key);+ if (!group) { group = { opacity, dashed, edges: [] }; groups.set(key, group); }+ group.edges.push(edge);+ }+ context.strokeStyle = "#f97316";+ context.lineWidth = 1;+ for (const group of groups.values()) {+ context.globalAlpha = group.opacity;+ context.setLineDash(group.dashed ? [3, 5] : []);+ context.beginPath();+ for (const edge of group.edges) {+ const a = positions.get(edge.source), b = positions.get(edge.target);+ if (!a || !b) continue;+ context.moveTo(a.x * view.k + view.x, a.y * view.k + view.y);+ context.lineTo(b.x * view.k + view.x, b.y * view.k + view.y);+ }+ context.stroke();+ }+ context.setLineDash([]);+ context.font = palette.font;+ context.textAlign = "center";+ context.textBaseline = "middle";+ for (const node of frame.nodes) {+ const point = positions.get(node.path);+ if (!point) continue;+ const x = point.x * view.k + view.x, y = point.y * view.k + view.y;+ const alpha = node.presence * node.emphasis;+ const color = blend(palette.muted, orange, node.focus);+ context.globalAlpha = alpha;+ context.strokeStyle = rgb(color);+ context.fillStyle = rgb(blend(palette.background, color, node.loaded));+ context.beginPath(); context.arc(x, y, node.radius - 0.5, 0, Math.PI * 2); context.fill(); context.stroke();+ if (node.path === focused) {+ context.strokeStyle = palette.foreground;+ context.lineWidth = 2;+ context.beginPath(); context.roundRect(x - 22, y - 22, 44, 44, 4); context.stroke();+ context.lineWidth = 1;+ }+ // Introduce newly loaded files for one second, then fade to the usual zoom visibility.+ const labelOpacity = node.path === highlighted ? 1 : Math.max(0, Math.min(1, (view.k - 1) / 3.75), Math.min(1, node.labelRemaining / 600));+ if (labelOpacity > 0) {+ context.globalAlpha = alpha * labelOpacity;+ context.fillStyle = palette.foreground;+ let label = palette.labels.get(node.name);+ if (label === undefined) {+ label = fitGraphLabel(node.name, (text) => context.measureText(text).width);+ palette.labels.set(node.name, label);+ }+ context.fillText(label, x, y + 24);+ }+ }+ context.globalAlpha = 1;+}diff --git a/webui/src/components/thread/graph-presentation.ts b/webui/src/components/thread/graph-presentation.tsnew file mode 100644index 000000000..77d313bb8--- /dev/null+++ b/webui/src/components/thread/graph-presentation.ts@@ -0,0 +1,77 @@+import { nodeRadius } from "@/lib/context-graph-layout";+import type { ContextGraph, ContextGraphNode } from "@/lib/types";++type PresentedNode = ContextGraphNode & { presence: number; emphasis: number; focus: number; radius: number; loaded: number; labelRemaining: number };+type PresentedEdge = ContextGraph["edges"][number] & { presence: number; emphasis: number };+export type GraphPresentation = { nodes: PresentedNode[]; edges: PresentedEdge[] };+const edgeKey = (edge: ContextGraph["edges"][number]) => JSON.stringify([edge.source, edge.target]);++/** Mutable animation state; request graphs remain immutable. The caller owns its clock. */+export function createGraphPresentation() {+ const nodes = new Map<string, PresentedNode>();+ const edges = new Map<string, PresentedEdge>();+ let wanted = new Set<string>();+ let wantedEdges = new Set<string>();+ let related = new Set<string | null>();+ let highlighted: string | null = null;+ let frame: GraphPresentation = { nodes: [], edges: [] };+ let moving = false;+ return {+ get frame() { return frame; },+ update(graph: ContextGraph, focus: string | null) {+ highlighted = focus;+ const previouslyWanted = wanted;+ wanted = new Set(graph.nodes.map((node) => node.path));+ wantedEdges = new Set(graph.edges.map(edgeKey));+ related = new Set([focus]);+ for (const edge of graph.edges) {+ if (edge.source === focus) related.add(edge.target);+ if (edge.target === focus) related.add(edge.source);+ }+ for (const node of graph.nodes) {+ const previous = nodes.get(node.path);+ if (previous) {+ if (node.state !== "loaded") previous.labelRemaining = 0;+ // A replay can reintroduce a node before its exit animation removes it.+ else if (previous.state !== "loaded" || !previouslyWanted.has(node.path)) previous.labelRemaining = 1600;+ Object.assign(previous, node);+ }+ else nodes.set(node.path, { ...node, presence: 0, emphasis: 1, focus: 0, radius: nodeRadius(node), loaded: Number(node.state === "loaded"), labelRemaining: node.state === "loaded" ? 1600 : 0 });+ }+ for (const edge of graph.edges) if (!edges.has(edgeKey(edge))) edges.set(edgeKey(edge), { ...edge, presence: 0, emphasis: 1 });+ frame = { nodes: [...nodes.values()], edges: [...edges.values()] };+ moving = true;+ return frame;+ },+ advance(elapsed: number, reducedMotion: boolean) {+ if (!moving) return { moving: false, removed: false };+ const amount = reducedMotion ? 1 : 1 - Math.pow(0.9, Math.min(64, Math.max(0, elapsed)) / (1000 / 60));+ moving = false;+ let removed = false;+ const approach = (value: number, target: number) => {+ const next = value + (target - value) * amount;+ if (Math.abs(next - target) < 0.005) return target;+ moving = true;+ return next;+ };+ for (const [path, node] of nodes) {+ // Keep the clock alive after the layout settles so new labels can fade out.+ node.labelRemaining = Math.max(0, node.labelRemaining - Math.max(0, elapsed));+ if (node.labelRemaining > 0) moving = true;+ node.presence = approach(node.presence, wanted.has(path) ? 1 : 0);+ node.emphasis = approach(node.emphasis, highlighted && !related.has(path) ? 0.2 : 1);+ node.focus = approach(node.focus, path === highlighted ? 1 : 0);+ node.radius = approach(node.radius, nodeRadius(node));+ node.loaded = approach(node.loaded, Number(node.state === "loaded"));+ if (!wanted.has(path) && node.presence === 0) { nodes.delete(path); removed = true; }+ }+ for (const [key, edge] of edges) {+ edge.presence = approach(edge.presence, wantedEdges.has(key) ? 1 : 0);+ edge.emphasis = approach(edge.emphasis, highlighted && edge.source !== highlighted && edge.target !== highlighted ? 0.2 : 1);+ if (!wantedEdges.has(key) && edge.presence === 0) { edges.delete(key); removed = true; }+ }+ if (removed) frame = { nodes: [...nodes.values()], edges: [...edges.values()] };+ return { moving, removed };+ },+ };+}diff --git a/webui/src/components/ui/dialog.tsx b/webui/src/components/ui/dialog.tsxindex 211b81442..4d9a27436 100644--- a/webui/src/components/ui/dialog.tsx+++ b/webui/src/components/ui/dialog.tsx@@ -41,26 +41,29 @@ DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;const DialogPositionedContent = React.forwardRef<React.ElementRef<typeof DialogPrimitive.Content>,React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & {+ contained?: boolean;positionerStyle?: React.CSSProperties;placement?: "center" | "bottom";overlayClassName?: string;}->(({ positionerStyle, placement, overlayClassName, ...props }, ref) => (- <DialogOverlay forceMount className={overlayClassName}>- <div className={cn("fixed inset-0 z-50 flex items-start justify-center overflow-y-auto overscroll-contain", placement !== "bottom" && "p-4")} style={{+>(({ contained, positionerStyle, placement, overlayClassName, ...props }, ref) => {+ const Overlay = contained ? "div" : DialogOverlay;+ return <Overlay data-dialog-backdrop {...(contained ? {} : { forceMount: true })} className={cn(contained && "absolute inset-0 z-50", overlayClassName)}>+ <div className={cn("fixed inset-0 z-50 flex items-start justify-center overscroll-contain", placement === "bottom" ? "overflow-clip" : "overflow-y-auto p-4", contained && "absolute")} style={{top: "var(--app-viewport-top, 0px)",height: "var(--app-viewport-height, 100%)",bottom: "auto",- ...positionerStyle,+ ...(contained ? { top: 0, height: "100%" } : positionerStyle),}}><DialogPrimitive.Content ref={ref} {...props} /></div>- </DialogOverlay>-));+ </Overlay>;+});DialogPositionedContent.displayName = "DialogPositionedContent";interface DialogContentPropsextends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> {+ portalContainer?: HTMLElement | null;showCloseButton?: boolean;overlayClassName?: string;layoutAnchor?: HTMLElement | null;@@ -71,10 +74,73 @@ interface DialogContentPropsconst DialogContent = React.forwardRef<React.ElementRef<typeof DialogPrimitive.Content>,DialogContentProps->(({ className, children, showCloseButton = true, overlayClassName, placement = "center", layoutAnchor: explicitLayoutAnchor, centerInLayoutAnchor = false, onOpenAutoFocus, ...props }, ref) => {+>(({ className, children, portalContainer, showCloseButton = true, overlayClassName, placement = "center", layoutAnchor: explicitLayoutAnchor, centerInLayoutAnchor = false, onOpenAutoFocus, ...props }, ref) => {const { t } = useTranslation();const [container, setContainer] = React.useState<HTMLDivElement | null>(null);const contentNode = React.useRef<HTMLDivElement | null>(null);+ const gesture = React.useRef<{ id: number; start: number; y: number; time: number; speed: number; moved: boolean } | null>(null);+ const suppressClick = React.useRef(false);+ const settleAnimation = React.useRef<Animation | null>(null);+ const backdropFrame = React.useRef<number | null>(null);+ const dragBackdrop = React.useRef<{ node: HTMLElement; color: string; blur: number } | null>(null);+ const paintBackdrop = (distance: number, height: number) => {+ const backdrop = dragBackdrop.current;+ if (!backdrop) return;+ const remaining = 1 - Math.min(1, Math.max(0, distance) / Math.max(1, height));+ backdrop.node.style.backgroundColor = `color-mix(in srgb, ${backdrop.color} ${remaining * 100}%, transparent)`;+ backdrop.node.style.backdropFilter = `blur(${backdrop.blur * remaining}px)`;+ };+ const cancelBackdropFrame = () => {+ if (backdropFrame.current !== null) cancelAnimationFrame(backdropFrame.current);+ backdropFrame.current = null;+ };+ React.useEffect(() => () => {+ settleAnimation.current?.cancel();+ if (backdropFrame.current !== null) cancelAnimationFrame(backdropFrame.current);+ }, []);+ const finishDrag = (button: HTMLButtonElement, pointerId: number, cancelled: boolean) => {+ const drag = gesture.current;+ const node = contentNode.current;+ if (!drag || drag.id !== pointerId || !node) return;+ gesture.current = null;+ suppressClick.current = drag.moved;+ if (!drag.moved) {+ if (dragBackdrop.current) {+ const style = dragBackdrop.current.node.style;+ for (const property of ["background-color", "backdrop-filter", "transition"]) style.removeProperty(property);+ dragBackdrop.current = null;+ }+ return;+ }+ const distance = Math.max(0, drag.y - drag.start);+ const dismiss = !cancelled && (distance > Math.min(120, node.offsetHeight * 0.22)+ || (distance > 24 && drag.speed > 0.65 && performance.now() - drag.time < 100));+ const destination = dismiss ? node.offsetHeight : 0;+ const animation = node.animate([{ translate: `0 ${distance}px` }, { translate: `0 ${destination}px` }], {+ duration: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? 0 : dismiss ? 180 : 260,+ easing: "cubic-bezier(0.2, 0, 0, 1)", fill: "forwards",+ });+ settleAnimation.current = animation;+ const follow = () => {+ paintBackdrop(parseFloat(getComputedStyle(node).getPropertyValue("translate").split(" ")[1]) || 0, node.offsetHeight);+ backdropFrame.current = requestAnimationFrame(follow);+ };+ backdropFrame.current = requestAnimationFrame(follow);+ animation.onfinish = () => {+ cancelBackdropFrame();+ node.style.translate = `0 ${destination}px`;+ paintBackdrop(destination, node.offsetHeight);+ if (!dismiss && dragBackdrop.current) {+ const style = dragBackdrop.current.node.style;+ for (const property of ["background-color", "backdrop-filter", "transition"]) style.removeProperty(property);+ dragBackdrop.current = null;+ }+ animation.cancel();+ settleAnimation.current = null;+ if (dismiss) { suppressClick.current = false; button.click(); }+ };+ };+const inheritedLayoutAnchor = React.useContext(DialogLayoutContext);const layoutAnchor = explicitLayoutAnchor ?? inheritedLayoutAnchor;const [layout, setLayout] = React.useState<React.CSSProperties>();@@ -114,13 +180,22 @@ const DialogContent = React.forwardRef<}, [layoutAnchor, placement, centerInLayoutAnchor]);const contentRef = React.useCallback((node: HTMLDivElement | null) => {contentNode.current = node;+ if (!node) {+ settleAnimation.current?.cancel();+ settleAnimation.current = null;+ if (backdropFrame.current !== null) cancelAnimationFrame(backdropFrame.current);+ backdropFrame.current = null;+ dragBackdrop.current = null;+ gesture.current = null;+ }setContainer(node);if (typeof ref === "function") ref(node);else if (ref) ref.current = node;}, [ref]);return (- <DialogPortal>+ <DialogPortal container={portalContainer}><DialogPositionedContent+ contained={!!portalContainer}positionerStyle={layout}placement={placement}overlayClassName={overlayClassName}@@ -136,9 +211,10 @@ const DialogContent = React.forwardRef<modalSurfaceClassName,"relative grid w-full max-w-lg gap-4 p-6 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 motion-reduce:animate-none",placement === "bottom"- ? "mt-auto max-h-[85dvh] overflow-y-auto overscroll-contain rounded-t-modal pb-[max(1rem,env(safe-area-inset-bottom))] data-[state=open]:slide-in-from-bottom-4 data-[state=closed]:slide-out-to-bottom-4"+ ? "mt-auto max-h-[85dvh] overflow-y-auto overscroll-contain rounded-t-modal pb-[max(1rem,env(safe-area-inset-bottom))] data-[state=open]:slide-in-from-bottom-full data-[state=closed]:slide-out-to-bottom-full ease-[cubic-bezier(0.2,0,0,1)] duration-300": "my-auto origin-center rounded-modal data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",className,+ placement === "bottom" && "pt-9 transition-none",)}{...props}>@@ -146,8 +222,45 @@ const DialogContent = React.forwardRef<{children}</FloatingPortalContext.Provider>{showCloseButton ? (- <DialogPrimitive.Close className={cn("absolute right-2.5 top-2.5 grid place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none", placement === "bottom" ? "h-11 w-11" : "h-7 w-7")}>- <X className="h-4 w-4" />+ <DialogPrimitive.Close+ onPointerDown={(event) => {+ if (placement !== "bottom" || !event.isPrimary || event.button !== 0) return;+ const node = contentNode.current;+ const offset = node ? parseFloat(getComputedStyle(node).getPropertyValue("translate").split(" ")[1]) || 0 : 0;+ cancelBackdropFrame();+ settleAnimation.current?.cancel();+ if (node) node.style.translate = `0 ${offset}px`;+ const backdrop = node?.closest<HTMLElement>("[data-dialog-backdrop]");+ if (backdrop && !dragBackdrop.current) {+ const style = getComputedStyle(backdrop);+ dragBackdrop.current = { node: backdrop, color: style.backgroundColor,+ blur: parseFloat(style.getPropertyValue("backdrop-filter").match(/blur\(([^)]+)/)?.[1] ?? "0") || 0 };+ backdrop.style.transition = "none";+ backdrop.style.animation = "none";+ }+ suppressClick.current = false;+ gesture.current = { id: event.pointerId, start: event.clientY - offset, y: event.clientY, time: performance.now(), speed: 0, moved: offset > 5 };+ event.currentTarget.setPointerCapture(event.pointerId);+ }}+ onPointerMove={(event) => {+ const drag = gesture.current;+ if (!drag || drag.id !== event.pointerId) return;+ const now = performance.now();+ drag.speed = (event.clientY - drag.y) / Math.max(1, now - drag.time);+ drag.y = event.clientY; drag.time = now;+ drag.moved ||= Math.abs(drag.y - drag.start) > 5;+ if (contentNode.current) {+ const distance = Math.max(0, drag.y - drag.start);+ contentNode.current.style.translate = `0 ${distance}px`;+ paintBackdrop(distance, contentNode.current.offsetHeight);+ }+ }}+ onPointerUp={(event) => finishDrag(event.currentTarget, event.pointerId, false)}+ onPointerCancel={(event) => finishDrag(event.currentTarget, event.pointerId, true)}+ onLostPointerCapture={(event) => finishDrag(event.currentTarget, event.pointerId, true)}+ onClick={(event) => { if (suppressClick.current) { event.preventDefault(); suppressClick.current = false; } }}+ className={cn("absolute grid place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none", placement === "bottom" ? "left-1/2 top-0 h-8 w-16 -translate-x-1/2 touch-none cursor-grab active:cursor-grabbing" : "right-2.5 top-2.5 h-7 w-7")}>+ {placement === "bottom" ? <span aria-hidden="true" className="h-1 w-9 rounded-full bg-current opacity-40" /> : <X className="h-4 w-4" />}<span className="sr-only">{t("common.close")}</span></DialogPrimitive.Close>) : null}diff --git a/webui/src/components/ui/floating-surface.ts b/webui/src/components/ui/floating-surface.tsindex c4a9e82d4..7a3446b2c 100644--- a/webui/src/components/ui/floating-surface.ts+++ b/webui/src/components/ui/floating-surface.ts@@ -12,6 +12,9 @@ export const modalOverlayClassName =export const modalSurfaceClassName ="outline-none bg-background text-foreground shadow-[0_12px_36px_rgba(15,23,42,0.12)] dark:bg-popover dark:shadow-[0_18px_44px_rgba(0,0,0,0.32)]";+export const sidePanelSurfaceClassName =+ "side-panel-surface outline-none bg-background text-foreground dark:bg-popover overflow-hidden rounded-[24px]";+export const floatingSurfaceClassName =`${floatingSurfaceVisualClassName} z-50 overflow-x-hidden overflow-y-auto overscroll-contain scrollbar-thin`;diff --git a/webui/src/components/ui/image-viewport.tsx b/webui/src/components/ui/image-viewport.tsxindex e3afca759..0ee903021 100644--- a/webui/src/components/ui/image-viewport.tsx+++ b/webui/src/components/ui/image-viewport.tsx@@ -1,3 +1,4 @@+import { surfaceFocusProps } from "@/lib/surface-focus";import { useCallback, useEffect, useRef, useState, type PointerEvent } from "react";import { Minus, Plus } from "lucide-react";import { useTranslation } from "react-i18next";@@ -121,8 +122,8 @@ export function ImageViewport({const buttonClass = "grid size-9 shrink-0 place-items-center rounded-full transition-colors hover:text-foreground disabled:opacity-30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";return <>- <div ref={viewport} data-testid={testId} tabIndex={0} role="group" aria-label={t("lightbox.gestures")}- className={cn("flex min-h-0 min-w-0 touch-none select-none items-center justify-center overflow-hidden focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring", view.scale > 1 ? dragging ? "cursor-grabbing" : "cursor-grab" : "cursor-zoom-in", className)}+ <div ref={viewport} data-testid={testId} {...surfaceFocusProps} tabIndex={0} role="group" aria-label={t("lightbox.gestures")}+ className={cn("flex min-h-0 min-w-0 touch-none select-none items-center justify-center overflow-hidden outline-none data-[keyboard-focus]:ring-1 data-[keyboard-focus]:ring-ring", view.scale > 1 ? dragging ? "cursor-grabbing" : "cursor-grab" : "cursor-zoom-in", className)}onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={endPointer} onPointerCancel={endPointer} onLostPointerCapture={endPointer}onDoubleClick={(event) => zoom(viewRef.current.scale > 1 ? 1 : 2, { x: event.clientX, y: event.clientY })}onKeyDown={(event) => {diff --git a/webui/src/components/ui/sheet.tsx b/webui/src/components/ui/sheet.tsxindex 00d3d9de0..15f03d6a3 100644--- a/webui/src/components/ui/sheet.tsx+++ b/webui/src/components/ui/sheet.tsx@@ -5,6 +5,7 @@ import { cva, type VariantProps } from "class-variance-authority";import { useTranslation } from "react-i18next";import { cn } from "@/lib/utils";+import { modalOverlayClassName, sidePanelSurfaceClassName } from "./floating-surface";const Sheet = DialogPrimitive.Root;const SheetTrigger = DialogPrimitive.Trigger;@@ -29,7 +30,7 @@ const SheetOverlay = React.forwardRef<SheetOverlay.displayName = DialogPrimitive.Overlay.displayName;const sheetVariants = cva(- "fixed z-50 flex flex-col gap-4 bg-background outline-none transition ease-in-out",+ "fixed z-50 flex flex-col gap-4 bg-background outline-none ease-out",{variants: {side: {@@ -42,12 +43,14 @@ const sheetVariants = cva("data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",),left: cn(- "inset-y-0 left-0 h-full w-3/4 sm:max-w-sm",- "data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left",+ "inset-y-2 left-2 w-3/4 max-w-[calc(100vw-1rem)] sm:max-w-sm",+ sidePanelSurfaceClassName,+ "data-[state=closed]:slide-out-to-left-4 data-[state=open]:slide-in-from-left-4",),right: cn(- "inset-y-0 right-0 h-full w-3/4 sm:max-w-sm",- "data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right",+ "inset-y-2 right-2 w-3/4 max-w-[calc(100vw-1rem)] sm:max-w-sm",+ sidePanelSurfaceClassName,+ "data-[state=closed]:slide-out-to-right-4 data-[state=open]:slide-in-from-right-4",),},},@@ -83,13 +86,13 @@ const SheetContent = React.forwardRef<const { t } = useTranslation();return (<SheetPortal>- <SheetOverlay className={overlayClassName} />+ <SheetOverlay className={cn((side === "right" || side === "left") && modalOverlayClassName, overlayClassName)} /><DialogPrimitive.Contentref={ref}className={cn(sheetVariants({ side }),"data-[state=open]:animate-in data-[state=closed]:animate-out",- "duration-300 motion-reduce:transition-none",+ "data-[state=open]:fade-in-0 data-[state=closed]:fade-out-0 duration-200 motion-reduce:transition-none","motion-reduce:data-[state=open]:animate-none motion-reduce:data-[state=closed]:animate-none",className,)}@@ -99,7 +102,7 @@ const SheetContent = React.forwardRef<{showCloseButton ? (<DialogPrimitive.CloseclassName={cn(- "absolute right-4 top-4 rounded-mark opacity-70 ring-offset-background transition-opacity",+ "absolute right-2 top-2 grid size-10 place-items-center rounded-full opacity-70 ring-offset-background transition-opacity","hover:opacity-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","disabled:pointer-events-none",closeButtonClassName,diff --git a/webui/src/components/ui/sidebar-panel.tsx b/webui/src/components/ui/sidebar-panel.tsxnew file mode 100644index 000000000..7a84f7e44--- /dev/null+++ b/webui/src/components/ui/sidebar-panel.tsx@@ -0,0 +1,68 @@+import { createContext, forwardRef, useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type HTMLAttributes, type ReactNode } from "react";+import { useReducedMotion } from "motion/react";+import { cn } from "@/lib/utils";++interface SidebarPanelProps extends HTMLAttributes<HTMLElement> {+ header?: ReactNode;+ width: number;+ isClosing?: boolean;+ open?: boolean;+ floating?: boolean;+ contentClassName?: string;+}++export const SidebarPanelActionsContext = createContext<HTMLElement | null>(null);++/** Retain the same surface through exit, including an interrupted close. */+export const SidebarPanel = forwardRef<HTMLElement, SidebarPanelProps>(function SidebarPanel({+ open = true, isClosing, ...props+}, ref) {+ const [present, setPresent] = useState(open);+ const reducedMotion = useReducedMotion();+ useEffect(() => {+ if (open) { setPresent(true); return; }+ const timer = window.setTimeout(() => setPresent(false), reducedMotion ? 0 : 300);+ return () => window.clearTimeout(timer);+ }, [open, reducedMotion]);+ return open || present ? <SidebarPanelContent {...props} ref={ref} isClosing={isClosing || !open} /> : null;+});++/** Shared nonmodal side slot. Contents keep their final width while the slot opens. */+const SidebarPanelContent = forwardRef<HTMLElement, SidebarPanelProps>(function SidebarPanelContent({+ width, isClosing = false, floating = false, header, contentClassName, className, style, children, ...props+}, forwardedRef) {+ const panel = useRef<HTMLElement | null>(null);+ const [entered, setEntered] = useState(false);+ const [actionsHost, setActionsHost] = useState<HTMLElement | null>(null);+ const setPanel = useCallback((node: HTMLElement | null) => {+ panel.current = node;+ if (typeof forwardedRef === "function") forwardedRef(node);+ else if (forwardedRef) forwardedRef.current = node;+ }, [forwardedRef]);+ useLayoutEffect(() => {+ // Commit the outgoing slot width before transitioning to the replacement width.+ panel.current?.getBoundingClientRect();+ let frame = requestAnimationFrame(() => { frame = requestAnimationFrame(() => setEntered(true)); });+ return () => cancelAnimationFrame(frame);+ }, []);+ return <aside {...props} ref={setPanel} data-closing={isClosing || undefined}+ style={{+ "--file-preview-width": `${width}px`,+ "--file-preview-slot-width": isClosing ? "0px" : !entered ? "var(--sidebar-enter-width, 0px)" : `${width}px`,+ "--file-preview-mobile-width": isClosing ? "0px" : !entered ? "var(--sidebar-enter-mobile-width, 0px)" : "100%",+ ...style,+ } as CSSProperties}+ className={cn("file-preview-pane z-30 min-h-0 w-[var(--file-preview-mobile-width)] overflow-hidden duration-300 ease-[cubic-bezier(0.2,0,0,1)] motion-reduce:transition-none",+ entered ? "transition-[width]" : "transition-none",+ floating ? "fixed inset-y-2 right-2 max-w-[420px]" : "absolute inset-y-0 right-0", isClosing && "pointer-events-none", className)}>+ <div className={cn("file-preview-content absolute inset-y-2 right-2 flex min-h-0 w-[calc(100cqw-1rem)] flex-col pb-[env(safe-area-inset-bottom)] transition-[opacity,transform] duration-200 ease-out motion-reduce:transition-none",+ floating && "w-[calc(min(420px,100vw)-1rem)]",+ !entered || isClosing ? "translate-x-2 opacity-0" : "translate-x-0 opacity-100", contentClassName)}>+ {header && <div className="flex min-h-10 shrink-0 items-center gap-1 border-b border-border/40 px-2 pt-2">+ {header}+ <div ref={setActionsHost} className="shrink-0" />+ </div>}+ <SidebarPanelActionsContext.Provider value={actionsHost}>{children}</SidebarPanelActionsContext.Provider>+ </div>+ </aside>;+});diff --git a/webui/src/components/workbench/PaneWorkbench.tsx b/webui/src/components/workbench/PaneWorkbench.tsxindex f6a988527..3f2a64756 100644--- a/webui/src/components/workbench/PaneWorkbench.tsx+++ b/webui/src/components/workbench/PaneWorkbench.tsx@@ -25,10 +25,8 @@ import { Button } from "@/components/ui/button";import {DropdownMenu,DropdownMenuContent,- DropdownMenuLabel,DropdownMenuRadioGroup,DropdownMenuRadioItem,- DropdownMenuSeparator,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";import { HoverHint } from "@/components/ui/tooltip";@@ -634,10 +632,6 @@ export function PaneWorkbench({align="end"onCloseAutoFocus={(event) => event.preventDefault()}>- <DropdownMenuLabel>- {t("workbench.layout", { defaultValue: "Pane layout" })}- </DropdownMenuLabel>- <DropdownMenuSeparator /><DropdownMenuRadioGroupvalue={layout}onValueChange={(value) => {@@ -701,8 +695,8 @@ export function PaneWorkbench({data-testid="pane-grid"data-layout={effectiveLayout}className={cn(- "grid h-full min-h-0 min-w-0 overflow-hidden",- chrome && displayedPanes.length > 1 && "gap-px bg-border/55",+ "grid h-full min-h-0 min-w-0 overflow-hidden bg-background",+ chrome && displayedPanes.length > 1 && "gap-px",)}style={gridStyle}>@@ -723,7 +717,10 @@ export function PaneWorkbench({data-testid={`workbench-pane-${pane.key}`}onPointerDownCapture={(event) => handlePanePointerDown(pane.key, event)}onFocusCapture={(event) => handlePaneFocus(pane.key, event)}- className="workbench-pane relative flex min-h-0 min-w-0 overflow-hidden bg-background"+ className={cn(+ "workbench-pane relative flex min-h-0 min-w-0 overflow-hidden bg-background",+ chrome && displayedPanes.length > 1 && "shadow-[0_0_0_1px_hsl(var(--border)/0.55)]",+ )}style={layoutGeometry.paneStyles[index]}>{renderPane(pane, {diff --git a/webui/src/dev/gallery/content.tsx b/webui/src/dev/gallery/content.tsxindex c012eb2da..27b0b8bf7 100644--- a/webui/src/dev/gallery/content.tsx+++ b/webui/src/dev/gallery/content.tsx@@ -65,7 +65,7 @@ function SessionPreview() {}}><StatePicker label={t("previews.session.state")} value={mode} options={["ready", "loading", "error", "empty", "action_error"]}onChange={(next) => { setMode(next); setJobs(exampleJobs(now)); setAction(null); }} />- <SessionInfoPopoverView title="组件设计" jobs={mode === "ready" || mode === "action_error" ? displayJobs(jobs) : []} loading={mode === "loading"} loadFailed={mode === "error"} now={now}+ <SessionInfoPopoverView jobs={mode === "ready" || mode === "action_error" ? displayJobs(jobs) : []} loading={mode === "loading"} loadFailed={mode === "error"} now={now}onOpenCalendar={() => setAction({ key: "previews.session.openedCalendar" })}onAction={(operation, job) => {if (mode === "action_error") return Promise.reject(new Error(t("previews.session.actionError")));@@ -106,7 +106,7 @@ export const contentExamples: ComponentExample[] = [code: '<FilePreviewPanelView path={path} state={previewState} imageOpen={imageOpen} onImageOpenChange={setImageOpen} onImageError={reportImageError} />' },{ title: "previews.session.title", files: ["webui/src/components/thread/SessionInfoPopoverView.tsx"], Preview: SessionPreview,description: "previews.session.description", options: "previews.session.options",- code: '<SessionInfoPopoverView title={title} jobs={jobs} loading={loading} loadFailed={failed} now={now} onAction={act} onEdit={edit} onOpenCalendar={openCalendar} />' },+ code: '<SessionInfoPopoverView jobs={jobs} loading={loading} loadFailed={failed} now={now} onAction={act} onEdit={edit} onOpenCalendar={openCalendar} />' },{ title: "previews.subagent.title", files: ["webui/src/components/thread/SubagentThreadView.tsx"], Preview: SubagentPreview,description: "previews.subagent.description", options: "previews.subagent.options",code: '<SubagentThreadView messages={messages} loading={loading} error={error} isStreaming={running} runStartedAt={startedAt} onRetry={retry} />' },diff --git a/webui/src/dev/gallery/conversation.tsx b/webui/src/dev/gallery/conversation.tsxindex 4a7f2d857..887336cfc 100644--- a/webui/src/dev/gallery/conversation.tsx+++ b/webui/src/dev/gallery/conversation.tsx@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";import { FallbackResponseSources } from "@/components/ResponseSourceBadge";import { AgentActivityCluster } from "@/components/thread/AgentActivityCluster";import { ComposerUsagePopover, type ComposerRoundUsage } from "@/components/thread/ComposerUsagePopover";+import type { ContextSnapshot } from "@/lib/types";import { ContextCompactionNotice } from "@/components/thread/ContextCompactionNotice";import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";import { ModelPresetBadge, type ModelPresetOption } from "@/components/thread/ModelPresetBadge";@@ -30,9 +31,9 @@ const presets: ModelPresetOption[] = [{ name: "推理", provider: "anthropic", model: "claude-sonnet-4", reasoningEffort: "high", contextWindowTokens: 200_000 },];const rounds: ComposerRoundUsage[] = [- { id: "gallery-round-1", timestamp: createdAt, inputTokens: 8_200, cachedTokens: 6_000, outputTokens: 620, generationMs: 3_100 },- { id: "gallery-round-2", timestamp: createdAt + 60_000, inputTokens: 12_000, cachedTokens: 8_200, outputTokens: 980, generationMs: 5_400 },- { id: "gallery-round-3", timestamp: createdAt + 120_000, inputTokens: 18_500, cachedTokens: 12_000, outputTokens: 1_240, generationMs: 7_200 },+ { inputTokens: 8_200, cachedTokens: 6_000, generationMs: 3_100 },+ { inputTokens: 12_000, cachedTokens: 8_200, generationMs: 5_400 },+ { inputTokens: 18_500, cachedTokens: 12_000, generationMs: 7_200 },];const commands: SlashCommand[] = [{ command: "/status", title: "previews.composer.statusCommand", description: "previews.composer.statusDescription", icon: "activity", lifecycle: "side_channel", acceptsArgs: false },@@ -102,14 +103,30 @@ function ModelPresetPreview() {</div>;}+const contextSnapshots: ContextSnapshot[] = [0, 1, 2].map((round) => ({+ id: `context-example-${round}`, contextWindowTokens: 128000,+ usage: { prompt_tokens: 28000 + round * 7300, context_tokens: 28000 + round * 7300, cached_tokens: 20000 + round * 7000, generation_ms: 8200 },+ graph: {+ nodes: [+ { path: "/workspace/MEMORY.md", name: "MEMORY.md", state: "loaded", tokens: 2100 },+ { path: "/workspace/SOUL.md", name: "SOUL.md", state: "loaded", tokens: 380 },+ { path: "/workspace/AGENTS.md", name: "AGENTS.md", state: "loaded", tokens: 1400 },+ { path: "/workspace/skills/nanobot-document/SKILL.md", name: "nanobot-document", state: "loaded", tokens: 550 },+ { path: "/workspace/skills/nanobot-document/references/architecture.md", name: "architecture.md", state: round ? "loaded" : "discovered", tokens: round * 1600 },+ { path: "/workspace/skills/nanobot-document/references/configuration.md", name: "configuration.md", state: "discovered", tokens: 0 },+ ],+ edges: ["architecture.md", "configuration.md"].map((name) => ({ source: "/workspace/skills/nanobot-document/SKILL.md", target: `/workspace/skills/nanobot-document/references/${name}` })),+ },+}));+function UsagePreview() {const { t } = useGalleryTranslation();- const [mode, setMode] = useState<"normal" | "caution" | "critical" | "rounds_only" | "sheet">("normal");+ const [mode, setMode] = useState<"normal" | "caution" | "critical" | "rounds_only">("normal");const tokens = mode === "critical" ? 192_000 : mode === "caution" ? 162_000 : 18_500;return <div className="space-y-4">- <StatePicker label={t("previews.usage.state")} value={mode} options={["normal", "caution", "critical", "rounds_only", "sheet"]} onChange={setMode} />+ <StatePicker label={t("previews.usage.state")} value={mode} options={["normal", "caution", "critical", "rounds_only"]} onChange={setMode} /><ComposerUsagePopover context={mode === "rounds_only" ? null : { contextTokens: tokens, contextWindowTokens: 200_000 }}- rounds={rounds} showLabel bottomSheet={mode === "sheet"} />+ rounds={rounds} snapshots={contextSnapshots} showLabel /><p className="text-sm text-muted-foreground">{t("previews.usage.hint")}</p></div>;}diff --git a/webui/src/dev/gallery/foundations.tsx b/webui/src/dev/gallery/foundations.tsxindex 64e24042f..91bbd97e8 100644--- a/webui/src/dev/gallery/foundations.tsx+++ b/webui/src/dev/gallery/foundations.tsx@@ -1,4 +1,5 @@import { useState } from "react";+import { SidebarPanel } from "@/components/ui/sidebar-panel";import { Plus } from "lucide-react";import { Button } from "@/components/ui/button";@@ -250,7 +251,23 @@ function ImageViewports() {}const base = "webui/src/components/ui/";+function Sidebars() {+ const { t } = useGalleryTranslation();+ const [open, setOpen] = useState(true);+ return <div className="space-y-3">+ <Button onClick={() => setOpen(!open)}>{t("controls.sidebarPanel.toggle")}</Button>+ <div className="thread-preview-layout relative h-64 overflow-hidden rounded-xl border">+ {open && <SidebarPanel width={320} header={<span>{t("controls.sidebarPanel.title")}</span>}>+ <p className="p-4 text-sm">{t("controls.sidebarPanel.content")}</p>+ </SidebarPanel>}+ </div>+ </div>;+}+export const foundationExamples: ComponentExample[] = [+ { title: "controls.sidebarPanel.title", files: ["sidebar-panel"], Preview: Sidebars,+ description: "controls.sidebarPanel.description", options: "controls.sidebarPanel.options",+ code: '<SidebarPanel width={320} header={<span>Details</span>}>{children}</SidebarPanel>' },{ title: "controls.button.title", files: ["button"], Preview: Buttons,description: "controls.button.description",options: "controls.button.options",diff --git a/webui/src/dev/gallery/locales/controls/en.json b/webui/src/dev/gallery/locales/controls/en.jsonindex da745c236..348c6f8b6 100644--- a/webui/src/dev/gallery/locales/controls/en.json+++ b/webui/src/dev/gallery/locales/controls/en.json@@ -504,5 +504,12 @@"view": "View invitation","dismissed": "Never remind again selected in preview","starred": "GitHub link selected in preview"+ },+ "sidebarPanel": {+ "title": "Sidebar panel",+ "toggle": "Toggle sidebar",+ "content": "Details stay inside the current pane.",+ "description": "A nonmodal side panel with a shared opening transition.",+ "options": "width, header, isClosing, floating, contentClassName"}}diff --git a/webui/src/dev/gallery/locales/controls/es.json b/webui/src/dev/gallery/locales/controls/es.jsonindex 5ab25f313..d1e0e41a3 100644--- a/webui/src/dev/gallery/locales/controls/es.json+++ b/webui/src/dev/gallery/locales/controls/es.json@@ -504,5 +504,12 @@"view": "Ver invitación","dismissed": "Se eligió no volver a recordar en la vista previa","starred": "Se eligió el enlace de GitHub en la vista previa"+ },+ "sidebarPanel": {+ "title": "Panel lateral",+ "toggle": "Mostrar u ocultar panel",+ "content": "Los detalles permanecen en el panel actual.",+ "description": "Un panel lateral no modal con una transición de apertura compartida.",+ "options": "width, header, isClosing, floating, contentClassName"}}diff --git a/webui/src/dev/gallery/locales/controls/fr.json b/webui/src/dev/gallery/locales/controls/fr.jsonindex 9ff62cc22..4a3c4f5fe 100644--- a/webui/src/dev/gallery/locales/controls/fr.json+++ b/webui/src/dev/gallery/locales/controls/fr.json@@ -504,5 +504,12 @@"view": "Voir l’invitation","dismissed": "Ne plus rappeler sélectionné dans l’aperçu","starred": "Lien GitHub sélectionné dans l’aperçu"+ },+ "sidebarPanel": {+ "title": "Panneau latéral",+ "toggle": "Afficher ou masquer le panneau",+ "content": "Les détails restent dans le volet actuel.",+ "description": "Un panneau latéral non modal avec une transition d’ouverture commune.",+ "options": "width, header, isClosing, floating, contentClassName"}}diff --git a/webui/src/dev/gallery/locales/controls/id.json b/webui/src/dev/gallery/locales/controls/id.jsonindex 2b604100b..1385bc44b 100644--- a/webui/src/dev/gallery/locales/controls/id.json+++ b/webui/src/dev/gallery/locales/controls/id.json@@ -504,5 +504,12 @@"view": "Lihat undangan","dismissed": "Jangan ingatkan lagi dipilih dalam pratinjau","starred": "Tautan GitHub dipilih dalam pratinjau"+ },+ "sidebarPanel": {+ "title": "Panel samping",+ "toggle": "Tampilkan atau sembunyikan panel",+ "content": "Detail tetap berada di panel saat ini.",+ "description": "Panel samping nonmodal dengan transisi pembukaan bersama.",+ "options": "width, header, isClosing, floating, contentClassName"}}diff --git a/webui/src/dev/gallery/locales/controls/ja.json b/webui/src/dev/gallery/locales/controls/ja.jsonindex e8cbb687a..edd3e4137 100644--- a/webui/src/dev/gallery/locales/controls/ja.json+++ b/webui/src/dev/gallery/locales/controls/ja.json@@ -504,5 +504,12 @@"view": "招待を表示","dismissed": "プレビューで今後表示しないを選択しました","starred": "プレビューで GitHub リンクを選択しました"+ },+ "sidebarPanel": {+ "title": "サイドパネル",+ "toggle": "パネルの表示を切り替え",+ "content": "詳細は現在のペイン内に表示されます。",+ "description": "共通の開くアニメーションを持つ非モーダルのサイドパネル。",+ "options": "width, header, isClosing, floating, contentClassName"}}diff --git a/webui/src/dev/gallery/locales/controls/ko.json b/webui/src/dev/gallery/locales/controls/ko.jsonindex 55635eb53..ac5cd4f06 100644--- a/webui/src/dev/gallery/locales/controls/ko.json+++ b/webui/src/dev/gallery/locales/controls/ko.json@@ -504,5 +504,12 @@"view": "안내 보기","dismissed": "미리보기에서 다시 알리지 않기를 선택했습니다","starred": "미리보기에서 GitHub 링크를 선택했습니다"+ },+ "sidebarPanel": {+ "title": "사이드 패널",+ "toggle": "패널 표시 전환",+ "content": "세부 정보는 현재 창 안에 표시됩니다.",+ "description": "공통 열기 전환 효과를 사용하는 비모달 사이드 패널입니다.",+ "options": "width, header, isClosing, floating, contentClassName"}}diff --git a/webui/src/dev/gallery/locales/controls/pt-BR.json b/webui/src/dev/gallery/locales/controls/pt-BR.jsonindex 0bf9a8406..ee000b30a 100644--- a/webui/src/dev/gallery/locales/controls/pt-BR.json+++ b/webui/src/dev/gallery/locales/controls/pt-BR.json@@ -504,5 +504,12 @@"view": "Ver convite","dismissed": "Nunca mais lembrar selecionado na prévia","starred": "Link do GitHub selecionado na prévia"+ },+ "sidebarPanel": {+ "title": "Painel lateral",+ "toggle": "Alternar painel",+ "content": "Os detalhes permanecem no painel atual.",+ "description": "Um painel lateral não modal com uma transição de abertura compartilhada.",+ "options": "width, header, isClosing, floating, contentClassName"}}diff --git a/webui/src/dev/gallery/locales/controls/vi.json b/webui/src/dev/gallery/locales/controls/vi.jsonindex ac9110dbd..fc9827be4 100644--- a/webui/src/dev/gallery/locales/controls/vi.json+++ b/webui/src/dev/gallery/locales/controls/vi.json@@ -504,5 +504,12 @@"view": "Xem lời mời","dismissed": "Đã chọn không nhắc lại trong bản xem trước","starred": "Đã chọn liên kết GitHub trong bản xem trước"+ },+ "sidebarPanel": {+ "title": "Bảng bên",+ "toggle": "Ẩn hoặc hiện bảng",+ "content": "Chi tiết nằm trong ngăn hiện tại.",+ "description": "Bảng bên không khóa giao diện với hiệu ứng mở dùng chung.",+ "options": "width, header, isClosing, floating, contentClassName"}}diff --git a/webui/src/dev/gallery/locales/controls/zh-CN.json b/webui/src/dev/gallery/locales/controls/zh-CN.jsonindex 91b449460..20696735d 100644--- a/webui/src/dev/gallery/locales/controls/zh-CN.json+++ b/webui/src/dev/gallery/locales/controls/zh-CN.json@@ -504,5 +504,12 @@"view": "查看邀请","dismissed": "预览中选择了不再提醒","starred": "预览中选择了 GitHub 链接"+ },+ "sidebarPanel": {+ "title": "侧边面板",+ "toggle": "切换侧边面板",+ "content": "详情保留在当前窗格内。",+ "description": "非模态侧边面板,使用统一的展开动画。",+ "options": "width, header, isClosing, floating, contentClassName"}}diff --git a/webui/src/dev/gallery/locales/controls/zh-TW.json b/webui/src/dev/gallery/locales/controls/zh-TW.jsonindex 2a27be077..37f7c6025 100644--- a/webui/src/dev/gallery/locales/controls/zh-TW.json+++ b/webui/src/dev/gallery/locales/controls/zh-TW.json@@ -504,5 +504,12 @@"view": "查看邀請","dismissed": "已在預覽中選取不再提醒","starred": "已在預覽中選取 GitHub 連結"+ },+ "sidebarPanel": {+ "title": "側邊面板",+ "toggle": "切換側邊面板",+ "content": "詳細資訊保留在目前的窗格內。",+ "description": "非模態側邊面板,使用統一的展開動畫。",+ "options": "width, header, isClosing, floating, contentClassName"}}diff --git a/webui/src/globals.css b/webui/src/globals.cssindex a05d963c2..be83ab373 100644--- a/webui/src/globals.css+++ b/webui/src/globals.css@@ -855,9 +855,32 @@.thread-preview-layout {container: thread-preview-layout / inline-size;}+ .context-expanded-overlay[data-state="open"] {+ animation: context-backdrop-in 250ms ease-out;+ }+ .context-expanded-overlay[data-state="closed"] {+ animation: context-backdrop-in 250ms ease-out reverse;+ }+ @keyframes context-backdrop-in {+ from { opacity: 0; backdrop-filter: blur(0); }+ to { opacity: 1; backdrop-filter: blur(12px); }+ }+ @media (prefers-reduced-motion: reduce) {+ .context-expanded-overlay { animation: none !important; }+ }+ /* Sidebars share the full pane height with a local conversation composer. */+ .workbench-composer-footer:not(:has([data-active-composer])) {+ display: none;+ }/* A split needs 420px for the conversation plus 360px for the preview.Narrow workbench panes use the same contained overlay as a phone. */@container thread-preview-layout (min-width: 780px) {+ /* A replacement owns the slot while the outgoing surface fades over it. */+ .thread-preview-layout:has(> .file-preview-pane:not([data-closing])) > .file-preview-pane[data-closing] {+ position: absolute;+ width: var(--file-preview-width);+ z-index: 30;+ }.file-preview-pane {position: relative;z-index: auto;@@ -866,7 +889,8 @@flex-shrink: 0;}.file-preview-content {- width: var(--file-preview-width);+ width: calc(var(--file-preview-width) - 1rem);+ bottom: var(--sidebar-bottom-inset, calc(1.125rem + env(safe-area-inset-bottom)));padding-bottom: 0;}.file-preview-resize {@@ -879,6 +903,27 @@visibility: hidden;}}+ @media (max-width: 639px) {+ .context-drawer-backdrop {+ animation: context-drawer-backdrop-in 150ms cubic-bezier(0.2, 0, 0, 1);+ transition: background-color 150ms cubic-bezier(0.2, 0, 0, 1), backdrop-filter 150ms cubic-bezier(0.2, 0, 0, 1);+ }+ .context-drawer-backdrop:has(.context-drawer-panel[data-state="closed"]) {+ animation: none;+ background-color: transparent;+ backdrop-filter: blur(0px);+ }+ }+ @keyframes context-drawer-backdrop-in {+ from { background-color: transparent; backdrop-filter: blur(0px); }+ to { background-color: rgb(0 0 0 / 0.25); backdrop-filter: blur(8px); }+ }+ @media (prefers-reduced-motion: reduce) {+ .context-drawer-backdrop { animation: none; transition: none; }+ }+ .thread-preview-layout:has(.context-drawer-panel) > .thread-conversation {+ visibility: visible;+ }.thread-preview-layout[data-preview-open] > .thread-conversation {--thread-header-position: relative;}@@ -947,9 +992,8 @@display: inline;}- /* Markdown tables wrap cell text to fit the conversation column. The- renderer's overflow-x:auto wrapper remains a fallback for content that- cannot shrink. */+ /* Markdown table cells retain whole-word minimum widths. The renderer's+ overflow-x:auto wrapper contains tables wider than the preview or chat. */.thread-viewport-scrollbar {overflow-x: hidden;@@ -1184,16 +1228,25 @@}}-.thread-composer-surface {+.thread-composer-surface,+.context-inspector-surface,+.user-message-surface,+.side-panel-surface {--composer-shadow-color: 240 10% 16%;--tw-shadow: inset 0 0 0 1px hsl(var(--border) / 0.75), 0 4px 18px -8px hsl(var(--composer-shadow-color) / 0.12);box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);+}++.thread-composer-surface {transition: var(--theme-paint-transition, background-color 160ms ease-out, box-shadow 160ms ease-out), opacity 160ms ease-out;container-name: thread-composer;container-type: inline-size;}-.dark .thread-composer-surface {+.dark .thread-composer-surface,+.dark .context-inspector-surface,+.dark .user-message-surface,+.dark .side-panel-surface {--composer-shadow-color: 240 12% 3%;}@@ -1202,8 +1255,9 @@}@media (forced-colors: active) {- .thread-composer-surface { outline: 1px solid CanvasText; }+ .thread-composer-surface, .context-inspector-surface, .user-message-surface, .side-panel-surface { outline: 1px solid CanvasText; }.thread-composer-surface:focus-within { outline: 2px solid Highlight; }+ [data-keyboard-focus] { outline: 2px solid Highlight; outline-offset: -2px; }}.thread-composer-footer-actions {diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.jsonindex a1ca0aa8a..d6f32f3f7 100644--- a/webui/src/i18n/locales/en/common.json+++ b/webui/src/i18n/locales/en/common.json@@ -2064,8 +2064,6 @@"sessionInfo": "Session details"},"sessionInfo": {- "title": "Session",- "untitled": "Untitled topic","automations": "Automations","count": "{{count}}","loading": "Loading automations...",@@ -2117,15 +2115,21 @@"reauthFallback": "A fallback model handled this response.","reauthSettings": "Open model settings","context": {+ "loaded": "Loaded",+ "unloaded": "Not loaded",+ "expand": "Expand context panel",+ "collapse": "Collapse context panel",+ "noFiles": "No context recorded yet",+ "estimatedNodeTokens": "About {{value}} tokens",+ "openFile": "Open file",+ "history": "Context history",+ "playHistory": "Play context history","tooltip": "Context {{percent}}%","detailsLabel": "Open context usage","panelTitle": "Context usage","contextTitle": "Context",- "recentRounds": "Recent rounds",- "inputTrend": "Input tokens",- "input": "Input tokens",- "cacheHitRate": "KV cache hit rate",- "output": "Output tokens",+ "cacheHitRate": "Cache hit rate",+ "tokenUsage": "{{used}} / {{limit}}","duration": "Generation time"},"queued": {@@ -2533,8 +2537,7 @@"fileEditDiffTruncated": "Diff truncated. Open the file for the full change.","usage": {"context": "Context now: {{tokens}}{{capacity}}",- "requests": "{{count}} calls this turn",- "estimated": "Includes estimated usage"+ "requests": "{{count}} calls this turn"}},"recovery": {diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.jsonindex 2a79795db..806a3938a 100644--- a/webui/src/i18n/locales/es/common.json+++ b/webui/src/i18n/locales/es/common.json@@ -1859,8 +1859,6 @@"sessionInfo": "Detalles de la sesión"},"sessionInfo": {- "title": "Sesión",- "untitled": "Tema sin título","automations": "Automatizaciones","count": "{{count}}","loading": "Cargando automatizaciones...",@@ -1912,15 +1910,21 @@"reauthFallback": "Un modelo alternativo respondió esta vez.","reauthSettings": "Abrir ajustes del modelo","context": {+ "loaded": "Cargado",+ "unloaded": "Sin cargar",+ "expand": "Ampliar contexto",+ "collapse": "Reducir contexto",+ "noFiles": "Aún no hay contexto registrado",+ "estimatedNodeTokens": "Unos {{value}} tokens",+ "openFile": "Abrir archivo",+ "history": "Historial de contexto",+ "playHistory": "Reproducir historial del contexto","tooltip": "Contexto {{percent}}%","detailsLabel": "Abrir uso del contexto","panelTitle": "Uso del contexto","contextTitle": "Contexto",- "recentRounds": "Rondas recientes",- "inputTrend": "Tokens de entrada",- "input": "Tokens de entrada",- "cacheHitRate": "Tasa de aciertos de KV Cache",- "output": "Tokens de salida",+ "cacheHitRate": "Tasa de aciertos de caché",+ "tokenUsage": "{{used}} / {{limit}}","duration": "Tiempo de generación"},"queued": {@@ -2148,8 +2152,7 @@"fileEditDiffTruncated": "Diferencias truncadas. Abre el archivo para ver el cambio completo.","usage": {"context": "Contexto más reciente: {{tokens}}{{capacity}} tokens",- "requests": "{{count}} solicitudes al modelo",- "estimated": "Incluye uso estimado"+ "requests": "{{count}} solicitudes al modelo"},"activityThinkingFor": "Pensando durante {{duration}}","activityThought": "Pensamiento completado",diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.jsonindex a5096c304..d94ae1a21 100644--- a/webui/src/i18n/locales/fr/common.json+++ b/webui/src/i18n/locales/fr/common.json@@ -1858,8 +1858,6 @@"sessionInfo": "Détails de la session"},"sessionInfo": {- "title": "Session",- "untitled": "Sujet sans titre","automations": "Automatisations","count": "{{count}}","loading": "Chargement des automatisations...",@@ -1911,15 +1909,21 @@"reauthFallback": "Un modèle de secours a traité cette réponse.","reauthSettings": "Ouvrir les paramètres du modèle","context": {+ "loaded": "Chargé",+ "unloaded": "Non chargé",+ "expand": "Agrandir le contexte",+ "collapse": "Réduire le contexte",+ "noFiles": "Aucun contexte enregistré pour le moment",+ "estimatedNodeTokens": "Environ {{value}} tokens",+ "openFile": "Ouvrir le fichier",+ "history": "Historique du contexte",+ "playHistory": "Lire l’historique du contexte","tooltip": "Contexte {{percent}} %","detailsLabel": "Ouvrir l’utilisation du contexte","panelTitle": "Utilisation du contexte","contextTitle": "Contexte",- "recentRounds": "Tours récents",- "inputTrend": "Jetons d’entrée",- "input": "Jetons d’entrée",- "cacheHitRate": "Taux de succès du cache KV",- "output": "Jetons de sortie",+ "cacheHitRate": "Taux de réussite du cache",+ "tokenUsage": "{{used}} / {{limit}}","duration": "Temps de génération"},"queued": {@@ -2147,8 +2151,7 @@"fileEditDiffTruncated": "Différences tronquées. Ouvrez le fichier pour voir la modification complète.","usage": {"context": "Dernier contexte : {{tokens}}{{capacity}} tokens",- "requests": "{{count}} requêtes au modèle",- "estimated": "Inclut une estimation de l’utilisation"+ "requests": "{{count}} requêtes au modèle"},"activityThinkingFor": "Réflexion pendant {{duration}}","activityThought": "Réflexion terminée",diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.jsonindex 210351372..c36394f79 100644--- a/webui/src/i18n/locales/id/common.json+++ b/webui/src/i18n/locales/id/common.json@@ -1858,8 +1858,6 @@"sessionInfo": "Detail sesi"},"sessionInfo": {- "title": "Sesi",- "untitled": "Topik tanpa judul","automations": "Otomasi","count": "{{count}}","loading": "Memuat otomasi...",@@ -1911,15 +1909,21 @@"reauthFallback": "Model cadangan menangani respons ini.","reauthSettings": "Buka pengaturan model","context": {+ "loaded": "Dimuat",+ "unloaded": "Belum dimuat",+ "expand": "Perbesar konteks",+ "collapse": "Perkecil konteks",+ "noFiles": "Belum ada konteks yang tercatat",+ "estimatedNodeTokens": "Sekitar {{value}} token",+ "openFile": "Buka berkas",+ "history": "Riwayat konteks",+ "playHistory": "Putar riwayat konteks","tooltip": "Konteks {{percent}}%","detailsLabel": "Buka penggunaan konteks","panelTitle": "Penggunaan konteks","contextTitle": "Konteks",- "recentRounds": "Putaran terbaru",- "inputTrend": "Token masukan",- "input": "Token masukan",- "cacheHitRate": "Rasio hit KV cache",- "output": "Token keluaran",+ "cacheHitRate": "Rasio cache hit",+ "tokenUsage": "{{used}} / {{limit}}","duration": "Waktu pembuatan"},"queued": {@@ -2147,8 +2151,7 @@"fileEditDiffTruncated": "Perbedaan dipotong. Buka file untuk melihat perubahan lengkap.","usage": {"context": "Konteks terbaru: {{tokens}}{{capacity}} token",- "requests": "{{count}} permintaan model",- "estimated": "Termasuk penggunaan perkiraan"+ "requests": "{{count}} permintaan model"},"activityThinkingFor": "Berpikir selama {{duration}}","activityThought": "Selesai berpikir",diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.jsonindex bfb9dd3d5..38bbbbe85 100644--- a/webui/src/i18n/locales/ja/common.json+++ b/webui/src/i18n/locales/ja/common.json@@ -1858,8 +1858,6 @@"sessionInfo": "セッション詳細"},"sessionInfo": {- "title": "セッション",- "untitled": "無題のトピック","automations": "自動タスク","count": "{{count}}","loading": "自動タスクを読み込み中...",@@ -1911,15 +1909,21 @@"reauthFallback": "今回の応答には代替モデルを使用しました。","reauthSettings": "モデル設定を開く","context": {+ "loaded": "読み込み済み",+ "unloaded": "未読み込み",+ "expand": "コンテキストを拡大",+ "collapse": "コンテキストを縮小",+ "noFiles": "コンテキストはまだ記録されていません",+ "estimatedNodeTokens": "約 {{value}} トークン",+ "openFile": "ファイルを開く",+ "history": "コンテキスト履歴",+ "playHistory": "コンテキストの変化を再生","tooltip": "コンテキスト {{percent}}%","detailsLabel": "コンテキスト使用量を開く","panelTitle": "コンテキスト使用量","contextTitle": "コンテキスト",- "recentRounds": "最近のラウンド",- "inputTrend": "入力トークン",- "input": "入力トークン",- "cacheHitRate": "KV キャッシュヒット率",- "output": "出力トークン",+ "cacheHitRate": "キャッシュヒット率",+ "tokenUsage": "{{used}} / {{limit}}","duration": "生成時間"},"queued": {@@ -2147,8 +2151,7 @@"fileEditDiffTruncated": "差分は切り詰められました。完全な変更はファイルを開いて確認してください。","usage": {"context": "最新のコンテキスト: {{tokens}}{{capacity}} トークン",- "requests": "モデルリクエスト {{count}} 回",- "estimated": "推定使用量を含みます"+ "requests": "モデルリクエスト {{count}} 回"},"activityThinkingFor": "{{duration}}考えています","activityThought": "思考しました",diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.jsonindex 33c6bd99f..cff5561b3 100644--- a/webui/src/i18n/locales/ko/common.json+++ b/webui/src/i18n/locales/ko/common.json@@ -1858,8 +1858,6 @@"sessionInfo": "세션 세부 정보"},"sessionInfo": {- "title": "세션",- "untitled": "제목 없는 주제","automations": "자동화","count": "{{count}}","loading": "자동화를 불러오는 중...",@@ -1911,15 +1909,21 @@"reauthFallback": "이번 응답은 대체 모델이 처리했습니다.","reauthSettings": "모델 설정 열기","context": {+ "loaded": "불러옴",+ "unloaded": "불러오지 않음",+ "expand": "컨텍스트 확대",+ "collapse": "컨텍스트 축소",+ "noFiles": "아직 기록된 컨텍스트가 없습니다",+ "estimatedNodeTokens": "약 {{value}} 토큰",+ "openFile": "파일 열기",+ "history": "컨텍스트 기록",+ "playHistory": "컨텍스트 기록 재생","tooltip": "컨텍스트 {{percent}}%","detailsLabel": "컨텍스트 사용량 열기","panelTitle": "컨텍스트 사용량","contextTitle": "컨텍스트",- "recentRounds": "최근 라운드",- "inputTrend": "입력 토큰",- "input": "입력 토큰",- "cacheHitRate": "KV 캐시 적중률",- "output": "출력 토큰",+ "cacheHitRate": "캐시 적중률",+ "tokenUsage": "{{used}} / {{limit}}","duration": "생성 시간"},"queued": {@@ -2147,8 +2151,7 @@"fileEditDiffTruncated": "변경 사항의 일부만 표시됩니다. 전체 내용은 파일을 열어 확인하세요.","usage": {"context": "최근 컨텍스트: {{tokens}}{{capacity}} 토큰",- "requests": "모델 요청 {{count}}회",- "estimated": "예상 사용량 포함"+ "requests": "모델 요청 {{count}}회"},"activityThinkingFor": "{{duration}} 동안 생각 중","activityThought": "생각함",diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.jsonindex 99a3c6ac8..1340aae17 100644--- a/webui/src/i18n/locales/pt-BR/common.json+++ b/webui/src/i18n/locales/pt-BR/common.json@@ -1872,8 +1872,6 @@"sessionInfo": "Detalhes da sessão"},"sessionInfo": {- "title": "Sessão",- "untitled": "Tópico sem título","automations": "Automações","count": "{{count}}","loading": "Carregando automações...",@@ -1925,15 +1923,21 @@"reauthFallback": "Um modelo alternativo respondeu desta vez.","reauthSettings": "Abrir configurações do modelo","context": {+ "loaded": "Carregado",+ "unloaded": "Não carregado",+ "expand": "Expandir contexto",+ "collapse": "Recolher contexto",+ "noFiles": "Nenhum contexto registrado ainda",+ "estimatedNodeTokens": "Cerca de {{value}} tokens",+ "openFile": "Abrir arquivo",+ "history": "Histórico de contexto",+ "playHistory": "Reproduzir histórico do contexto","tooltip": "Contexto {{percent}}%","detailsLabel": "Abrir uso do contexto","panelTitle": "Uso do contexto","contextTitle": "Contexto",- "recentRounds": "Rodadas recentes",- "inputTrend": "Tokens de entrada",- "input": "Tokens de entrada",- "cacheHitRate": "Taxa de acertos do cache KV",- "output": "Tokens de saída",+ "cacheHitRate": "Taxa de acertos de cache",+ "tokenUsage": "{{used}} / {{limit}}","duration": "Tempo de geração"},"queued": {@@ -2341,8 +2345,7 @@"fileEditDiffTruncated": "Diferenças truncadas. Abra o arquivo para ver a alteração completa.","usage": {"context": "Contexto atual: {{tokens}}{{capacity}}",- "requests": "{{count}} chamadas nesta rodada",- "estimated": "Inclui uso estimado"+ "requests": "{{count}} chamadas nesta rodada"}},"recovery": {diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.jsonindex 6b78d18dd..2a422873b 100644--- a/webui/src/i18n/locales/vi/common.json+++ b/webui/src/i18n/locales/vi/common.json@@ -1858,8 +1858,6 @@"sessionInfo": "Chi tiết phiên"},"sessionInfo": {- "title": "Phiên",- "untitled": "Chủ đề chưa đặt tên","automations": "Tự động hóa","count": "{{count}}","loading": "Đang tải tự động hóa...",@@ -1911,15 +1909,21 @@"reauthFallback": "Mô hình dự phòng đã xử lý phản hồi này.","reauthSettings": "Mở cài đặt mô hình","context": {+ "loaded": "Đã tải",+ "unloaded": "Chưa tải",+ "expand": "Mở rộng ngữ cảnh",+ "collapse": "Thu gọn ngữ cảnh",+ "noFiles": "Chưa có ngữ cảnh được ghi nhận",+ "estimatedNodeTokens": "Khoảng {{value}} token",+ "openFile": "Mở tệp",+ "history": "Lịch sử ngữ cảnh",+ "playHistory": "Phát lịch sử ngữ cảnh","tooltip": "Ngữ cảnh {{percent}}%","detailsLabel": "Mở mức sử dụng ngữ cảnh","panelTitle": "Mức sử dụng ngữ cảnh","contextTitle": "Ngữ cảnh",- "recentRounds": "Các lượt gần đây",- "inputTrend": "Token đầu vào",- "input": "Token đầu vào",- "cacheHitRate": "Tỷ lệ hit KV cache",- "output": "Token đầu ra",+ "cacheHitRate": "Tỷ lệ trúng bộ nhớ đệm",+ "tokenUsage": "{{used}} / {{limit}}","duration": "Thời gian tạo"},"queued": {@@ -2147,8 +2151,7 @@"fileEditDiffTruncated": "Chỉ hiển thị một phần thay đổi. Mở tệp để xem nội dung đầy đủ.","usage": {"context": "Ngữ cảnh gần nhất: {{tokens}}{{capacity}} token",- "requests": "{{count}} yêu cầu mô hình",- "estimated": "Bao gồm mức sử dụng ước tính"+ "requests": "{{count}} yêu cầu mô hình"},"activityThinkingFor": "Đang suy nghĩ trong {{duration}}","activityThought": "Đã suy nghĩ",diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.jsonindex 8edb2c912..b94d08b98 100644--- a/webui/src/i18n/locales/zh-CN/common.json+++ b/webui/src/i18n/locales/zh-CN/common.json@@ -2064,8 +2064,6 @@"sessionInfo": "会话详情"},"sessionInfo": {- "title": "会话",- "untitled": "未命名话题","automations": "自动任务","count": "{{count}}","loading": "正在加载自动任务...",@@ -2116,15 +2114,21 @@"reauthFallback": "本次已由备用模型继续回复。","reauthSettings": "打开模型设置","context": {+ "loaded": "已加载",+ "unloaded": "未加载",+ "expand": "展开上下文面板",+ "collapse": "收起上下文面板",+ "noFiles": "暂无上下文记录",+ "estimatedNodeTokens": "约 {{value}} tokens",+ "openFile": "打开文件",+ "history": "上下文历史",+ "playHistory": "播放上下文演变","tooltip": "上下文 {{percent}}%","detailsLabel": "打开上下文用量","panelTitle": "上下文用量","contextTitle": "上下文",- "recentRounds": "最近轮次",- "inputTrend": "输入 Token",- "input": "输入 Token",- "cacheHitRate": "KV Cache 命中率",- "output": "输出 Token",+ "cacheHitRate": "缓存命中率",+ "tokenUsage": "{{used}} / {{limit}}","duration": "生成耗时"},"queued": {@@ -2533,8 +2537,7 @@"fileEditDiffTruncated": "仅显示部分差异,打开文件可查看完整内容。","usage": {"context": "当前上下文:{{tokens}}{{capacity}}",- "requests": "本轮 {{count}} 次模型调用",- "estimated": "包含估算用量"+ "requests": "本轮 {{count}} 次模型调用"}},"recovery": {diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.jsonindex 17ea1740a..b810c0020 100644--- a/webui/src/i18n/locales/zh-TW/common.json+++ b/webui/src/i18n/locales/zh-TW/common.json@@ -1858,8 +1858,6 @@"sessionInfo": "對話詳細資料"},"sessionInfo": {- "title": "對話",- "untitled": "未命名話題","automations": "自動任務","count": "{{count}}","loading": "正在載入自動任務…",@@ -1911,15 +1909,21 @@"reauthFallback": "本次已由備用模型繼續回覆。","reauthSettings": "開啟模型設定","context": {+ "loaded": "已載入",+ "unloaded": "未載入",+ "expand": "展開上下文面板",+ "collapse": "收合上下文面板",+ "noFiles": "暫無上下文紀錄",+ "estimatedNodeTokens": "約 {{value}} tokens",+ "openFile": "開啟檔案",+ "history": "上下文歷史",+ "playHistory": "播放上下文演變","tooltip": "上下文 {{percent}}%","detailsLabel": "開啟上下文用量","panelTitle": "上下文用量","contextTitle": "上下文",- "recentRounds": "最近輪次",- "inputTrend": "輸入 Token",- "input": "輸入 Token",- "cacheHitRate": "KV Cache 命中率",- "output": "輸出 Token",+ "cacheHitRate": "快取命中率",+ "tokenUsage": "{{used}} / {{limit}}","duration": "生成耗時"},"queued": {@@ -2146,8 +2150,7 @@"fileEditDiffTruncated": "僅顯示部分差異,請開啟檔案查看完整內容。","usage": {"context": "目前上下文:{{tokens}}{{capacity}} tokens",- "requests": "{{count}} 次模型請求",- "estimated": "包含估算用量"+ "requests": "{{count}} 次模型請求"},"activityThinkingFor": "思考中,已 {{duration}}","activityThought": "已思考",diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.tsindex 81733d681..47bffc418 100644--- a/webui/src/lib/api.ts+++ b/webui/src/lib/api.ts@@ -1,3 +1,4 @@+import { isContextGraph, isContextInspection } from "@/lib/context-graph";import { isCompactionPhase, isCompactionReason } from "../../../packages/client-events/notifications";import type {ApiServicePayload,@@ -10,6 +11,7 @@ import type {ChannelConnectPayload,ChannelValidationPayload,ChatSummary,+ ContextGraph,CliAppsPayload,FilePreviewPayload,FileReferenceMetadata,@@ -315,7 +317,7 @@ function isProjectionTraceDetail(value: unknown): boolean {&& value.traceCount >= 0;}-function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {+function parseThreadProjectionEvent(value: unknown, validatedGraphs: ReadonlySet<unknown> = new Set()): ThreadProjectionEvent {if (!isRecord(value) || typeof value.event !== "string" || typeof value.chat_id !== "string") {throw new Error("Invalid WebUI thread event");}@@ -383,11 +385,13 @@ function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {if (value.text !== undefined && typeof value.text !== "string") break;return value as unknown as ThreadProjectionEvent;case "context_compaction":+ 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)|| (value.reason !== undefined && !isCompactionReason(value.reason))) break;return value as unknown as ThreadProjectionEvent;case "model_request": {+ if (value.context_graph !== undefined && !validatedGraphs.has(value.context_graph) && !isContextGraph(value.context_graph)) break;const isUsage = (usage: unknown) => isRecord(usage)&& Object.values(usage).every((count) => typeof count === "number" && Number.isFinite(count) && count >= 0);if (typeof value.request_id !== "string" || !value.request_id@@ -395,6 +399,7 @@ function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {|| !Number.isSafeInteger(value.sequence) || Number(value.sequence) < 0|| !["started", "completed", "failed", "cancelled"].includes(String(value.phase))|| (value.usage !== undefined && !isUsage(value.usage))+ || (value.request_usage != null && !isUsage(value.request_usage))|| (value.round_usages !== undefined && (!Array.isArray(value.round_usages) || !value.round_usages.every(isUsage)))|| (value.context_window_tokens !== undefined && (typeof value.context_window_tokens !== "number"|| !Number.isFinite(value.context_window_tokens) || value.context_window_tokens < 0))) break;@@ -413,12 +418,57 @@ export function parseWebuiThreadPayload(value: unknown): WebuiThreadPersistedPayif (value.projection !== "events" || !Array.isArray(value.events)) {throw new Error("Invalid WebUI thread events");}- const events = value.events.map(parseThreadProjectionEvent);- return {- ...value,- projection: "events",- events,- } as unknown as WebuiThreadPersistedPayload;+ const graphs = new Map<string, ContextGraph>();+ if (value.context_graphs !== undefined) {+ if (!isRecord(value.context_graphs)) throw new Error("Invalid context graph dictionary");+ const table = { nodes: value.context_graph_nodes, edges: value.context_graph_edges };+ if (!isContextGraph(table)) throw new Error("Invalid context graph entity table");+ const resolveIndex = <T,>(entries: readonly T[], index: unknown): T => {+ if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0 || index >= entries.length) {+ throw new Error("Unknown context graph entity reference");+ }+ return entries[index];+ };+ for (const [key, descriptor] of Object.entries(value.context_graphs)) {+ if (!isRecord(descriptor) || !Array.isArray(descriptor.nodes) || !Array.isArray(descriptor.edges)) {+ throw new Error("Invalid context graph dictionary entry");+ }+ const nodes = descriptor.nodes.map((index: unknown) => resolveIndex(table.nodes, index));+ const paths = new Set(nodes.map((node) => node.path));+ const edges = descriptor.edges.map((index: unknown) => {+ const edge = resolveIndex(table.edges, index);+ if (!paths.has(edge.source) || !paths.has(edge.target)) throw new Error("Invalid context graph edge reference");+ return edge;+ });+ graphs.set(key, { nodes, edges });+ }+ }+ const validatedGraphs = new Set(graphs.values());+ const resolveGraph = (key: unknown): ContextGraph => {+ const graph = typeof key === "string" ? graphs.get(key) : undefined;+ if (!graph) throw new Error("Unknown context graph reference");+ return graph;+ };+ const events = value.events.map((raw) => {+ if (!isRecord(raw)) return parseThreadProjectionEvent(raw);+ const event = { ...raw };+ if (event.context_graph_ref !== undefined) {+ if (event.context_graph !== undefined) throw new Error("Ambiguous context graph reference");+ event.context_graph = resolveGraph(event.context_graph_ref);+ delete event.context_graph_ref;+ }+ if (isRecord(event.context_snapshot) && event.context_snapshot.graph_ref !== undefined) {+ if (event.context_snapshot.graph !== undefined) throw new Error("Ambiguous context graph reference");+ const { graph_ref, ...snapshot } = event.context_snapshot;+ event.context_snapshot = { ...snapshot, graph: resolveGraph(graph_ref) };+ }+ return parseThreadProjectionEvent(event, validatedGraphs);+ });+ const body: Record<string, unknown> = { ...value, projection: "events", events };+ delete body.context_graphs;+ delete body.context_graph_nodes;+ delete body.context_graph_edges;+ return body as unknown as WebuiThreadPersistedPayload;}function parseWebuiThreadTraceDetailPayload(value: unknown): WebuiThreadTraceDetailPayload {@@ -432,7 +482,7 @@ function parseWebuiThreadTraceDetailPayload(value: unknown): WebuiThreadTraceDet}return {message_id: value.message_id,- events: value.events.map(parseThreadProjectionEvent),+ events: value.events.map((event) => parseThreadProjectionEvent(event)),};}@@ -450,6 +500,7 @@ export async function fetchWebuiThread(if (options?.before) params.set("before", options.before);if (options?.after) params.set("after", options.after);params.set("include_model_requests", "1");+ params.set("context_graph_encoding", "references-v1");const query = params.toString();const suffix = query ? `?${query}` : "";const url = `${resolvedBase}/api/sessions/${encodeURIComponent(key)}/webui-thread${suffix}`;diff --git a/webui/src/lib/context-graph-layout.ts b/webui/src/lib/context-graph-layout.tsnew file mode 100644index 000000000..a97509e47--- /dev/null+++ b/webui/src/lib/context-graph-layout.ts@@ -0,0 +1,100 @@+import type { ContextGraph, ContextGraphNode } from "@/lib/types";+import { forceCollide, forceLink, forceManyBody, forceSimulation, forceX, forceY, type SimulationNodeDatum } from "d3-force";++export interface GraphPosition { x: number; y: number }++export interface GraphParticle extends SimulationNodeDatum { path: string; radius: number; x: number; y: number }++// Obsidian display settings: center 0.52, repel 10, link strength 1, distance 250.+// Use 0.36 world units per reference unit to fit the compact panel.+const GRAPH_SCALE = 0.36;+const CENTER_STRENGTH = (Math.pow(0.01, 1 - 0.52) - 0.01) / 0.99;++/** Keep mutable simulation particles separate from immutable request snapshots. */+export function createGraphSimulation(graph: ContextGraph, previous: ReadonlyMap<string, GraphPosition>, width: number, height: number) {+ const simulation = forceSimulation<GraphParticle>()+ .alphaDecay(1 - Math.pow(0.001, 1 / 300)).velocityDecay(0.4)+ // Force order matters: each force reads velocities written by the previous one.+ .force("x", forceX<GraphParticle>(width / 2).strength(CENTER_STRENGTH))+ .force("y", forceY<GraphParticle>(height / 2).strength(CENTER_STRENGTH))+ .force("link", forceLink<GraphParticle, { source: string; target: string }>().id((node) => node.path).distance(250 * GRAPH_SCALE))+ .force("charge", forceManyBody<GraphParticle>().strength(-Math.pow(10, 3) * GRAPH_SCALE ** 2))+ .force("collision", forceCollide<GraphParticle>().radius(60 * GRAPH_SCALE).strength(0.5));+ updateGraphSimulation(simulation, graph, previous, width, height);+ return simulation;+}++export function updateGraphSimulation(simulation: ReturnType<typeof forceSimulation<GraphParticle>>, graph: ContextGraph,+ previous: ReadonlyMap<string, GraphPosition>, width: number, height: number) {+ const existing = new Map(simulation.nodes().map((node) => [node.path, node]));+ const placed = new Map<string, GraphPosition>(existing);+ const addedCount = graph.nodes.filter((node) => !existing.has(node.path)).length;+ const area = (60 * GRAPH_SCALE) ** 2 * addedCount;+ const outerRadius = Math.max(0, ...[...existing.values()].map((node) => Math.hypot(node.x - width / 2, node.y - height / 2)));+ const ringWidth = Math.sqrt(area / Math.PI + outerRadius ** 2) - outerRadius;+ const spread = Math.sqrt(area);+ const adjacent = new Map<string, string[]>();+ for (const edge of graph.edges) {+ const sources = adjacent.get(edge.source) ?? [];+ sources.push(edge.target); adjacent.set(edge.source, sources);+ const targets = adjacent.get(edge.target) ?? [];+ targets.push(edge.source); adjacent.set(edge.target, targets);+ }+ const nodes = graph.nodes.map((node): GraphParticle => {+ const retained = existing.get(node.path);+ if (retained) return retained;+ const neighbours = (adjacent.get(node.path) ?? [])+ .map((path) => placed.get(path)).filter((point): point is GraphPosition => !!point);+ let position = previous.get(node.path);+ if (!position && neighbours.length) position = {+ x: neighbours.reduce((sum, point) => sum + point.x, 0) / neighbours.length + (Math.random() - 0.5) * spread,+ y: neighbours.reduce((sum, point) => sum + point.y, 0) / neighbours.length + (Math.random() - 0.5) * spread,+ };+ if (!position) {+ const angle = Math.random() * Math.PI * 2;+ const radius = outerRadius + Math.sqrt(Math.random()) * ringWidth;+ position = { x: width / 2 + Math.cos(angle) * radius, y: height / 2 + Math.sin(angle) * radius };+ }+ placed.set(node.path, position);+ return { path: node.path, radius: 60 * GRAPH_SCALE, ...position };+ });+ const link = simulation.force<ReturnType<typeof forceLink<GraphParticle, { source: string; target: string }>>>("link")!;+ // Clear old links before removing particles; D3 initializes forces inside nodes().+ link.links([]);+ simulation.nodes(nodes);+ link.links(graph.edges.map((edge) => ({ ...edge })));+ simulation.force<ReturnType<typeof forceCollide<GraphParticle>>>("collision")!.radius((node) => node.radius);+ simulation.force<ReturnType<typeof forceX<GraphParticle>>>("x")!.x(width / 2);+ simulation.force<ReturnType<typeof forceY<GraphParticle>>>("y")!.y(height / 2);+}++/** Preserve the simulation steps while bounding work per animated frame. */+export function advanceGraphSimulation(simulation: ReturnType<typeof createGraphSimulation>, elapsedMs: number, budgetMs = 8) {+ // Advance physical time independently of painting cadence, but never spend an+ // unbounded frame catching up after a hidden tab or a busy main thread.+ const steps = Math.max(1, Math.floor(Math.min(elapsedMs, 100) * 240 / 1000));+ const deadline = performance.now() + budgetMs;+ for (let step = 0; step < steps; step++) {+ if (simulation.alpha() <= simulation.alphaMin() && simulation.alphaTarget() === 0) break;+ simulation.tick();+ if (performance.now() >= deadline) break;+ }+}++/** Finish the same finite layout in short slices without painting intermediate positions. */+export function startGraphSettlement(simulation: ReturnType<typeof createGraphSimulation>) {+ simulation.stop().alpha(1).alphaTarget(0);+ let remaining = Math.ceil(Math.log(simulation.alphaMin()) / Math.log(1 - simulation.alphaDecay()));+ return (budgetMs = 4) => {+ const deadline = performance.now() + budgetMs;+ do { simulation.tick(); remaining--; } while (remaining > 0 && performance.now() < deadline);+ if (remaining > 0) return false;+ for (const node of simulation.nodes()) { node.vx = 0; node.vy = 0; }+ simulation.alpha(0);+ return true;+ };+}++export function nodeRadius(node: ContextGraphNode): number {+ return node.state === "discovered" ? 3.5 : Math.max(4, Math.min(12.5, Math.sqrt(node.tokens) * 0.215));+}diff --git a/webui/src/lib/context-graph.ts b/webui/src/lib/context-graph.tsnew file mode 100644index 000000000..db50dbfee--- /dev/null+++ b/webui/src/lib/context-graph.ts@@ -0,0 +1,47 @@+import type { ContextGraph, ContextGraphNode, ContextInspection, ContextSnapshot, UIMessage, UIModelRequestSnapshot } from "@/lib/types";++export function isContextGraph(value: unknown): value is ContextGraph {+ if (!value || typeof value !== "object") return false;+ const graph = value as Record<string, unknown>;+ if (!Array.isArray(graph.nodes) || !Array.isArray(graph.edges)) return false;+ if (!graph.nodes.every((n: unknown) => {+ if (!n || typeof n !== "object") return false;+ const node = n as Record<string, unknown>;+ return typeof node.path === "string" && typeof node.name === "string"+ && (node.state === "loaded" || node.state === "discovered")+ && typeof node.tokens === "number" && Number.isFinite(node.tokens) && node.tokens >= 0;+ })) return false;+ const paths = new Set(graph.nodes.map((n: ContextGraphNode) => n.path));+ return graph.edges.every((e: unknown) => {+ if (!e || typeof e !== "object") return false;+ const edge = e as Record<string, unknown>;+ return typeof edge.source === "string" && typeof edge.target === "string"+ && paths.has(edge.source) && paths.has(edge.target);+ });+}++export function isContextInspection(value: unknown, validateGraph: typeof isContextGraph = isContextGraph): value is ContextInspection {+ return typeof value === "object" && value !== null+ && "graph" in value && validateGraph(value.graph)+ && "estimated_tokens" in value && typeof value.estimated_tokens === "number"+ && Number.isFinite(value.estimated_tokens) && value.estimated_tokens >= 0+ && "context_window_tokens" in value && typeof value.context_window_tokens === "number"+ && Number.isFinite(value.context_window_tokens) && value.context_window_tokens > 0;+}++export function composerContextSnapshots(+ messages: UIMessage[], requests: ReadonlyMap<string, UIModelRequestSnapshot>,+): ContextSnapshot[] {+ const boundary = messages.filter((message) => message.compaction?.phase === "succeeded").at(-1);+ const baseline = boundary?.compaction?.contextSnapshot;+ const snapshots = Array.from(requests.entries()).sort((a, b) => a[1].createdAt - b[1].createdAt)+ .flatMap(([turnId, request]) => (request.contextSnapshots ?? []).filter((snapshot) => {+ if (!boundary) return true;+ if (turnId === boundary.turnId) {+ return snapshot.turnSeq !== undefined && boundary.compaction?.turnSeq !== undefined+ && snapshot.turnSeq > boundary.compaction.turnSeq;+ }+ return request.createdAt > boundary.createdAt;+ }));+ return [...(baseline ? [baseline] : []), ...snapshots];+}diff --git a/webui/src/lib/model-request.ts b/webui/src/lib/model-request.tsindex 7c39c99a1..bbba0d37c 100644--- a/webui/src/lib/model-request.ts+++ b/webui/src/lib/model-request.ts@@ -2,7 +2,7 @@ import type { UIMessage, UIModelRequestSnapshot } from "@/lib/types";export type ComposerUsageSnapshot = Pick<UIMessage,"id" | "turnId" | "createdAt" | "completedAt" | "usage" | "roundUsages" | "contextWindowTokens"-> & { compacted?: boolean };+> & { compacted?: boolean; estimatedContextTokens?: number };export function reconcileModelRequest(current: UIModelRequestSnapshot | undefined,@@ -44,12 +44,20 @@ export function composerUsageSnapshots(const compactionSeq = compactions.get(row.turnId!);const compacted = compactions.has(row.turnId!) && !(snapshot.usageTurnSeq !== undefined&& compactionSeq !== undefined && snapshot.usageTurnSeq > compactionSeq);+ if (compacted) {+ const baseline = messages.filter((message) => message.turnId === row.turnId+ && message.compaction?.phase === "succeeded").at(-1)?.compaction?.contextSnapshot;+ return [{ id: row.id, turnId: row.turnId, createdAt: row.createdAt, compacted: true,+ estimatedContextTokens: baseline?.estimatedTokens, contextWindowTokens: baseline?.contextWindowTokens }];+ }return [{ id: row.id, turnId: row.turnId, createdAt: row.createdAt, compacted,completedAt: snapshot.completedAt ?? row.completedAt, usage: snapshot.usage,roundUsages: snapshot.roundUsages, contextWindowTokens: snapshot.contextWindowTokens }];}if (row.kind === "compaction" && row.compaction?.phase === "succeeded") {- return [{ id: row.id, createdAt: row.createdAt, compacted: true }];+ return [{ id: row.id, createdAt: row.createdAt, compacted: true,+ estimatedContextTokens: row.compaction.contextSnapshot?.estimatedTokens,+ contextWindowTokens: row.compaction.contextSnapshot?.contextWindowTokens }];}if (row.role !== "assistant" || row.kind === "trace" || row.isStreaming) return [];return [row];diff --git a/webui/src/lib/surface-focus.ts b/webui/src/lib/surface-focus.tsnew file mode 100644index 000000000..43b978de5--- /dev/null+++ b/webui/src/lib/surface-focus.ts@@ -0,0 +1,22 @@+import type { HTMLAttributes } from "react";++const MODIFIER_KEYS = new Set(["Shift", "Control", "Alt", "Meta", "CapsLock"]);++/** Preserve keyboard focus cues without treating Shift + wheel as navigation. */+export const surfaceFocusProps = {+ onFocusCapture(event) {+ if (event.target !== event.currentTarget) return;+ if (event.currentTarget.matches(":focus-visible")) event.currentTarget.dataset.keyboardFocus = "true";+ else delete event.currentTarget.dataset.keyboardFocus;+ },+ onBlurCapture(event) {+ if (event.target === event.currentTarget) delete event.currentTarget.dataset.keyboardFocus;+ },+ onPointerDownCapture(event) {+ delete event.currentTarget.dataset.keyboardFocus;+ },+ onKeyDownCapture(event) {+ if (event.target === event.currentTarget && !MODIFIER_KEYS.has(event.key)+ && !event.ctrlKey && !event.metaKey && !event.altKey) event.currentTarget.dataset.keyboardFocus = "true";+ },+} satisfies HTMLAttributes<HTMLElement>;diff --git a/webui/src/lib/thread-event-projection.ts b/webui/src/lib/thread-event-projection.tsindex 6c65fe53f..5f5230e59 100644--- a/webui/src/lib/thread-event-projection.ts+++ b/webui/src/lib/thread-event-projection.ts@@ -885,6 +885,11 @@ export function projectThreadEvent(...(event.usage !== undefined ? { usage: event.usage } : {}),...(event.round_usages !== undefined ? { roundUsages: event.round_usages.slice(-8) } : {}),...(event.context_window_tokens !== undefined ? { contextWindowTokens: event.context_window_tokens } : {}),+ ...(event.context_graph ? { contextSnapshots: [+ ...(previousRequest?.contextSnapshots ?? []).filter((s) => s.id !== event.request_id),+ { id: event.request_id, turnSeq: event.turn_seq, graph: event.context_graph, usage: event.request_usage === undefined+ ? (event.phase === "completed" ? event.round_usages?.at(-1) : undefined) : event.request_usage ?? undefined, contextWindowTokens: event.context_window_tokens },+ ] } : {}),};state.modelRequests = new Map(state.modelRequests).set(event.turn_id, modelRequest);return state;@@ -1024,6 +1029,10 @@ export function projectThreadEvent(if (event.event === "context_compaction") {Object.assign(state, closeThreadProjectionAnswer(state));+ if (event.phase === "succeeded") {+ state.modelRequests = new Map(Array.from(state.modelRequests, ([turn, request]) =>+ [turn, { ...request, contextSnapshots: [] }]));+ }const id = `compaction-${event.compaction_id}`;const existing = state.messages.findIndex((message) => message.id === id);const message: UIMessage = {@@ -1037,6 +1046,11 @@ export function projectThreadEvent(phase: event.phase,turnSeq: event.turn_seq,reason: event.reason,+ ...(event.context_snapshot ? { contextSnapshot: {+ id, graph: event.context_snapshot.graph,+ estimatedTokens: event.context_snapshot.estimated_tokens,+ contextWindowTokens: event.context_snapshot.context_window_tokens,+ } } : {}),...(!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.tsindex 59d92b26b..aa50ed8ed 100644--- a/webui/src/lib/types.ts+++ b/webui/src/lib/types.ts@@ -8,6 +8,7 @@ type Role = "user" | "assistant" | "tool" | "system";type MessageKind = "message" | "trace" | "compaction";export interface UIContextCompaction extends ContextCompaction {+ contextSnapshot?: ContextSnapshot;/** Lifecycle event sequence, independent of the row's display position. */turnSeq?: number;/** Live wire transitions announce; hydrated transcript rows stay silent. */@@ -183,7 +184,35 @@ export interface UIMessage {}/** Turn-owned telemetry, not a transcript row or body-history source. */+export interface ContextGraphNode {+ path: string;+ name: string;+ state: "loaded" | "discovered";+ tokens: number;+}++export interface ContextGraph {+ nodes: ContextGraphNode[];+ edges: { source: string; target: string }[];+}++export interface ContextInspection {+ graph: ContextGraph;+ estimated_tokens: number;+ context_window_tokens: number;+}++export interface ContextSnapshot {+ turnSeq?: number;+ estimatedTokens?: number;+ id: string;+ graph: ContextGraph;+ usage?: TurnUsage;+ contextWindowTokens?: number;+}+export interface UIModelRequestSnapshot {+ contextSnapshots?: ContextSnapshot[];runId: string;sequence: number;turnSeq?: number;@@ -1546,7 +1575,8 @@ export type InboundEvent =/** Optional structured payload on progress frames (channel-specific). */agent_ui?: AgentUIBlob;} & InboundTurnMetadata)- | (NotificationEvent & InboundTurnMetadata)+ | (Exclude<NotificationEvent, { event: "context_compaction" }> & InboundTurnMetadata)+ | (Extract<NotificationEvent, { event: "context_compaction" }> & InboundTurnMetadata & { context_snapshot?: ContextInspection })| ({event: "file_edit";chat_id: string;@@ -1603,6 +1633,8 @@ export type InboundEvent =}| ({event: "model_request";+ request_usage?: TurnUsage | null;+ context_graph?: ContextGraph;chat_id: string;request_id: string;run_id: string;diff --git a/webui/src/lib/webui-thread-cache.ts b/webui/src/lib/webui-thread-cache.tsindex f3282aac3..dac3bb619 100644--- a/webui/src/lib/webui-thread-cache.ts+++ b/webui/src/lib/webui-thread-cache.ts@@ -1,7 +1,54 @@import { MemoryLruCache } from "./memory-lru-cache";import { parseWebuiThreadPayload } from "./api";import { readReloadCache, removeReloadCache, writeReloadCache } from "./reload-cache";-import type { WebuiThreadPersistedPayload } from "./types";+import type { ContextGraph, WebuiThreadPersistedPayload } from "./types";++/** Persist shared graph entities instead of expanding them in every replay frame. */+function reloadPayload(body: WebuiThreadPersistedPayload): unknown {+ function table<T extends object>(key: (value: T) => string) {+ const values: T[] = [];+ const identities = new Map<T, number>();+ const keys = new Map<string, number>();+ return { values, index(value: T): number {+ const known = identities.get(value);+ if (known !== undefined) return known;+ const valueKey = key(value);+ let index = keys.get(valueKey);+ if (index === undefined) {+ index = values.length;+ values.push(value);+ keys.set(valueKey, index);+ }+ identities.set(value, index);+ return index;+ } };+ }+ const nodes = table<ContextGraph["nodes"][number]>((node) => JSON.stringify([node.path, node.name, node.tokens, node.state]));+ const edges = table<ContextGraph["edges"][number]>((edge) => JSON.stringify([edge.source, edge.target]));+ const references = new Map<ContextGraph, string>();+ const graphs: Record<string, { nodes: number[]; edges: number[] }> = {};+ const reference = (graph: ContextGraph): string => {+ const known = references.get(graph);+ if (known !== undefined) return known;+ const key = String(references.size);+ references.set(graph, key);+ graphs[key] = { nodes: graph.nodes.map(nodes.index), edges: graph.edges.map(edges.index) };+ return key;+ };+ const events = body.events.map((event) => {+ if (event.event === "model_request" && event.context_graph) {+ 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) } };+ }+ return event;+ });+ return references.size ? { ...body, events, context_graphs: graphs,+ context_graph_nodes: nodes.values, context_graph_edges: edges.values } : body;+}/** Bounded canonical replay cache; the most recent snapshot also survives tab reloads. */export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload> {@@ -32,7 +79,7 @@ export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayloadoverride set(key: string, body: WebuiThreadPersistedPayload): void {super.set(key, body);- if (super.get(key)) writeReloadCache("thread", { key, body });+ if (super.get(key)) writeReloadCache("thread", { key, body: reloadPayload(body) });for (const listener of this.listeners.get(key) ?? []) listener(body);}diff --git a/webui/src/tests/api.test.ts b/webui/src/tests/api.test.tsindex 9649e8694..c1c5464ba 100644--- a/webui/src/tests/api.test.ts+++ b/webui/src/tests/api.test.ts@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {changeAutomationChat,+ parseWebuiThreadPayload,cancelMcpOAuth,configureChannel,completeMcpOAuth,@@ -110,7 +111,7 @@ describe("webui API helpers", () => {await fetchWebuiThread("tok", "websocket:chat-1");expect(fetch).toHaveBeenCalledWith(- "/api/sessions/websocket%3Achat-1/webui-thread?include_model_requests=1",+ "/api/sessions/websocket%3Achat-1/webui-thread?include_model_requests=1&context_graph_encoding=references-v1",expect.objectContaining({headers: { Authorization: "Bearer tok" },credentials: "same-origin",@@ -126,7 +127,7 @@ describe("webui API helpers", () => {});expect(fetch).toHaveBeenCalledWith(- "/api/sessions/websocket%3Achat-1/webui-thread?limit=120&before=abc%2B%2F%3D&include_model_requests=1",+ "/api/sessions/websocket%3Achat-1/webui-thread?limit=120&before=abc%2B%2F%3D&include_model_requests=1&context_graph_encoding=references-v1",expect.objectContaining({headers: { Authorization: "Bearer tok" },credentials: "same-origin",@@ -172,7 +173,7 @@ describe("webui API helpers", () => {})).resolves.toBe(cached);expect(fetch).toHaveBeenCalledWith(- "/api/sessions/websocket%3Achat-1/webui-thread?include_model_requests=1",+ "/api/sessions/websocket%3Achat-1/webui-thread?include_model_requests=1&context_graph_encoding=references-v1",expect.objectContaining({headers: {Authorization: "Bearer tok",@@ -1423,3 +1424,56 @@ describe("webui API helpers", () => {);});});++describe("context graph response dictionaries", () => {+ const graph = { nodes: [{ path: "/guide.md", name: "guide.md", tokens: 10, state: "loaded" }], edges: [] };+ const request = (id: string, fields: Record<string, unknown>) => ({+ event: "model_request", chat_id: "chat", request_id: id, run_id: "run", sequence: 2,+ phase: "completed", ...fields,+ });+ const payload = (events: unknown[], fields: Record<string, unknown> = {}) => ({ schemaVersion: 3, projection: "events", events, ...fields });++ it("resolves repeated graphs and checkpoint graphs into shared domain objects", () => {+ const result = parseWebuiThreadPayload(payload([+ request("one", { context_graph_ref: "0", request_usage: { context_tokens: 20 } }),+ request("two", { context_graph_ref: "0", request_usage: null }),+ { event: "context_compaction", chat_id: "chat", compaction_id: "compact", phase: "succeeded",+ context_snapshot: { graph_ref: "0", estimated_tokens: 10, context_window_tokens: 100 } },+ ], { context_graphs: { "0": { nodes: [0], edges: [] } }, context_graph_nodes: graph.nodes, context_graph_edges: graph.edges }));+ const requests = result.events.filter((event) => event.event === "model_request");+ expect(requests[0].context_graph).toBe(requests[1].context_graph);+ expect(requests[0].context_graph).toEqual(graph);+ expect(requests[1].request_usage).toBeNull();+ expect(result.events[2]).toMatchObject({ context_snapshot: { graph } });+ });++ it("preserves a growing timeline while sharing unchanged node and edge entities", () => {+ const nodes = Array.from({ length: 300 }, (_, index) => ({ path: `/${index}.md`, name: `${index}.md`, tokens: 10, state: "loaded" }));+ const edges = nodes.slice(1).map((node, index) => ({ source: nodes[index].path, target: node.path }));+ const descriptors = Object.fromEntries(Array.from({ length: 50 }, (_, index) => [String(index), {+ nodes: Array.from({ length: 251 + index }, (_, n) => n),+ edges: Array.from({ length: 250 + index }, (_, n) => n),+ }]));+ const result = parseWebuiThreadPayload(payload(Array.from({ length: 50 }, (_, index) => request(String(index), { context_graph_ref: String(index) })), {+ context_graphs: descriptors, context_graph_nodes: nodes, context_graph_edges: edges,+ }));+ const requests = result.events.filter((event) => event.event === "model_request");+ for (let index = 0; index < requests.length; index += 1) {+ expect(requests[index].context_graph?.nodes).toEqual(nodes.slice(0, 251 + index));+ expect(requests[index].context_graph?.edges).toEqual(edges.slice(0, 250 + index));+ }+ expect(requests[0].context_graph).not.toBe(requests[1].context_graph);+ expect(requests[0].context_graph?.nodes[0]).toBe(requests[49].context_graph?.nodes[0]);+ expect(requests[0].context_graph?.edges[0]).toBe(requests[49].context_graph?.edges[0]);+ });++ it("continues to accept inline graphs from older hosts", () => {+ const result = parseWebuiThreadPayload(payload([request("one", { context_graph: graph })]));+ expect(result.events[0]).toMatchObject({ context_graph: graph });+ });++ it("rejects unknown references and invalid dictionary entries", () => {+ expect(() => parseWebuiThreadPayload(payload([request("one", { context_graph_ref: "missing" })], { context_graphs: {}, context_graph_nodes: [], context_graph_edges: [] }))).toThrow("Unknown context graph reference");+ expect(() => parseWebuiThreadPayload(payload([], { context_graphs: { "0": { nodes: [], edges: [0] } }, context_graph_nodes: [], context_graph_edges: [{ source: "missing", target: "missing" }] }))).toThrow("Invalid context graph entity table");+ });+});diff --git a/webui/src/tests/code-block.test.tsx b/webui/src/tests/code-block.test.tsxindex 43c45ad1c..beb7c2163 100644--- a/webui/src/tests/code-block.test.tsx+++ b/webui/src/tests/code-block.test.tsx@@ -65,6 +65,13 @@ describe("CodeBlock", () => {expect(container.querySelectorAll("*").length).toBeLessThan(10);});+ it("keeps a Python module beyond the preview budget available as complete plain text", () => {+ const code = Array.from({ length: 2800 }, (_, index) => `def function_${index}(): return "a realistic source line"`).join("\n");+ render(<CodeBlock code={code} language="python" chrome="none"+ showLineNumbers wrapLongLines={false} viewportHighlight />);+ expect(screen.getByTestId("plain-code-fallback").querySelector("code > span > span:last-child")?.textContent).toBe(code);+ });+it("paints large preview text before enhancing it, and cancels enhancement on unmount", async () => {const callbacks = new Map<number, FrameRequestCallback>();let next = 0;diff --git a/webui/src/tests/composer-usage-popover.test.tsx b/webui/src/tests/composer-usage-popover.test.tsxindex 5311b7cff..3c49b2c11 100644--- a/webui/src/tests/composer-usage-popover.test.tsx+++ b/webui/src/tests/composer-usage-popover.test.tsx@@ -1,181 +1,91 @@-import { createEvent, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { act, render, screen, waitFor, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { describe, expect, it } from "vitest";-import { ComposerUsagePopover } from "@/components/thread/ComposerUsagePopover";+import type { ContextSnapshot } from "@/lib/types";-function pointer(- target: HTMLElement,- type: "pointerDown" | "pointerMove" | "pointerUp" | "pointerCancel" | "lostPointerCapture",- { y, x = 160, time = 1000, id = 1 }: { y: number; x?: number; time?: number; id?: number },-) {- const event = createEvent[type](target, {- pointerId: id, pointerType: "touch", isPrimary: true, button: 0, clientX: x, clientY: y,- });- Object.defineProperty(event, "timeStamp", { value: time });- fireEvent(target, event);-}--async function openSheet() {- const user = userEvent.setup();- render(- <ComposerUsagePopover- bottomSheet- showLabel- context={{ contextTokens: 10000, contextWindowTokens: 200000 }}- rounds={[- { id: "round", timestamp: 0, inputTokens: 10000, cachedTokens: 8000 },- { id: "round-2", timestamp: 60000, inputTokens: 14000, outputTokens: 280 },- ]}- />,- );- const trigger = screen.getByTestId("composer-context-usage");- await user.click(trigger);- const sheet = screen.getByRole("dialog", { name: "Context usage" });- const handle = within(sheet).getByRole("button", { name: "Close" });- return { user, trigger, sheet, handle };-}+const first: ContextSnapshot = { id: "1", contextWindowTokens: 10000, usage: { prompt_tokens: 1000 },+ graph: { nodes: [{ path: "/a.md", name: "a.md", state: "loaded", tokens: 100 }], edges: [] } };-describe("Mobile context usage sheet", () => {- it("keeps tiny rounds tappable without exaggerating their visual token usage", async () => {+describe("Context sidebar", () => {+ it("stays open while writing a message and updates the graph as new snapshots arrive", async () => {const user = userEvent.setup();- render(<ComposerUsagePopover bottomSheet context={null} rounds={[- { id: "small", timestamp: 0, inputTokens: 1000 },- { id: "large", timestamp: 60000, inputTokens: 500000 },- ]} />);+ const content = (snapshots: ContextSnapshot[]) => <><textarea aria-label="Message" />+ <ComposerUsagePopover context={null} rounds={[]} snapshots={snapshots} /></>;+ const view = render(content([first]));await user.click(screen.getByTestId("composer-context-usage"));- const [small, large] = screen.getAllByTestId("round-usage-bar");- for (const bar of [small, large]) {- expect(bar.parentElement).toHaveClass("relative", "h-full", "flex-1");- expect(bar).toHaveClass("before:absolute", "before:inset-0");- }- expect(small).toHaveStyle({ height: "0.216px" });- expect(large).toHaveStyle({ height: "108px" });- await user.pointer([{ keys: "[TouchA>]", target: small }, { keys: "[/TouchA]", target: small }]);- expect(within(screen.getByRole("dialog", { name: "Context usage" })).getByRole("dialog"))- .toHaveTextContent("1,000");- });-- it("replaces the X with a keyboard-accessible drag handle", async () => {- const { user, handle, sheet, trigger } = await openSheet();- expect(within(sheet).getAllByRole("button", { name: "Close" })).toEqual([handle]);- expect(handle.querySelector("svg")).toBeNull();- expect(handle).toHaveClass("touch-none", "h-11");- handle.focus();- await user.keyboard("{Enter}");- await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());- expect(trigger).toHaveFocus();- });-- it("keeps tapped round details open, switches rounds, and toggles the same bar closed", async () => {- const { user, sheet } = await openSheet();- const [first, second] = within(sheet).getAllByTestId("round-usage-bar");- const tap = (target: HTMLElement) => user.pointer([- { keys: "[TouchA>]", target },- { keys: "[/TouchA]", target },- ]);-- expect(first.tagName).toBe("BUTTON");- await tap(first);- const details = within(sheet).getByRole("dialog");- expect(details).toHaveTextContent("10,000");- expect(details).toHaveTextContent("80%");- expect(first).toHaveAttribute("aria-expanded", "true");- expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();- fireEvent.pointerLeave(first, { pointerType: "touch" });- expect(details).toBeVisible();-- await tap(second);- await waitFor(() => expect(within(sheet).getAllByRole("dialog")).toHaveLength(1));- expect(within(sheet).getByRole("dialog")).toHaveTextContent("14,000");- expect(within(sheet).getByRole("dialog")).toHaveTextContent("280");- expect(first).toHaveAttribute("aria-expanded", "false");- expect(second).toHaveAttribute("aria-expanded", "true");-- await tap(second);- await waitFor(() => expect(within(sheet).queryByRole("dialog")).not.toBeInTheDocument());- expect(sheet).toBeVisible();- await tap(first);- await tap(within(sheet).getByRole("heading", { name: "Context usage" }));- await waitFor(() => expect(within(sheet).queryByRole("dialog")).not.toBeInTheDocument());- expect(sheet).toBeVisible();+ const sidebar = screen.getByRole("complementary", { name: "Context usage" });+ await user.type(screen.getByRole("textbox"), "Continue reading");+ expect(sidebar).toBeVisible();+ expect(screen.getByRole("textbox")).toHaveValue("Continue reading");+ view.rerender(content([first, { ...first, id: "2", usage: { prompt_tokens: 2000 }, graph: {+ nodes: [...first.graph.nodes, { path: "/b.md", name: "b.md", state: "loaded", tokens: 200 }], edges: [],+ } }]));+ expect(await within(sidebar).findByRole("button", { name: "b.md" })).toBeInTheDocument();+ expect(within(sidebar).getByRole("progressbar")).toHaveAttribute("aria-valuenow", "20");+ expect(screen.getByRole("textbox")).toHaveFocus();+ await user.click(within(sidebar).getByRole("button", { name: "Expand context panel" }));+ const expanded = await screen.findByRole("dialog", { name: "Context usage" });+ expect(within(expanded).getByRole("button", { name: "b.md" })).toBeInTheDocument();+ expect(within(expanded).getByRole("progressbar")).toHaveAttribute("aria-valuenow", "20");+ await user.click(within(expanded).getByRole("button", { name: "Collapse context panel" }));+ expect(within(sidebar).getByRole("button", { name: "Expand context panel" })).toBeVisible();+ await user.click(screen.getByTestId("composer-context-usage"));+ await waitFor(() => expect(screen.getByTestId("composer-context-usage")).toHaveFocus());});- it("dismisses nested round details with Escape before the sheet, and supports dragging with details open", async () => {- const { user, sheet, handle, trigger } = await openSheet();- const first = within(sheet).getAllByTestId("round-usage-bar")[0];- first.focus();- await user.keyboard("{Enter}");- expect(within(sheet).getByRole("dialog")).toBeVisible();+ it("mounts in the conversation's side slot and closes with Escape from its controls", async () => {+ const user = userEvent.setup();+ const host = document.createElement("section");+ Object.defineProperty(host, "clientWidth", { value: 900 });+ document.body.append(host);+ const view = render(<ComposerUsagePopover sidebarHost={host} context={null} rounds={[]} snapshots={[first]} />);+ await user.click(screen.getByTestId("composer-context-usage"));+ const sidebar = within(host).getByRole("complementary");+ act(() => within(sidebar).getByRole("button", { name: "Expand context panel" }).focus());await user.keyboard("{Escape}");- await waitFor(() => expect(within(sheet).queryByRole("dialog")).not.toBeInTheDocument());- expect(sheet).toBeVisible();- expect(first).toHaveFocus();-- await user.click(first);- pointer(handle, "pointerDown", { y: 400 });- pointer(handle, "pointerMove", { y: 520, time: 1400 });- pointer(handle, "pointerUp", { y: 520, time: 1500 });- await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());- expect(document.body).not.toHaveStyle({ pointerEvents: "none" });- expect(trigger).toHaveFocus();+ await waitFor(() => expect(screen.getByTestId("composer-context-usage")).toHaveFocus());+ expect(screen.getByTestId("composer-context-usage")).toHaveAttribute("aria-expanded", "false");+ view.unmount(); host.remove();});-- it.each([- [100, 500],- [32, 40],- ])("dismisses after dragging %dpx in %dms and opens at the original position", async (distance, duration) => {- const { user, handle, sheet, trigger } = await openSheet();- pointer(handle, "pointerDown", { y: 400 });- pointer(handle, "pointerMove", { y: 400 + distance, time: 1000 + duration });- // happy-dom doesn't expose individual transforms through getComputedStyle.- expect(sheet.style.translate).toBe(`0 ${distance}px`);- expect(sheet).toHaveStyle({ transition: "none" });- pointer(handle, "pointerUp", { y: 400 + distance, time: 1000 + duration });- await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());- expect(document.body).not.toHaveStyle({ pointerEvents: "none" });- expect(trigger).toHaveFocus();-- await user.click(trigger);- expect(screen.getByRole("dialog").style.translate).toBe("0 0px");+ it("keeps the open sidebar and playback when its trigger moves between responsive slots", async () => {+ const user = userEvent.setup();+ const toolbar = document.createElement("span");+ const footer = document.createElement("span");+ document.body.append(toolbar, footer);+ const content = (host: HTMLElement) => <ComposerUsagePopover triggerHost={host} context={null} rounds={[]}+ snapshots={[first, { ...first, id: "2", usage: { prompt_tokens: 2000 } }]} />;+ const view = render(content(toolbar));+ await user.click(within(toolbar).getByTestId("composer-context-usage"));+ const sidebar = screen.getByRole("complementary");+ await user.click(within(sidebar).getByRole("button", { name: "Play context history" }));+ view.rerender(content(footer));+ expect(screen.getByRole("complementary")).toBe(sidebar);+ expect(within(sidebar).getByRole("progressbar")).toHaveAttribute("aria-valuenow", "10");+ expect(within(footer).getByTestId("composer-context-usage")).toHaveAttribute("aria-expanded", "true");+ await user.click(within(footer).getByTestId("composer-context-usage"));+ expect(screen.getByRole("complementary")).toBe(sidebar);+ expect(sidebar.style.getPropertyValue("--file-preview-slot-width")).toBe("0px");+ // Reopening during exit retains the graph instead of remounting it.+ await user.click(within(footer).getByTestId("composer-context-usage"));+ expect(screen.getByRole("complementary")).toBe(sidebar);+ await user.click(within(footer).getByTestId("composer-context-usage"));+ await waitFor(() => expect(screen.queryByRole("complementary")).not.toBeInTheDocument());+ view.unmount(); toolbar.remove(); footer.remove();});- it.each([- { end: "pointerUp" as const, y: 432, x: 160 },- { end: "pointerUp" as const, y: 370, x: 160 },- { end: "pointerUp" as const, y: 460, x: 260 },- { end: "pointerCancel" as const, y: 500, x: 160 },- { end: "lostPointerCapture" as const, y: 500, x: 160 },- ])("snaps back without a click-through on $end at ($x, $y)", async ({ end, y, x }) => {- const { user, handle, sheet } = await openSheet();- pointer(handle, "pointerDown", { y: 400 });- pointer(handle, "pointerMove", { y, x, time: 1400 });- pointer(handle, end, { y, x, time: 1500 });- expect(sheet.style.translate).toBe("0 0px");- expect(sheet.style.transition).toBe("");- fireEvent.click(handle, { detail: 1 });- expect(screen.getByRole("dialog")).toBeVisible();- await user.click(handle);+ it("opens a pane-contained drawer with a visible close control on narrow panes", async () => {+ const user = userEvent.setup();+ const host = document.createElement("section");+ Object.defineProperty(host, "clientWidth", { value: 600 });+ document.body.append(host);+ const view = render(<ComposerUsagePopover sidebarHost={host} context={null} rounds={[]} snapshots={[first]} />);+ await user.click(screen.getByTestId("composer-context-usage"));+ const drawer = within(host).getByRole("dialog", { name: "Context usage" });+ await user.click(within(drawer).getByRole("button", { name: "Close" }));await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());- expect(document.body).not.toHaveStyle({ pointerEvents: "none" });+ expect(screen.getByTestId("composer-context-usage")).toHaveFocus();+ view.unmount(); host.remove();});- it("does not capture content scrolling or let another pointer finish the drag", async () => {- const { user, handle, sheet } = await openSheet();- const content = within(sheet).getByRole("group", { name: "Input tokens" });- pointer(content, "pointerDown", { y: 480 });- pointer(content, "pointerMove", { y: 580 });- pointer(content, "pointerUp", { y: 580, time: 1500 });- expect(sheet.style.translate).toBe("0 0px");-- pointer(handle, "pointerDown", { y: 400 });- pointer(handle, "pointerMove", { y: 412 });- pointer(handle, "pointerDown", { y: 412, id: 2 });- pointer(handle, "pointerUp", { y: 600, id: 2 });- expect(sheet.style.translate).toBe("0 12px");- pointer(handle, "pointerUp", { y: 412, time: 1500 });- expect(sheet.style.translate).toBe("0 0px");- await user.keyboard("{Escape}");- await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());- });});diff --git a/webui/src/tests/context-graph-canvas.test.ts b/webui/src/tests/context-graph-canvas.test.tsnew file mode 100644index 000000000..1d3ec6384--- /dev/null+++ b/webui/src/tests/context-graph-canvas.test.ts@@ -0,0 +1,11 @@+import { expect, it, vi } from "vitest";+import { fitGraphLabel } from "@/components/thread/graph-canvas";++it("fits long Unicode labels with bounded measurements and complete code points", () => {+ const name = "😀".repeat(255);+ const measure = vi.fn((text: string) => Array.from(text).length);+ const fitted = fitGraphLabel(name, measure);+ expect(fitted).toBe(`${"😀".repeat(127)}…`);+ expect(measure.mock.calls.length).toBeLessThanOrEqual(10);+ expect(fitGraphLabel("a.md", measure)).toBe("a.md");+});diff --git a/webui/src/tests/context-graph-motion.test.tsx b/webui/src/tests/context-graph-motion.test.tsxnew file mode 100644index 000000000..4b90838a5--- /dev/null+++ b/webui/src/tests/context-graph-motion.test.tsx@@ -0,0 +1,119 @@+import { describe, expect, it } from "vitest";+import { createGraphSimulation, updateGraphSimulation, advanceGraphSimulation, startGraphSettlement } from "@/lib/context-graph-layout";+import { createGraphPresentation } from "@/components/thread/graph-presentation";+import type { ContextGraph } from "@/lib/types";++const first: ContextGraph = { nodes: [{ path: "a.md", name: "a.md", state: "loaded", tokens: 100 }], edges: [] };+const next: ContextGraph = { nodes: [...first.nodes, { path: "b.md", name: "b.md", state: "discovered", tokens: 0 }],+ edges: [{ source: "a.md", target: "b.md" }] };++describe("context graph continuity", () => {+ it("reintroduces a loaded filename when fast replay reverses its unfinished exit", () => {+ const presentation = createGraphPresentation();+ const loaded: ContextGraph = { nodes: [{ path: "loop.py", name: "loop.py", state: "loaded", tokens: 200 }], edges: [] };+ presentation.update(loaded, null);+ presentation.advance(2000, true);+ presentation.update({ nodes: [], edges: [] }, null);+ presentation.advance(200, false);+ const exiting = presentation.frame.nodes[0];+ expect(exiting.presence).toBeGreaterThan(0);+ expect(exiting.labelRemaining).toBe(0);+ presentation.update(loaded, null);+ expect(presentation.frame.nodes[0]).toBe(exiting);+ expect(exiting.labelRemaining).toBe(1600);+ presentation.advance(300, false);+ presentation.update(loaded, "loop.py");+ expect(exiting.labelRemaining).toBe(1300);+ });++ it("briefly introduces new labels without restarting existing labels on graph or focus updates", () => {+ const presentation = createGraphPresentation();+ presentation.update(first, null);+ presentation.advance(1000, false);+ expect(presentation.frame.nodes[0].labelRemaining).toBe(600);+ presentation.update(next, "a.md");+ presentation.advance(300, false);+ expect(presentation.frame.nodes.map((node) => node.labelRemaining)).toEqual([300, 0]);+ const loaded: ContextGraph = { ...next, nodes: next.nodes.map((node) => ({ ...node, state: "loaded" })) };+ presentation.update(loaded, null);+ presentation.advance(300, false);+ expect(presentation.frame.nodes.map((node) => node.labelRemaining)).toEqual([0, 1300]);+ presentation.update(loaded, "b.md");+ presentation.advance(300, false);+ expect(presentation.frame.nodes[1].labelRemaining).toBe(1000);+ // Replaying an earlier, unloaded state ends the automatic label reveal.+ presentation.update(next, null);+ expect(presentation.advance(0, true).moving).toBe(false);+ expect(presentation.frame.nodes.map((node) => node.labelRemaining)).toEqual([0, 0]);+ });++ it("retains existing particles and grows a linked node near its neighbour", () => {+ const sim = createGraphSimulation(first, new Map(), 600, 300).stop();+ const original = sim.nodes()[0];+ original.x = 100; original.y = 100; original.vx = 2;+ updateGraphSimulation(sim, next, new Map(), 600, 300);+ expect(sim.nodes()[0]).toBe(original);+ expect(original.vx).toBe(2);+ expect(Math.hypot(sim.nodes()[1].x - 100, sim.nodes()[1].y - 100)).toBeLessThan(20);+ const cache = new Map(sim.nodes().map((node) => [node.path, { x: node.x, y: node.y }]));+ updateGraphSimulation(sim, first, cache, 600, 300);+ updateGraphSimulation(sim, next, cache, 600, 300);+ expect(sim.nodes()[1].x).toBe(cache.get("b.md")!.x);+ expect(sim.nodes()[1].y).toBe(cache.get("b.md")!.y);+ sim.stop();+ });++ it("settles reduced motion in slices to the same finite layout", () => {+ const previous = new Map([["a.md", { x: 50, y: 80 }], ["b.md", { x: 150, y: 130 }]]);+ const reference = createGraphSimulation(next, previous, 600, 300).stop();+ const sliced = createGraphSimulation(next, previous, 600, 300).stop();+ reference.alpha(1).alphaTarget(0).tick(300);+ const advance = startGraphSettlement(sliced);+ expect(advance(0)).toBe(false);+ let slices = 1;+ while (!advance(0)) slices++;+ expect(slices).toBe(299);+ expect(sliced.nodes().map(({ x, y }) => ({ x, y }))).toEqual(reference.nodes().map(({ x, y }) => ({ x, y })));+ expect(sliced.nodes().every((node) => node.vx === 0 && node.vy === 0)).toBe(true);+ expect(sliced.alpha()).toBe(0);+ });++ it("reaches the same layout at slow and fast paint rates without stretching physical time", () => {+ const previous = new Map([["a.md", { x: 50, y: 80 }], ["b.md", { x: 150, y: 130 }]]);+ const simulate = (frameMs: number) => {+ const sim = createGraphSimulation(next, previous, 600, 300).stop();+ let elapsed = 0;+ while (sim.alpha() > sim.alphaMin()) {+ advanceGraphSimulation(sim, frameMs, Infinity);+ elapsed += frameMs;+ }+ return { elapsed, positions: sim.nodes().map(({ x, y }) => ({ x, y })) };+ };+ const fast = simulate(1000 / 60), slow = simulate(50);+ expect(slow.positions).toEqual(fast.positions);+ expect(Math.abs(slow.elapsed - fast.elapsed)).toBeLessThan(51);+ // A constrained frame still makes progress, rather than queuing an unbounded catch-up.+ const bounded = createGraphSimulation(next, previous, 600, 300).stop();+ const reference = createGraphSimulation(next, previous, 600, 300).stop().tick();+ advanceGraphSimulation(bounded, 10_000, 0);+ expect(bounded.nodes().map(({ x, y }) => ({ x, y }))).toEqual(reference.nodes().map(({ x, y }) => ({ x, y })));+ });++ it("reverses an in-flight exit from its current opacity when a graph returns", () => {+ const presentation = createGraphPresentation();+ presentation.update(next, null);+ for (let index = 0; index < 20; index++) presentation.advance(1000 / 60, false);+ const node = () => presentation.frame.nodes.find((item) => item.path === "b.md")!;+ expect(node().presence).toBeGreaterThan(0.7);+ presentation.update(first, null);+ for (let index = 0; index < 8; index++) presentation.advance(1000 / 60, false);+ const fading = node().presence;+ expect(fading).toBeGreaterThan(0);+ expect(fading).toBeLessThan(0.5);+ presentation.update(next, null);+ expect(node().presence).toBe(fading);+ for (let index = 0; index < 20; index++) presentation.advance(1000 / 60, false);+ expect(node().presence).toBeGreaterThan(0.9);+ expect(presentation.frame.edges).toHaveLength(1);+ });+});diff --git a/webui/src/tests/context-inspector.test.tsx b/webui/src/tests/context-inspector.test.tsxnew file mode 100644index 000000000..f705f6d5b--- /dev/null+++ b/webui/src/tests/context-inspector.test.tsx@@ -0,0 +1,70 @@+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";+import { ContextInspector } from "@/components/thread/ContextInspector";+import type { ContextSnapshot } from "@/lib/types";++const snapshots: ContextSnapshot[] = [+ { id: "first", contextWindowTokens: 10000, usage: { prompt_tokens: 1000 }, graph: {+ nodes: [{ path: "/a.md", name: "a.md", state: "loaded", tokens: 100 }], edges: [],+ } },+ { id: "second", contextWindowTokens: 10000, usage: { prompt_tokens: 2000, cached_tokens: 800 }, graph: {+ nodes: [{ path: "/a.md", name: "a.md", state: "loaded", tokens: 100 }, { path: "/b.md", name: "b.md", state: "discovered", tokens: 0 }],+ edges: [{ source: "/a.md", target: "/b.md" }],+ } },+];++describe("Context inspector", () => {+ it("exposes every graph node as a named keyboard control", async () => {+ const user = userEvent.setup();+ render(<ContextInspector context={null} rounds={[]} snapshots={snapshots} />);+ const node = await screen.findByRole("button", { name: "a.md" });+ expect(screen.getByRole("button", { name: "b.md" })).toBeInTheDocument();+ act(() => node.focus());+ await user.keyboard("{Enter}");+ expect(await screen.findByText("About 100 tokens")).toBeVisible();+ expect(node).toHaveFocus();+ });++ it("opens the selected file through the supplied preview action without loading its context", async () => {+ const open = vi.fn();+ const user = userEvent.setup();+ render(<ContextInspector context={null} rounds={[]} snapshots={snapshots} onOpenFile={open} />);+ const node = await screen.findByRole("button", { name: "a.md" });+ await user.hover(node);+ expect(screen.queryByText("About 100 tokens")).not.toBeInTheDocument();+ await user.click(node);+ expect(await screen.findByText("About 100 tokens")).toBeVisible();+ expect(open).not.toHaveBeenCalled();+ await user.click(screen.getByRole("button", { name: "Open file" }));+ expect(open).toHaveBeenCalledWith("/a.md");+ expect(snapshots[1].graph.nodes[1].state).toBe("discovered");+ });+});+++it("stops playback at compaction and shows the new baseline", async () => {+ const { rerender } = render(<ContextInspector context={null} rounds={[]} snapshots={snapshots} />);+ fireEvent.click(screen.getByRole("button", { name: "Play context history" }));+ const compacted: ContextSnapshot = { id: "compacted", graph: { nodes: [{ path: "/system.md", name: "system.md", state: "loaded", tokens: 300 }], edges: [] },+ estimatedTokens: 1500, contextWindowTokens: 10000 };+ rerender(<ContextInspector context={null} rounds={[]} snapshots={[compacted]} />);+ expect(screen.getByRole("progressbar")).toHaveAttribute("aria-valuenow", "15");+ expect(screen.getByText("≈15%")).toBeVisible();+ await waitFor(() => expect(screen.queryByRole("button", { name: "a.md" })).not.toBeInTheDocument());+ expect(screen.getByRole("button", { name: "system.md" })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Play context history" })).toBeDisabled();+});+++it("shows token usage from the displayed snapshot, including estimates without cache data", () => {+ const { rerender } = render(<ContextInspector context={null} rounds={[]} snapshots={snapshots} />);+ const meter = screen.getByRole("progressbar").parentElement!.parentElement!;+ fireEvent.pointerEnter(meter);+ expect(screen.getByText("2k / 10k")).toBeVisible();+ expect(screen.getByText("40%")).toBeVisible();+ rerender(<ContextInspector context={null} rounds={[]} snapshots={[{+ id: "compacted", estimatedTokens: 1500, contextWindowTokens: 10000, graph: { nodes: [], edges: [] },+ }]} />);+ expect(screen.getByText("≈1.5k / 10k")).toBeVisible();+});diff --git a/webui/src/tests/context-replay.test.tsx b/webui/src/tests/context-replay.test.tsxnew file mode 100644index 000000000..1995e2f96--- /dev/null+++ b/webui/src/tests/context-replay.test.tsx@@ -0,0 +1,62 @@+import { act, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, expect, it, vi } from "vitest";+import { ContextInspector } from "@/components/thread/ContextInspector";+import type { ContextGraph, ContextSnapshot } from "@/lib/types";++// Painting is explicit here so slow rendering can be exercised without a canvas.+vi.mock("@/components/thread/ContextGraphScene", () => ({+ ContextGraphScene: ({ graph, onReady }: { graph: ContextGraph; onReady: (graph: ContextGraph) => void }) =>+ <button onClick={() => onReady(graph)}>Paint snapshot</button>,+}));+afterEach(() => vi.useRealTimers());++async function start(count: number) {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] });+ const snapshots: ContextSnapshot[] = Array.from({ length: count }, (_, index) => ({+ id: String(index), contextWindowTokens: 10000,+ usage: { prompt_tokens: (index + 1) * 100 }, graph: { nodes: [], edges: [] },+ }));+ await act(async () => {+ render(<ContextInspector context={null} rounds={[]} snapshots={snapshots} />);+ await vi.dynamicImportSettled();+ });+ const play = screen.getByRole("button", { name: "Play context history" });+ fireEvent.click(play);+ return play;+}+const paint = () => fireEvent.click(screen.getByRole("button", { name: "Paint snapshot" }));+const progress = () => screen.getByRole("progressbar").getAttribute("aria-valuenow");++it("replays short histories at five steps per second and can restart", async () => {+ const play = await start(2);+ expect(play).toBeDisabled();+ expect(progress()).toBe("1");+ paint();+ act(() => vi.advanceTimersByTime(200));+ expect(progress()).toBe("2");+ paint();+ act(() => vi.advanceTimersByTime(200));+ expect(play).toBeEnabled();+ fireEvent.click(play);+ expect(progress()).toBe("1");+});++it("speeds up longer histories without dropping unpainted snapshots", async () => {+ await start(400);+ // A delayed first paint does not skip intermediate request states.+ act(() => vi.advanceTimersByTime(350));+ expect(progress()).toBe("1");+ paint();+ act(() => vi.advanceTimersByTime(1));+ expect(progress()).toBe("2");+ paint();+ act(() => vi.advanceTimersByTime(1));+ expect(progress()).toBe("3");+ paint();+ act(() => vi.advanceTimersByTime(1));+ expect(progress()).toBe("4");+ paint();+ // The fourth deadline remains at 400ms, not 100ms after its late paint.+ act(() => vi.advanceTimersByTime(47));+ expect(progress()).toBe("5");+});diff --git a/webui/src/tests/dialog-drag.test.tsx b/webui/src/tests/dialog-drag.test.tsxnew file mode 100644index 000000000..41d41fce3--- /dev/null+++ b/webui/src/tests/dialog-drag.test.tsx@@ -0,0 +1,61 @@+import { act, createEvent, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";++const originalAnimate = Object.getOwnPropertyDescriptor(Element.prototype, "animate");+let finish: (() => void) | null = null;+beforeEach(() => {+ // happy-dom has no WAAPI timeline; explicitly finish the browser-owned settlement.+ Object.defineProperty(Element.prototype, "animate", { configurable: true, value: () => ({+ cancel: vi.fn(),+ set onfinish(callback: () => void) { finish = callback; },+ }) });+});+afterEach(() => {+ if (originalAnimate) Object.defineProperty(Element.prototype, "animate", originalAnimate);+ else Reflect.deleteProperty(Element.prototype, "animate");+ finish = null;+});++function pointer(target: HTMLElement, type: "pointerDown" | "pointerMove" | "pointerUp" | "pointerCancel" | "lostPointerCapture", y: number, id = 1) {+ fireEvent(target, createEvent[type](target, { pointerId: id, pointerType: "touch", isPrimary: id === 1, button: 0, clientY: y }));+}+function openDrawer() {+ render(<Dialog><DialogTrigger>Open drawer</DialogTrigger><DialogContent placement="bottom" aria-describedby={undefined}>+ <DialogTitle>Details</DialogTitle>+ </DialogContent></Dialog>);+ fireEvent.click(screen.getByRole("button", { name: "Open drawer" }));+ const drawer = screen.getByRole("dialog");+ Object.defineProperty(drawer, "offsetHeight", { configurable: true, value: 500 });+ return { drawer, handle: screen.getByRole("button", { name: "Close" }) };+}++describe("shared bottom dialog drag", () => {+ it.each(["pointerUp", "pointerCancel", "lostPointerCapture"] as const)("rebounds without click-through after %s", (end) => {+ const { drawer, handle } = openDrawer();+ pointer(handle, "pointerDown", 100);+ pointer(handle, "pointerMove", end === "pointerUp" ? 115 : 260);+ pointer(handle, end, end === "pointerUp" ? 115 : 260);+ fireEvent.click(handle, { detail: 1 });+ expect(screen.getByRole("dialog")).toBe(drawer);+ act(() => finish?.());+ expect(drawer.style.translate).toBe("0 0px");+ expect(screen.getByRole("dialog")).toBe(drawer);+ fireEvent.click(handle);+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });++ it("ignores another touch ending over the handle while the first touch drags", () => {+ const { drawer, handle } = openDrawer();+ pointer(handle, "pointerDown", 100);+ pointer(handle, "pointerMove", 115);+ pointer(handle, "pointerDown", 115, 2);+ pointer(handle, "pointerUp", 200, 2);+ expect(finish).toBeNull();+ pointer(handle, "pointerMove", 120);+ expect(drawer.style.translate).toBe("0 20px");+ pointer(handle, "pointerCancel", 120);+ act(() => finish?.());+ expect(drawer.style.translate).toBe("0 0px");+ });+});diff --git a/webui/src/tests/file-preview-panel.test.tsx b/webui/src/tests/file-preview-panel.test.tsxindex 9761bbf74..92ba1b7f7 100644--- a/webui/src/tests/file-preview-panel.test.tsx+++ b/webui/src/tests/file-preview-panel.test.tsx@@ -227,7 +227,7 @@ describe("FilePreviewPanel", () => {await setAppLanguage("zh-CN");});- expect(screen.getByRole("button", { name: "预览" })).toHaveAttribute("aria-pressed", "true");+ expect(screen.getByRole("heading", { name: "Notes" })).toBeVisible();expect(screen.getByRole("button", { name: "原文" })).toBeInTheDocument();expect(fetchFilePreview).toHaveBeenCalledTimes(1);});@@ -246,7 +246,7 @@ describe("FilePreviewPanel", () => {source.focus();fireEvent.click(source);expect(source).toHaveFocus();- expect(source).toHaveAttribute("aria-pressed", "true");+ expect(source).toHaveAccessibleName("Preview");expect(screen.getByTestId("mock-code-block").textContent).toBe(content);expect(CodeBlock).toHaveBeenLastCalledWith(expect.objectContaining({code: content, chrome: "none", showLineNumbers: true, wrapLongLines: false, viewportHighlight: true,@@ -267,7 +267,8 @@ describe("FilePreviewPanel", () => {await screen.findByRole("heading", { name: "Notes" });fireEvent.click(screen.getByRole("button", { name: "Source" }));rerender(view("notes.md", "a", "new"));- expect(screen.getByRole("button", { name: "Source" })).toHaveAttribute("aria-pressed", "true");+ expect(screen.getByRole("button", { name: "Preview" })).toBeVisible();+ expect(screen.getByTestId("mock-code-block")).toHaveTextContent("# Notes");expect(fetchFilePreview).toHaveBeenCalledTimes(1);rerender(view("other.md"));await screen.findByRole("heading", { name: "Notes" });diff --git a/webui/src/tests/latest-thread-request.test.ts b/webui/src/tests/latest-thread-request.test.tsindex 58b803783..3616b962c 100644--- a/webui/src/tests/latest-thread-request.test.ts+++ b/webui/src/tests/latest-thread-request.test.ts@@ -43,7 +43,7 @@ describe("shared latest thread requests", () => {const surviving = fetchLatestWebuiThread(client, "token", KEY);expect(fetchMock).toHaveBeenCalledTimes(1);expect(fetchMock).toHaveBeenCalledWith(- "/api/sessions/websocket%3Ashared/webui-thread?limit=40&direction=latest&include_model_requests=1",+ "/api/sessions/websocket%3Ashared/webui-thread?limit=40&direction=latest&include_model_requests=1&context_graph_encoding=references-v1",expect.objectContaining({ headers: { Authorization: "Bearer token", "If-None-Match": '"cached"' } }),);const rejected = expect(first).rejects.toMatchObject({ name: "AbortError" });diff --git a/webui/src/tests/markdown-text-renderer.test.tsx b/webui/src/tests/markdown-text-renderer.test.tsxindex d6b9cc908..51f48b3fb 100644--- a/webui/src/tests/markdown-text-renderer.test.tsx+++ b/webui/src/tests/markdown-text-renderer.test.tsx@@ -742,9 +742,9 @@ describe("MarkdownTextRenderer", () => {expect(table).toHaveTextContent("nanobot");expect(table).toHaveClass("[&_th]:whitespace-normal",- "[&_th]:[overflow-wrap:anywhere]",+ "[&_th]:[overflow-wrap:normal]","[&_td]:whitespace-normal",- "[&_td]:[overflow-wrap:anywhere]",+ "[&_td]:[overflow-wrap:normal]",);expect(container.firstElementChild).toHaveClass("space-y-4");expect(container.firstElementChild).not.toHaveClass("space-y-0");diff --git a/webui/src/tests/message-bubble.test.tsx b/webui/src/tests/message-bubble.test.tsxindex f9998c14c..899959f30 100644--- a/webui/src/tests/message-bubble.test.tsx+++ b/webui/src/tests/message-bubble.test.tsx@@ -372,7 +372,7 @@ describe("MessageBubble", () => {rerender(<MessageBubble message={message} />);expect(bubble).not.toHaveClass("border-dashed");- expect(bubble).toHaveClass("bg-secondary/70");+ expect(bubble).toHaveClass("user-message-surface", "bg-secondary/70");});it("renders completed message branches with static wrapper classes", async () => {@@ -538,7 +538,7 @@ describe("MessageBubble", () => {expect(command.firstElementChild).toHaveClass("opacity-90");expect(command.className).not.toMatch(/(?:^|\s)(?:bg-|border|ring|rounded)/);expect(command.parentElement).toHaveTextContent("/model gpt-5");- expect(command.parentElement).toHaveClass("rounded-floating", "bg-secondary/70");+ expect(command.parentElement).toHaveClass("rounded-floating", "user-message-surface", "bg-secondary/70");});it("keeps unknown and invalid slash commands as plain message text", () => {diff --git a/webui/src/tests/model-request.test.ts b/webui/src/tests/model-request.test.tsindex bf2552ac0..935ffdf64 100644--- a/webui/src/tests/model-request.test.ts+++ b/webui/src/tests/model-request.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from "vitest";import { parseWebuiThreadPayload } from "@/lib/api";+import { composerContextSnapshots } from "@/lib/context-graph";import { composerUsageSnapshots } from "@/lib/model-request";import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";import { ThreadTranscript } from "@/lib/thread-transcript";@@ -18,6 +19,20 @@ function project(transcript: ThreadTranscript, event: ThreadProjectionEvent, per}describe("model request snapshots", () => {+ it("replays each request's matching file graph and usage after reload", () => {+ const transcript = new ThreadTranscript();+ const first = { nodes: [{ path: "/a.md", name: "a.md", state: "loaded" as const, tokens: 100 }], edges: [] };+ const second = { nodes: [...first.nodes, { path: "/b.md", name: "b.md", state: "discovered" as const, tokens: 0 }], edges: [{ source: "/a.md", target: "/b.md" }] };+ for (const event of [+ request(1, { request_id: "first", context_graph: first }),+ request(2, { request_id: "first", phase: "completed", context_graph: first, round_usages: rounds(1) }),+ request(3, { request_id: "second", context_graph: second }),+ request(4, { request_id: "second", phase: "completed", context_graph: second, round_usages: rounds(2) }),+ ]) project(transcript, event, true);+ expect(transcript.modelRequests.get("turn")?.contextSnapshots?.map((snapshot) => ({+ graph: snapshot.graph, tokens: snapshot.usage?.prompt_tokens,+ }))).toEqual([{ graph: first, tokens: 100 }, { graph: second, tokens: 101 }]);+ });it("validates request identity, phase, sequence, and usage at the history boundary", () => {for (const invalid of [{ phase: "unknown" }, { sequence: -1 }, { run_id: null }, { usage: { context_tokens: "123" } }]) {expect(() => parseWebuiThreadPayload({ schemaVersion: 3, projection: "events", events: [{ ...request(1), ...invalid }] })).toThrow();@@ -60,10 +75,10 @@ describe("model request snapshots", () => {expect(latest().compacted).toBe(false);send({ ...envelope, event: "context_compaction", compaction_id: "compact", phase: "succeeded", turn_seq: 3 });expect(latest().compacted).toBe(true);- expect(latest().roundUsages).toEqual(rounds(1));+ expect(latest().roundUsages).toBeUndefined();send(request(4, { usage: usage(1), round_usages: rounds(1) }));expect(latest().compacted).toBe(true);- expect(latest().roundUsages).toEqual(rounds(1));+ expect(latest().roundUsages).toBeUndefined();expect(projectWebuiThreadMessages(transcript.messages).map((row) => row.kind)).toEqual(["compaction"]);const smaller = { ...usage(2), context_tokens: 50 };send(request(5, { request_id: "request-4", phase: "completed", usage: smaller, round_usages: rounds(2) }));@@ -86,7 +101,7 @@ describe("model request snapshots", () => {] as ThreadProjectionEvent[]) project(transcript, event, persisted);const snapshot = composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)!;expect(snapshot.compacted).toBe(true);- expect(snapshot.roundUsages).toEqual(rounds(1));+ expect(snapshot.roundUsages).toBeUndefined();});it("preserves legacy compaction invalidation and historical rounds without request events", () => {@@ -203,3 +218,42 @@ describe("model request snapshots", () => {expect(snapshot.roundUsages?.[0].prompt_tokens).toBe(102);});});+++it.each([false, true])("starts a new graph history and estimated meter at compaction (persisted=%s)", (persisted) => {+ const transcript = new ThreadTranscript();+ const oldGraph = { nodes: [{ path: "/read.md", name: "read.md", state: "loaded" as const, tokens: 300 }], edges: [] };+ const systemGraph = { nodes: [{ path: "/SOUL.md", name: "SOUL.md", state: "loaded" as const, tokens: 40 }], edges: [] };+ project(transcript, request(1, { context_graph: oldGraph, phase: "completed", usage: usage(1) }), persisted);+ const event = parseWebuiThreadPayload({ schemaVersion: 3, projection: "events", events: [{ ...envelope, event: "context_compaction", compaction_id: "boundary",+ phase: "succeeded", turn_seq: 2, context_snapshot: { graph: systemGraph, estimated_tokens: 1200, context_window_tokens: 10000 } }] }).events[0];+ expect(event).not.toBeNull();+ if (!event) throw new Error("Compaction snapshot rejected");+ project(transcript, event, persisted);+ expect(composerContextSnapshots(transcript.messages, transcript.modelRequests)).toEqual([+ { id: "compaction-boundary", graph: systemGraph, estimatedTokens: 1200, contextWindowTokens: 10000 },+ ]);+ expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)).toMatchObject({+ compacted: true, estimatedContextTokens: 1200, contextWindowTokens: 10000,+ });+ const reloadedRequests = new Map(transcript.modelRequests);+ reloadedRequests.set("older-turn", {+ ...transcript.modelRequests.get("turn")!, createdAt: 0,+ contextSnapshots: [{ id: "older-request", graph: oldGraph, turnSeq: 1 }],+ });+ expect(composerContextSnapshots(transcript.messages, reloadedRequests).map((s) => s.id))+ .toEqual(["compaction-boundary"]);+ project(transcript, request(3, { context_graph: systemGraph, phase: "completed", usage: { context_tokens: 1300, request_count: 2 } }), persisted);+ expect(composerContextSnapshots(transcript.messages, transcript.modelRequests).map((s) => s.id)).toEqual(["compaction-boundary", "request-3"]);+ expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)).toMatchObject({ compacted: false, usage: { context_tokens: 1300 } });+});++it.each(["failed", "cancelled", "completed"] as const)("does not borrow previous usage for a %s request without measurement", (phase) => {+ const transcript = new ThreadTranscript();+ const graph = { nodes: [{ path: "/a.md", name: "a.md", state: "loaded" as const, tokens: 20 }], edges: [] };+ project(transcript, request(1, { phase: "completed", context_graph: graph, request_usage: usage(1), round_usages: rounds(1) }));+ project(transcript, request(2, { phase, context_graph: graph, request_usage: null, round_usages: rounds(1) }));+ const frames = composerContextSnapshots(transcript.messages, transcript.modelRequests);+ expect(frames[0].usage).toEqual(usage(1));+ expect(frames[1].usage).toBeUndefined();+});diff --git a/webui/src/tests/prompt-navigator.test.tsx b/webui/src/tests/prompt-navigator.test.tsxindex 1df4ebc8a..ca428fa19 100644--- a/webui/src/tests/prompt-navigator.test.tsx+++ b/webui/src/tests/prompt-navigator.test.tsx@@ -1,4 +1,4 @@-import { render, screen, waitFor } from "@testing-library/react";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { afterEach, beforeEach, expect, it, vi } from "vitest";@@ -12,6 +12,21 @@ beforeEach(() => {afterEach(() => restoreBrowserFocus());+it("opens Ctrl+F only in the active pane and selects a filtered message with Enter", async () => {+ const user = userEvent.setup();+ const jump = vi.fn();+ const props = { messages: [{ id: "one", role: "user" as const, content: "alpha", createdAt: 1 }], onJumpToPrompt: jump };+ const view = render(<PromptNavigator {...props} shortcutEnabled={false} />);+ fireEvent.keyDown(window, { key: "f", ctrlKey: true });+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ view.rerender(<PromptNavigator {...props} shortcutEnabled />);+ fireEvent.keyDown(window, { key: "f", ctrlKey: true });+ const input = await screen.findByRole("textbox", { name: "Search messages" });+ await waitFor(() => expect(input).toHaveFocus());+ await user.keyboard("alpha{Enter}");+ expect(jump).toHaveBeenCalledWith("one");+});+it("keeps a long searchable index windowed and keyboard-reachable", async () => {const user = userEvent.setup();const jump = vi.fn();diff --git a/webui/src/tests/reload-cache.test.ts b/webui/src/tests/reload-cache.test.tsindex 358d2b612..4f0286cd4 100644--- a/webui/src/tests/reload-cache.test.ts+++ b/webui/src/tests/reload-cache.test.ts@@ -1,5 +1,6 @@import { afterEach, describe, expect, it, vi } from "vitest";import { activateReloadCache, clearReloadCache, readReloadSessions, writeReloadCache } from "@/lib/reload-cache";+import { parseWebuiThreadPayload } from "@/lib/api";import { WebuiThreadCache } from "@/lib/webui-thread-cache";import { canonicalThreadPayload } from "./thread-test-payload";@@ -19,6 +20,54 @@ describe("tab reload cache", () => {expect(new WebuiThreadCache().get("websocket:b")).toBeUndefined();});+ it.each(["inline", "references"])("restores all 50 growing graph frames from compact tab storage (%s)", (format) => {+ activateReloadCache("ws://localhost:8765/?token=first");+ const nodes = Array.from({ length: 300 }, (_, index) => ({+ path: `/workspace/${index}.md`, name: `${index}.md`, tokens: 256, state: "loaded",+ }));+ const edges = nodes.flatMap((node, source) => [1, 2, 3].flatMap((offset) => source + offset < nodes.length+ ? [{ source: node.path, target: nodes[source + offset].path }] : []));+ const graphs = Array.from({ length: 50 }, (_, index) => {+ const count = 251 + index;+ const paths = new Set(nodes.slice(0, count).map((node) => node.path));+ return { nodes: nodes.slice(0, count), edges: edges.filter((edge) => paths.has(edge.source) && paths.has(edge.target)) };+ });+ const table = Object.fromEntries(graphs.map((graph, index) => [String(index), {+ nodes: graph.nodes.map((node) => nodes.indexOf(node)), edges: graph.edges.map((edge) => edges.indexOf(edge)),+ }]));+ const events = graphs.map((graph, index) => ({+ event: "model_request", chat_id: "growing", request_id: String(index), run_id: "run", sequence: index + 1,+ phase: "completed", request_usage: { context_tokens: 10000 + index },+ ...(format === "inline" ? { context_graph: structuredClone(graph) } : { context_graph_ref: String(index) }),+ }));+ 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",+ 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 } : {}),+ });+ const cache = new WebuiThreadCache();+ cache.set("websocket:growing", body);+ expect(cache.get("websocket:growing")).toBe(body);+ const raw = sessionStorage.getItem("nanobot.reload.v1.thread");+ expect(raw).not.toBeNull();+ expect(raw!.length).toBeLessThanOrEqual(512 * 1024);+ const restored = new WebuiThreadCache().get("websocket:growing");+ expect(restored).toEqual(body);+ expect(restored).not.toHaveProperty("context_graphs");+ expect(restored).not.toHaveProperty("context_graph_nodes");+ expect(restored).not.toHaveProperty("context_graph_edges");+ const frames = restored!.events.filter((event) => event.event === "model_request");+ expect(frames).toHaveLength(50);+ for (let index = 0; index < frames.length; index += 1) {+ expect(frames[index].context_graph).toEqual(graphs[index]);+ expect(frames[index].request_usage?.context_tokens).toBe(10000 + index);+ }+ expect(frames[0].context_graph?.nodes[0]).toBe(frames[49].context_graph?.nodes[0]);+ expect(frames[0].context_graph?.edges[0]).toBe(frames[49].context_graph?.edges[0]);+ });+it("does not restore another gateway's data or data after logout", () => {activateReloadCache("ws://localhost:8765/");new WebuiThreadCache().set("websocket:a", thread);diff --git a/webui/src/tests/session-automation-lazy.test.tsx b/webui/src/tests/session-automation-lazy.test.tsxindex 25fb15fdc..07146a4c5 100644--- a/webui/src/tests/session-automation-lazy.test.tsx+++ b/webui/src/tests/session-automation-lazy.test.tsx@@ -26,8 +26,7 @@ async function loadView(fail = false) {await initializeI18n();await loadAllLocaleResources();const { SessionInfoPopoverView } = await import("@/components/thread/SessionInfoPopoverView");- render(<><textarea aria-label="Unsent draft" defaultValue="Keep this draft" /><SessionInfoPopoverView- title="Release work" jobs={[job]} loading={false} loadFailed={false} now={Date.now()}+ render(<><textarea aria-label="Unsent draft" defaultValue="Keep this draft" /><SessionInfoPopoverView jobs={[job]} loading={false} loadFailed={false} now={Date.now()}onAction={async () => []} onEdit={async () => [job]}/></>);return loaded;diff --git a/webui/src/tests/session-info-popover.test.tsx b/webui/src/tests/session-info-popover.test.tsxindex 582f63782..3cdcaac17 100644--- a/webui/src/tests/session-info-popover.test.tsx+++ b/webui/src/tests/session-info-popover.test.tsx@@ -58,7 +58,6 @@ describe("SessionInfoPopover", () => {client={client}sessionKey="websocket:chat-1"token="tok"- title="Release work"/>,);@@ -93,7 +92,7 @@ describe("SessionInfoPopover", () => {let finish!: (response: Response) => void;vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));const user = userEvent.setup();- const view = render(<SessionInfoPopover client={client} sessionKey="websocket:chat-1" token="tok" title="Release work" />);+ const view = render(<SessionInfoPopover client={client} sessionKey="websocket:chat-1" token="tok" />);await user.click(screen.getByRole("button", { name: "Session details" }));expect(screen.getByRole("status", { name: "Loading automations..." })).toHaveAttribute("aria-busy", "true");await act(async () => finish(automationsResponse([automationJob()])));@@ -107,7 +106,7 @@ describe("SessionInfoPopover", () => {await act(async () => fail(new Error("Refresh failed")));expect(screen.getByRole("button", { name: /Morning check/ })).toBeVisible();vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));- view.rerender(<SessionInfoPopover client={client} sessionKey="websocket:chat-2" token="tok" title="Other project" />);+ view.rerender(<SessionInfoPopover client={client} sessionKey="websocket:chat-2" token="tok" />);expect(screen.queryByRole("button", { name: /Morning check/ })).not.toBeInTheDocument();expect(screen.getByRole("status", { name: "Loading automations..." })).toBeVisible();await act(async () => finish(automationsResponse([])));@@ -128,7 +127,6 @@ describe("SessionInfoPopover", () => {client={client}sessionKey="websocket:chat-1"token="tok"- title="Release work"/>,);@@ -165,7 +163,6 @@ describe("SessionInfoPopover", () => {client={client}sessionKey="websocket:chat-1"token="tok"- title="Release work"/>,);@@ -189,14 +186,12 @@ describe("SessionInfoPopover", () => {client={client}sessionKey="websocket:chat-1"token="tok"- title="@hyperframes 使用指南"/>,);await user.click(screen.getByRole("button", { name: "会话详情" }));- expect(await screen.findByText("会话")).toBeInTheDocument();- expect(screen.getByText("自动任务")).toBeInTheDocument();+ expect(await screen.findByText("自动任务")).toBeInTheDocument();expect(screen.getByText("Morning check")).toBeInTheDocument();expect(screen.getByText(/下次/)).toBeInTheDocument();expect(screen.queryByText("Session")).not.toBeInTheDocument();@@ -217,7 +212,6 @@ describe("SessionInfoPopover", () => {client={client}sessionKey="websocket:chat-1"token="tok"- title="Release work"/>,);@@ -255,7 +249,6 @@ describe("SessionInfoPopover", () => {client={client}sessionKey="websocket:chat-1"token="tok"- title="Release work"/>,);@@ -284,7 +277,6 @@ describe("SessionInfoPopover", () => {client={client}sessionKey="websocket:chat-1"token="tok"- title="Release work"/>,);@@ -314,7 +306,6 @@ describe("SessionInfoPopover", () => {client={client}sessionKey="websocket:chat-1"token="tok"- title="Release work"/>,);diff --git a/webui/src/tests/thread-composer.test.tsx b/webui/src/tests/thread-composer.test.tsxindex f52823b49..ee799c127 100644--- a/webui/src/tests/thread-composer.test.tsx+++ b/webui/src/tests/thread-composer.test.tsx@@ -672,130 +672,54 @@ describe("ThreadComposer", () => {fireEvent.focus(context);const tooltip = await screen.findByRole("tooltip");expect(tooltip).toHaveTextContent("Context 7%");- expect(tooltip.parentElement).toHaveClass("rounded-full", "px-2.5", "py-1");expect(tooltip.parentElement).not.toHaveTextContent("Available");});- it("opens an input-token chart with one bar for each logical round", () => {- render(- <ThreadComposer- onSend={vi.fn()}- modelLabel="gpt-5.6-sol"- modelPreset="gpt-5-6-sol"- modelProvider="openai_codex"- contextUsage={{- contextTokens: 14_700,- contextWindowTokens: 200_000,- }}- recentRoundUsage={[- {- id: "turn-1",- timestamp: Date.UTC(2026, 8, 3, 7, 20),- inputTokens: 18_000,- outputTokens: 280,- cachedTokens: 12_000,- generationMs: 12_000,- },- {- id: "turn-2",- timestamp: Date.UTC(2026, 8, 3, 8, 22),- inputTokens: 29_400,- outputTokens: 416,- cachedTokens: 26_180,- generationMs: 40_000,- },- ]}- placeholder="Ask anything..."- />,- );-+ it("opens the current graph and replays its request snapshots from the beginning", async () => {+ // Happy DOM has no canvas renderer; supply the operations used by graph paint+ // so replay can receive the same painted-frame acknowledgement as a browser.+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({+ setTransform: vi.fn(), clearRect: vi.fn(), setLineDash: vi.fn(), beginPath: vi.fn(),+ moveTo: vi.fn(), lineTo: vi.fn(), stroke: vi.fn(), arc: vi.fn(), fill: vi.fn(),+ roundRect: vi.fn(), fillText: vi.fn(), measureText: (text: string) => ({ width: text.length * 6 }),+ } as unknown as CanvasRenderingContext2D);+ render(<ThreadComposer onSend={vi.fn()} contextUsage={{ contextTokens: 200, contextWindowTokens: 1000 }}+ contextSnapshots={[+ { id: "first", contextWindowTokens: 1000, usage: { prompt_tokens: 100 }, graph: { nodes: [{ path: "/a.md", name: "a.md", state: "loaded", tokens: 40 }], edges: [] } },+ { id: "second", contextWindowTokens: 1000, usage: { prompt_tokens: 200 }, graph: { nodes: [{ path: "/b.md", name: "b.md", state: "loaded", tokens: 60 }], edges: [] } },+ ]} />);fireEvent.click(screen.getByTestId("composer-context-usage"));-- expect(screen.getByText("Context")).toBeInTheDocument();- expect(screen.getByText("14.7K / 200K")).toBeInTheDocument();- expect(screen.getByText("Recent rounds")).toBeInTheDocument();- expect(screen.getByText("Input tokens")).toBeInTheDocument();- expect(screen.getAllByTestId("round-usage-bar")).toHaveLength(2);- const [smallerBar, largerBar] = screen.getAllByTestId("round-usage-bar");- expect(- Number.parseFloat(smallerBar.style.height) / Number.parseFloat(largerBar.style.height),- ).toBeCloseTo(18_000 / 29_400, 5);- expect(largerBar.querySelector(".kv-cache-reused")).toBeInTheDocument();- expect(largerBar.querySelector(".kv-cache-not-reused")).toBeInTheDocument();- expect(screen.queryByText("Reused")).not.toBeInTheDocument();- expect(screen.queryByText("Not reused")).not.toBeInTheDocument();- expect(screen.getByRole("img", {- name: /input tokens 29,400.*KV cache hit rate 89%.*output tokens 416.*generation time 40/i,- })).toBeInTheDocument();- });-- it("uses each visible bar as its round detail trigger", async () => {- const user = userEvent.setup();- render(- <ThreadComposer- onSend={vi.fn()}- contextUsage={{ contextTokens: 14_700, contextWindowTokens: 200_000 }}- recentRoundUsage={[- {- id: "turn-1",- timestamp: Date.UTC(2026, 8, 3, 7, 20),- inputTokens: 18_000,- outputTokens: 280,- cachedTokens: 12_000,- },- {- id: "turn-2",- timestamp: Date.UTC(2026, 8, 3, 8, 22),- inputTokens: 29_400,- outputTokens: 416,- cachedTokens: 26_180,- },- ]}- placeholder="Ask anything..."- />,- );-- await user.click(screen.getByTestId("composer-context-usage"));- const firstBar = screen.getByRole("img", { name: /input tokens 18,000/i });- const secondBar = screen.getByRole("img", { name: /input tokens 29,400/i });- expect(firstBar).toHaveAttribute("data-testid", "round-usage-bar");- expect(secondBar).toHaveAttribute("data-testid", "round-usage-bar");- await user.hover(firstBar);- const firstTooltip = await screen.findByRole("tooltip");- expect(within(firstTooltip).getByText("Input tokens")).toBeInTheDocument();- expect(within(firstTooltip).getByText("18,000")).toBeInTheDocument();- await user.click(firstBar);- await user.unhover(firstBar);- await user.hover(secondBar);- const secondTooltip = await screen.findByRole("tooltip");- expect(within(secondTooltip).getByText("Input tokens")).toBeInTheDocument();- expect(within(secondTooltip).getByText("29,400")).toBeInTheDocument();+ expect(await screen.findByRole("button", { name: "b.md" })).toBeInTheDocument();+ expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "20");+ const replay = screen.getByRole("button", { name: "Play context history" });+ fireEvent.click(replay);+ expect(replay).toBeDisabled();+ expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "10");+ expect(await screen.findByRole("button", { name: "a.md" })).toBeInTheDocument();+ await waitFor(() => expect(replay).toBeEnabled(), { timeout: 2500 });+ expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "20");+ });++ it("shows the latest round cache metrics when inspecting legacy history", () => {+ render(<ThreadComposer onSend={vi.fn()} contextUsage={{ contextTokens: 14700, contextWindowTokens: 200000 }}+ recentRoundUsage={[{ inputTokens: 18000, cachedTokens: 12000 },+ { inputTokens: 29400, cachedTokens: 26180 }]} />);+ fireEvent.click(screen.getByTestId("composer-context-usage"));+ const meter = screen.getByRole("progressbar", { name: "Context" });+ fireEvent.pointerEnter(meter.parentElement!.parentElement!);+ expect(screen.getByText("Cache hit rate")).toBeInTheDocument();+ expect(screen.getByText("89%")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Play context history" })).toBeDisabled();});it("keeps context usage visible when the provider omits cache metrics", () => {- render(- <ThreadComposer- onSend={() => {}}- contextUsage={{ contextTokens: 14_700, contextWindowTokens: 200_000 }}- recentRoundUsage={[{- id: "turn-without-cache-metrics",- timestamp: new Date(2026, 8, 3, 16, 22).getTime(),- inputTokens: 29_400,- outputTokens: 416,- }]}- placeholder="Ask anything..."- />,- );-+ render(<ThreadComposer onSend={vi.fn()} contextUsage={{ contextTokens: 14700, contextWindowTokens: 200000 }}+ recentRoundUsage={[{ inputTokens: 29400 }]} />);fireEvent.click(screen.getByTestId("composer-context-usage"));-- expect(screen.getByRole("progressbar", { name: "Context 7%" })).toHaveAttribute(- "aria-valuenow",- "7",- );- const [bar] = screen.getAllByTestId("round-usage-bar");- expect(bar.firstElementChild).toHaveClass("bg-muted-foreground/25");- expect(screen.queryByText("Reused")).not.toBeInTheDocument();+ const meter = screen.getByRole("progressbar", { name: "Context" });+ expect(meter).toHaveAttribute("aria-valuenow", "7");+ fireEvent.pointerEnter(meter.parentElement!.parentElement!);+ expect(screen.queryByText("Cache hit rate")).not.toBeInTheDocument();});it("keeps the thread composer compact while matching the hero style", () => {@@ -1292,6 +1216,7 @@ describe("ThreadComposer", () => {it.each(["thread", "hero"] as const)("keeps narrow %s permissions inline and usage below without losing the draft", async (variant) => {let width = 390;+ vi.stubGlobal("innerWidth", width);vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockImplementation(() => rect({ width, height: 160 }),);@@ -1323,6 +1248,7 @@ describe("ThreadComposer", () => {// A narrow desktop panel uses the same layout; resizing must not replace the textarea.width = 800;+ vi.stubGlobal("innerWidth", width);fireEvent(window, new Event("resize"));expect(form).not.toHaveAttribute("data-compact-controls");expect(primary).toContainElement(access);@@ -1374,6 +1300,7 @@ describe("ThreadComposer", () => {vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockReturnValue(rect({ width: 390, height: 160 }),);+ vi.stubGlobal("innerWidth", 390);const user = userEvent.setup();const onSend = vi.fn();render(@@ -1381,10 +1308,7 @@ describe("ThreadComposer", () => {onSend={onSend}contextUsage={{ contextTokens: 10000, contextWindowTokens: 200000 }}recentRoundUsage={[{- id: "turn-1",- timestamp: Date.UTC(2026, 8, 13, 7, 20),inputTokens: 10000,- outputTokens: 280,cachedTokens: 8000,}]}/>,@@ -1392,12 +1316,11 @@ describe("ThreadComposer", () => {const trigger = screen.getByTestId("composer-context-usage");await user.click(trigger);const sheet = screen.getByRole("dialog", { name: "Context usage" });- expect(sheet).toHaveClass("bottom-0", "max-h-[60dvh]");- expect(sheet).toHaveFocus();- expect(within(sheet).getByRole("heading", { name: "Context usage" })).toBeVisible();- expect(within(sheet).getByText("10K / 200K")).toBeVisible();- expect(within(sheet).getByTestId("round-usage-bar")).toBeVisible();- expect(sheet).toContainElement(within(sheet).getByRole("group", { name: "Input tokens" }));+ expect(sheet).toHaveClass("mt-auto", "h-[85%]");+ expect(sheet.contains(document.activeElement)).toBe(true);+ expect(within(sheet).getByRole("heading", { name: "Context usage" })).toBeInTheDocument();+ expect(within(sheet).getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "5");+ expect(within(sheet).getByRole("button", { name: "Play context history" })).toBeDisabled();expect(document.body).toHaveStyle({ pointerEvents: "none" });if (dismissal === "Escape") await user.keyboard("{Escape}");@@ -1410,23 +1333,24 @@ describe("ThreadComposer", () => {expect(onSend).toHaveBeenCalledWith("still works", undefined, undefined);});- it("releases the mobile sheet when resizing to desktop and keeps the desktop popover", async () => {+ it("releases the mobile modal lock when resizing and keeps the desktop sidebar open", async () => {let width = 390;+ vi.stubGlobal("innerWidth", width);vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockImplementation(() => rect({ width, height: 160 }),);const user = userEvent.setup();render(<ThreadComposer onSend={vi.fn()} contextUsage={{ contextTokens: 500, contextWindowTokens: 1000 }} />);await user.click(screen.getByTestId("composer-context-usage"));- expect(screen.getByRole("dialog")).toHaveClass("bottom-0");+ expect(screen.getByRole("dialog")).toHaveClass("mt-auto");width = 800;+ vi.stubGlobal("innerWidth", width);fireEvent(window, new Event("resize"));await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());expect(document.body).not.toHaveStyle({ pointerEvents: "none" });- await user.click(screen.getByTestId("composer-context-usage"));- expect(screen.getByRole("dialog", { name: "Context usage" })).not.toHaveClass("bottom-0");- expect(screen.getByRole("progressbar", { name: "Context 50%" })).toBeVisible();+ expect(screen.getByRole("complementary", { name: "Context usage" })).toBeInTheDocument();+ expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "50");});it.each([@@ -1640,6 +1564,7 @@ describe("ThreadComposer", () => {it("keeps the inline permission menu and directory picker mounted across composer widths", () => {let width = 390;+ vi.stubGlobal("innerWidth", width);vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockImplementation(() => rect({ width, height: 160 }));const defaultScope = { project_path: "/srv/workspace", project_name: "workspace", access_mode: "full" as const };const { container } = render(<ThreadComposer variant="hero" onSend={vi.fn()} workspaceScope={defaultScope}@@ -1652,6 +1577,7 @@ describe("ThreadComposer", () => {expect(row.querySelector(".thread-composer-workspace-group")).toContainElement(trigger);expect(container.querySelector(".thread-composer-footer-primary")).toContainElement(access);width = 800;+ vi.stubGlobal("innerWidth", width);fireEvent(window, new Event("resize"));expect(container.querySelector(".thread-composer-meta")).toBe(row);expect(screen.getByRole("button", { name: "Switch directory" })).toBe(trigger);diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsxindex 92749392c..ddda72e01 100644--- a/webui/src/tests/thread-shell.test.tsx+++ b/webui/src/tests/thread-shell.test.tsx@@ -947,7 +947,7 @@ describe("ThreadShell", () => {expect(screen.queryByRole("alert")).not.toBeInTheDocument();});- it("renders each logical round in a completed turn as its own usage bar", async () => {+ it("shows legacy history usage and clears it after successful compaction", async () => {const client = makeClient();vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {if (String(input).includes("websocket%3Ausage-chart/webui-thread")) {@@ -1013,10 +1013,8 @@ describe("ThreadShell", () => {const trigger = await screen.findByTestId("composer-context-usage");fireEvent.click(trigger);- expect(await screen.findAllByTestId("round-usage-bar")).toHaveLength(4);- expect(screen.getByRole("img", {- name: /input tokens 16,400.*KV cache hit rate 99%.*output tokens 236/i,- })).toBeInTheDocument();+ expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "22");+ expect(screen.getByRole("button", { name: "Play context history" })).toBeDisabled();expect(screen.getByTestId("composer-context-meter")).toBeInTheDocument();for (const phase of ["started", "failed"] as const) {act(() => client._emitChat("usage-chart", {@@ -1028,8 +1026,7 @@ describe("ThreadShell", () => {event: "context_compaction", chat_id: "usage-chart",compaction_id: "success", phase: "succeeded",}));- expect(trigger).toHaveAccessibleName("Open context usage");- expect(screen.getAllByTestId("round-usage-bar")).toHaveLength(4);+ await waitFor(() => expect(screen.queryByTestId("composer-context-usage")).not.toBeInTheDocument());});it("updates composer usage from active model snapshots without changing the body", async () => {@@ -1041,7 +1038,10 @@ describe("ThreadShell", () => {events: [{ ...envelope, event: "user_message", text: "Waiting for answer", starts_turn: true, turn_seq: 0 }] }): { ok: false, status: 404, json: async () => ({}) },)));- render(wrap(client, <ThreadShell+ const footer = document.createElement("div");+ document.body.append(footer);+ const view = render(wrap(client, <ThreadShell+ composerPortalTarget={footer}session={session("live-usage")} title="Live usage" onToggleSidebar={() => {}}settingsSnapshot={modelSettings("test-model", "deepseek")}/>));@@ -1050,6 +1050,7 @@ describe("ThreadShell", () => {phase: "completed", sequence: 1, turn_seq: 1, context_window_tokens: 1000,usage: { prompt_tokens: 100, completion_tokens: 10, context_tokens: 100, request_count: 1 },round_usages: [{ prompt_tokens: 100, completion_tokens: 10 }],+ context_graph: { nodes: [{ path: "/first.md", name: "first.md", state: "loaded", tokens: 40 }], edges: [] },}));const trigger = await screen.findByTestId("composer-context-usage");expect(trigger).toHaveAccessibleName("Context 10%. Open context usage");@@ -1057,11 +1058,34 @@ describe("ThreadShell", () => {phase: "completed", sequence: 2, turn_seq: 2, context_window_tokens: 1000,usage: { prompt_tokens: 300, completion_tokens: 20, context_tokens: 200, request_count: 2 },round_usages: [{ prompt_tokens: 100, completion_tokens: 10 }, { prompt_tokens: 200, completion_tokens: 10 }],+ context_graph: { nodes: [{ path: "/second.md", name: "second.md", state: "loaded", tokens: 60 }], edges: [] },}));expect(trigger).toHaveAccessibleName("Context 20%. Open context usage");+ const input = screen.getByRole("textbox");+ expect(footer).toContainElement(input);+ fireEvent.change(input, { target: { value: "Preserve this draft" } });+ const host = document.querySelector(".thread-preview-layout")!;+ Object.defineProperty(host, "clientWidth", { value: 1000 });+ fireEvent(window, new Event("resize"));+ act(() => input.focus());fireEvent.click(trigger);- expect(await screen.findAllByTestId("round-usage-bar")).toHaveLength(2);+ expect(host.querySelector(".thread-conversation")).toContainElement(input);+ expect(footer).not.toContainElement(input);+ expect(input).toHaveValue("Preserve this draft");+ expect(input).toHaveFocus();+ expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "20");+ expect(await screen.findByRole("button", { name: "second.md" })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Play context history" })).toBeEnabled();expect(screen.getByText("Waiting for answer")).toBeInTheDocument();+ const sidebar = screen.getByTestId("context-sidebar");+ fireEvent.click(trigger);+ expect(screen.getByTestId("context-sidebar")).toBe(sidebar);+ expect(sidebar).toHaveAttribute("data-closing");+ expect(footer).toContainElement(input);+ expect(input).toHaveValue("Preserve this draft");+ await waitFor(() => expect(screen.queryByTestId("context-sidebar")).not.toBeInTheDocument());+ view.unmount();+ footer.remove();});it.each([false, true])("restores context after compaction only with newer usage (%s)", async (newReply) => {@@ -1090,11 +1114,12 @@ describe("ThreadShell", () => {session={session("compact-usage")} title="Compact usage" onToggleSidebar={() => {}}settingsSnapshot={modelSettings("test-model", "deepseek")}/>));- const trigger = await screen.findByTestId("composer-context-usage");+ await screen.findByText("Before compact");if (newReply) {+ const trigger = await screen.findByTestId("composer-context-usage");expect(trigger).toHaveAccessibleName("Context 2%. Open context usage");} else {- expect(trigger).toHaveAccessibleName("Open context usage");+ expect(screen.queryByTestId("composer-context-usage")).not.toBeInTheDocument();}});diff --git a/webui/src/tests/ui-shape-system.test.tsx b/webui/src/tests/ui-shape-system.test.tsxindex 36e4ad8e7..589eda383 100644--- a/webui/src/tests/ui-shape-system.test.tsx+++ b/webui/src/tests/ui-shape-system.test.tsx@@ -30,7 +30,8 @@ describe("UI shape system", () => {<DialogDescription>Content that can outgrow a keyboard-fitted frame.</DialogDescription></DialogContent></Dialog>);const dialog = screen.getByRole("dialog");- expect(dialog.parentElement).toHaveClass("items-start", "overflow-y-auto");+ expect(dialog.parentElement).toHaveClass("items-start", placement === "bottom" ? "overflow-clip" : "overflow-y-auto");+ if (placement === "bottom") expect(dialog).toHaveClass("overflow-y-auto");// The scroll owner stays inside Radix's overlay/scroll-lock boundary.expect(dialog.parentElement?.parentElement).toHaveAttribute("data-state", "open");expect(dialog).toHaveClass(placement === "bottom" ? "mt-auto" : "my-auto");diff --git a/webui/src/tests/useReconnectRuns.test.tsx b/webui/src/tests/useReconnectRuns.test.tsxindex b10d3bdd4..aa18ae9d6 100644--- a/webui/src/tests/useReconnectRuns.test.tsx+++ b/webui/src/tests/useReconnectRuns.test.tsx@@ -306,7 +306,7 @@ describe("durable run recovery", () => {await reopen();expect(fetchMock).toHaveBeenCalledWith(- "/api/sessions/websocket%3Ainactive/webui-thread?limit=40&direction=latest&include_model_requests=1",+ "/api/sessions/websocket%3Ainactive/webui-thread?limit=40&direction=latest&include_model_requests=1&context_graph_encoding=references-v1",expect.objectContaining({ headers: { Authorization: "Bearer renewed-token" } }),);expect(client.getRunStartedAt("inactive")).toBeNull();