From 519ed81132c3c7b823d908502fe30cab75bf4104 Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Thu, 5 Nov 2026 17:09:20 +0800 Subject: [PATCH] feat(webui): inspect file context in a live graph sidebar (#6562) * feat(webui): inspect file context in a live graph sidebar * refactor(webui): place preview controls in the shared sidebar header * fix(webui): synchronize npm lockfile for graph dependencies * fix(webui): preserve compacted context and refine graph inspection * fix(context): harden provenance, request usage, and drawer lifecycle * fix(webui): align source skeleton and browser fixtures * perf(context): reuse source analysis and capture request graphs once * perf(webui): compact graph history and render graph motion on canvas * fix(webui): remove redundant context sidebar header * style(webui): clarify context replay icon * perf(webui): pace context replay on an adaptive timeline * feat(webui): briefly reveal labels for new context nodes * fix(webui): reveal new labels only for loaded context files * fix(webui): restart graph animation clock after idle * fix(webui): reveal labels when replay reverses node exit * refactor(context): project file-use facts without retention tracking * refactor(context): observe file reads outside agent execution * fix(webui): animate context sidebar closing * refactor(context): remove unused graph and usage panel code * refactor(context): isolate prompt observation from execution metadata * fix(webui): clarify cache rate and show context token usage * fix(webui): abbreviate context token counts in thousands * fix(webui): omit token unit from context usage details * fix(webui): restore large source preview highlighting and panel elevation * fix(webui): distinguish modifier scrolling from keyboard focus * fix(webui): align preview tab and panel corner radii * fix(webui): attach file tabs to the header divider * fix(webui): use one action to toggle file preview mode * fix(webui): use hover hint for context replay * fix(webui): share composer layout between graph and file sidebars * fix(webui): align sidebar bottom with composer surface * fix(webui): restore mobile graph drawing and touch file details * test(webui): align legacy cache assertions with current label * perf(context): retain source analysis and bound graph animation work * style(webui): add light elevation to user messages * test(webui): await lazy graph scene before replay assertions * fix(webui): align preview skeleton and browser contracts --- docs/webui.md | 2 + nanobot/agent/context.py | 12 +- nanobot/agent/hook.py | 7 + nanobot/agent/progress_hook.py | 14 + nanobot/agent/runner.py | 5 + nanobot/agent/skills.py | 27 +- nanobot/agent/turn_hooks.py | 1 + nanobot/bus/notification_delivery.py | 2 + .../websocket/tests/test_websocket_channel.py | 104 +++- .../tests/test_websocket_outbound_delivery.py | 60 ++- nanobot/cli/commands.py | 3 +- nanobot/cli/gateway_runtime.py | 3 +- nanobot/context_graph.py | 85 +++ nanobot/context_sources.py | 70 +++ nanobot/events.py | 1 + nanobot/file_references.py | 112 ++++ nanobot/session/display_history.py | 24 +- nanobot/session/history_graph.py | 250 +++++++++ nanobot/session/sqlite_store.py | 41 +- nanobot/session/state.py | 10 +- nanobot/utils/prompt_templates.py | 9 +- nanobot/webui/client_contract.py | 3 +- nanobot/webui/context_observer.py | 179 +++++++ nanobot/webui/context_source_hook.py | 32 ++ nanobot/webui/history.py | 9 +- nanobot/webui/outbound_delivery.py | 63 ++- nanobot/webui/outbound_wire.py | 8 + nanobot/webui/transcript.py | 26 +- nanobot/webui/ws_http.py | 84 ++- pyproject.toml | 1 + tests/agent/test_context_source_hook.py | 59 ++ tests/agent/test_model_request_events.py | 54 ++ tests/agent/test_runner_progress_events.py | 5 +- tests/agent/test_skills_loader.py | 22 + tests/command/test_compact_command.py | 6 +- tests/session/test_history_graph.py | 173 ++++++ tests/test_context_graph.py | 259 +++++++++ tests/utils/test_webui_transcript.py | 4 +- tests/webui/test_context_observer.py | 166 ++++++ webui/browser/context-graph-fixture.tsx | 39 ++ webui/browser/context-graph.html | 1 + webui/browser/context-graph.spec.ts | 205 +++++++ webui/browser/history-boundary.spec.ts | 58 +- webui/browser/mobile-chat-layout.spec.ts | 2 +- webui/browser/prompt-rail.spec.ts | 6 +- webui/browser/skeleton-additions-fixture.tsx | 2 +- webui/browser/skeleton-layout.spec.ts | 4 +- webui/browser/theme-toggle-fixture.tsx | 2 +- webui/browser/typography.spec.ts | 11 +- webui/bun.lock | 12 + webui/package-lock.json | 50 ++ webui/package.json | 2 + webui/src/components/CodeBlock.tsx | 6 +- webui/src/components/FilePreviewPanelView.tsx | 36 +- webui/src/components/MarkdownTextRenderer.tsx | 9 +- webui/src/components/MessageBubble.tsx | 2 +- webui/src/components/PreviewPane.tsx | 46 +- webui/src/components/ViewportCodeRows.tsx | 8 +- .../settings/SkillsCatalogSettings.tsx | 4 +- .../thread/ComposerUsagePopover.tsx | 505 +++--------------- .../components/thread/ContextGraphScene.tsx | 294 ++++++++++ .../components/thread/ContextInspector.tsx | 99 ++++ .../components/thread/ContextReplayButton.tsx | 12 + .../src/components/thread/PromptNavigator.tsx | 89 ++- .../components/thread/SessionInfoPopover.tsx | 5 +- .../thread/SessionInfoPopoverView.tsx | 14 +- webui/src/components/thread/SubagentTasks.tsx | 3 +- .../src/components/thread/ThreadComposer.tsx | 20 +- .../src/components/thread/ThreadMessages.tsx | 2 +- webui/src/components/thread/ThreadShell.tsx | 98 +++- .../components/thread/WorkspaceControls.tsx | 5 +- webui/src/components/thread/graph-canvas.ts | 94 ++++ .../components/thread/graph-presentation.ts | 77 +++ webui/src/components/ui/dialog.tsx | 135 ++++- webui/src/components/ui/floating-surface.ts | 3 + webui/src/components/ui/image-viewport.tsx | 5 +- webui/src/components/ui/sheet.tsx | 19 +- webui/src/components/ui/sidebar-panel.tsx | 68 +++ .../components/workbench/PaneWorkbench.tsx | 15 +- webui/src/dev/gallery/content.tsx | 4 +- webui/src/dev/gallery/conversation.tsx | 29 +- webui/src/dev/gallery/foundations.tsx | 17 + .../src/dev/gallery/locales/controls/en.json | 7 + .../src/dev/gallery/locales/controls/es.json | 7 + .../src/dev/gallery/locales/controls/fr.json | 7 + .../src/dev/gallery/locales/controls/id.json | 7 + .../src/dev/gallery/locales/controls/ja.json | 7 + .../src/dev/gallery/locales/controls/ko.json | 7 + .../dev/gallery/locales/controls/pt-BR.json | 7 + .../src/dev/gallery/locales/controls/vi.json | 7 + .../dev/gallery/locales/controls/zh-CN.json | 7 + .../dev/gallery/locales/controls/zh-TW.json | 7 + webui/src/globals.css | 68 ++- webui/src/i18n/locales/en/common.json | 21 +- webui/src/i18n/locales/es/common.json | 21 +- webui/src/i18n/locales/fr/common.json | 21 +- webui/src/i18n/locales/id/common.json | 21 +- webui/src/i18n/locales/ja/common.json | 21 +- webui/src/i18n/locales/ko/common.json | 21 +- webui/src/i18n/locales/pt-BR/common.json | 21 +- webui/src/i18n/locales/vi/common.json | 21 +- webui/src/i18n/locales/zh-CN/common.json | 21 +- webui/src/i18n/locales/zh-TW/common.json | 21 +- webui/src/lib/api.ts | 67 ++- webui/src/lib/context-graph-layout.ts | 100 ++++ webui/src/lib/context-graph.ts | 47 ++ webui/src/lib/model-request.ts | 12 +- webui/src/lib/surface-focus.ts | 22 + webui/src/lib/thread-event-projection.ts | 14 + webui/src/lib/types.ts | 34 +- webui/src/lib/webui-thread-cache.ts | 51 +- webui/src/tests/api.test.ts | 60 ++- webui/src/tests/code-block.test.tsx | 7 + .../src/tests/composer-usage-popover.test.tsx | 240 +++------ webui/src/tests/context-graph-canvas.test.ts | 11 + webui/src/tests/context-graph-motion.test.tsx | 119 +++++ webui/src/tests/context-inspector.test.tsx | 70 +++ webui/src/tests/context-replay.test.tsx | 62 +++ webui/src/tests/dialog-drag.test.tsx | 61 +++ webui/src/tests/file-preview-panel.test.tsx | 7 +- webui/src/tests/latest-thread-request.test.ts | 2 +- .../src/tests/markdown-text-renderer.test.tsx | 4 +- webui/src/tests/message-bubble.test.tsx | 4 +- webui/src/tests/model-request.test.ts | 60 ++- webui/src/tests/prompt-navigator.test.tsx | 17 +- webui/src/tests/reload-cache.test.ts | 49 ++ .../tests/session-automation-lazy.test.tsx | 3 +- webui/src/tests/session-info-popover.test.tsx | 15 +- webui/src/tests/thread-composer.test.tsx | 182 ++----- webui/src/tests/thread-shell.test.tsx | 47 +- webui/src/tests/ui-shape-system.test.tsx | 3 +- webui/src/tests/useReconnectRuns.test.tsx | 2 +- 132 files changed, 4673 insertions(+), 1159 deletions(-) create mode 100644 nanobot/context_graph.py create mode 100644 nanobot/context_sources.py create mode 100644 nanobot/file_references.py create mode 100644 nanobot/session/history_graph.py create mode 100644 nanobot/webui/context_observer.py create mode 100644 nanobot/webui/context_source_hook.py create mode 100644 tests/agent/test_context_source_hook.py create mode 100644 tests/session/test_history_graph.py create mode 100644 tests/test_context_graph.py create mode 100644 tests/webui/test_context_observer.py create mode 100644 webui/browser/context-graph-fixture.tsx create mode 100644 webui/browser/context-graph.html create mode 100644 webui/browser/context-graph.spec.ts create mode 100644 webui/src/components/thread/ContextGraphScene.tsx create mode 100644 webui/src/components/thread/ContextInspector.tsx create mode 100644 webui/src/components/thread/ContextReplayButton.tsx create mode 100644 webui/src/components/thread/graph-canvas.ts create mode 100644 webui/src/components/thread/graph-presentation.ts create mode 100644 webui/src/components/ui/sidebar-panel.tsx create mode 100644 webui/src/lib/context-graph-layout.ts create mode 100644 webui/src/lib/context-graph.ts create mode 100644 webui/src/lib/surface-focus.ts create mode 100644 webui/src/tests/context-graph-canvas.test.ts create mode 100644 webui/src/tests/context-graph-motion.test.tsx create mode 100644 webui/src/tests/context-inspector.test.tsx create mode 100644 webui/src/tests/context-replay.test.tsx create mode 100644 webui/src/tests/dialog-drag.test.tsx diff --git a/docs/webui.md b/docs/webui.md index 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 and The 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 previews diff --git a/nanobot/agent/context.py b/nanobot/agent/context.py index d1102e06e..dcb480423 100644 --- a/nanobot/agent/context.py +++ b/nanobot/agent/context.py @@ -10,6 +10,7 @@ from nanobot.agent.skills import SkillsLoader from nanobot.agent.tools import mcp as mcp_tools from nanobot.agent.tools import sessions as session_tools from nanobot.apps.cli import utils as cli_app_utils +from nanobot.context_sources import record_source from nanobot.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 content if not content.strip(): + record_source(file_path, "", loaded=False) continue if filename in self._SKIPPABLE_DEFAULTS and self._is_template_content( content, filename ): + record_source(file_path, "", loaded=False) continue parts.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.py index 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.py index ad2f4125a..e17000f9e 100644 --- a/nanobot/agent/progress_hook.py +++ b/nanobot/agent/progress_hook.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +from pathlib import Path from typing import Any from loguru import logger @@ -8,6 +9,7 @@ from loguru import logger from nanobot.agent.hook import AgentHook, AgentHookContext from nanobot.bus.outbound_events import ProgressEvent, StreamDeltaEvent, StreamEndEvent from nanobot.events import NO_EVENTS, EventSink +from nanobot.security.workspace_access import current_tool_workspace from nanobot.utils.helpers import IncrementalThinkExtractor, strip_think from 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.publish self._streaming = streaming self._session_key = session_key self._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] = directory payloads = ( build_tool_event_finish_payloads(context) if finished else [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"] = directory await 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.py index 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 = None async 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_usage state.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.py index 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_source from nanobot.runtime_context import RuntimeContextBlock _SKILL_REFERENCE = re.compile(r"(? 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 None snapshot = 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 content def 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.py index 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_hook diff --git a/nanobot/bus/notification_delivery.py b/nanobot/bus/notification_delivery.py index 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 PromptSourcesEvent from 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.py index 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_reco original_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_res original_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_et assert 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"]) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("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 + + +@pytest.mark.asyncio +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.py index 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, monke if 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"] == graph assert 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(h assert [row["text"] for row in history.read(f"websocket:{chat}")] == ["first", "last"] finally: await channel.stop() + + +@pytest.mark.parametrize("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.py index 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: E402 sync_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.py index 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_prompt from nanobot.utils.helpers import sync_workspace_templates from nanobot.utils.token_encoding import warmup_token_encoding from nanobot.webui.build import BuildMode +from nanobot.webui.context_source_hook import create_context_source_hook from nanobot.webui.dev import WebUIDevError, WebUIDevServer from 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.py new file mode 100644 index 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: int diff --git a/nanobot/context_sources.py b/nanobot/context_sources.py new file mode 100644 index 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.py index c2e7c4bea..f3ff8d096 100644 --- a/nanobot/events.py +++ b/nanobot/events.py @@ -24,6 +24,7 @@ class ModelRequestEvent(AgentEvent): usage: LLMUsage | None = None round_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.py new file mode 100644 index 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.py index 498e5f46b..2bd93c660 100644 --- a/nanobot/session/display_history.py +++ b/nanobot/session/display_history.py @@ -8,6 +8,8 @@ from enum import StrEnum from pathlib import Path from typing import Any, cast +from nanobot.session.history_graph import encode_graph_fields, graph_size_adjustment + MAX_HISTORY_FACT_BYTES = 8 * 1024 * 1024 HISTORY_GENERATION_METADATA_KEY = "_history_generation" @@ -40,13 +42,23 @@ class HistoryFact: created_at_ms: int = 0 def 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.py new file mode 100644 index 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 stored diff --git a/nanobot/session/sqlite_store.py b/nanobot/session/sqlite_store.py index fd8e3b36d..16fb4aaf7 100644 --- a/nanobot/session/sqlite_store.py +++ b/nanobot/session/sqlite_store.py @@ -12,6 +12,7 @@ from typing import Any, TypeVar, cast from nanobot.providers.base import ProviderConversationState from nanobot.session.display_history import HistoryFact, HistoryKind, HistoryReader +from nanobot.session.history_graph import history_record_size from nanobot.session.history_visibility import is_hidden_history_message from 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 errors with 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, 0 if 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.COMPLETION db.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 errors def 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.py index 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.py index 27b12f79e..41cc4862e 100644 --- a/nanobot/utils/prompt_templates.py +++ b/nanobot/utils/prompt_templates.py @@ -11,6 +11,8 @@ from typing import Any from 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 ends with 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 text diff --git a/nanobot/webui/client_contract.py b/nanobot/webui/client_contract.py index 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.py new file mode 100644 index 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.py new file mode 100644 index 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 None diff --git a/nanobot/webui/history.py b/nanobot/webui/history.py index bfb888604..db93bc4cf 100644 --- a/nanobot/webui/history.py +++ b/nanobot/webui/history.py @@ -5,6 +5,7 @@ from typing import Any from nanobot.bus.events import INBOUND_META_LOCAL_MEDIA from nanobot.session.display_history import HistoryFact, HistoryKind, HistoryReader +from nanobot.session.history_graph import expand_graph_fields from nanobot.webui.session_identity import webui_chat_id _EVENTS = { @@ -31,7 +32,7 @@ _CONTENT_FIELDS = frozenset({ "merge_next", "latency_ms", "usage", "round_usages", "context_window_tokens", "goal_state", "outcome", "failure_kind", "failure_error_kind", "failure_attempts", "failure_message", "transcript_incomplete", "stream_id", "compaction_id", "phase", "reason", "render_as", - "request_id", "run_id", "sequence", + "request_usage", "request_id", "run_id", "sequence", "context_graph", "context_snapshot", }) @@ -63,14 +64,14 @@ def fact_from_record(record: Mapping[str, Any]) -> HistoryFact: return fact -def record_from_fact(fact: HistoryFact, key: str) -> dict[str, Any]: +def record_from_fact(fact: HistoryFact, key: str, *, expand_graphs: bool = True) -> dict[str, Any]: if fact.kind in _MESSAGE_KINDS.values(): event = "message" message_kind = next(name for name, kind in _MESSAGE_KINDS.items() if kind is fact.kind) else: event = next(name for name, kind in _EVENTS.items() if kind is fact.kind) message_kind = None - record = {"event": event, "chat_id": webui_chat_id(key), **fact.content, + record = {"event": event, "chat_id": webui_chat_id(key), **(expand_graph_fields(fact.content) if expand_graphs else fact.content), "created_at_ms": fact.created_at_ms} if message_kind: record["kind"] = message_kind @@ -86,6 +87,6 @@ def record_from_fact(fact: HistoryFact, key: str) -> dict[str, Any]: def turn_records( history: HistoryReader, ordinal: int, *, max_records: int | None = None, max_bytes: int | None = None, ) -> list[dict[str, Any]]: - return [{**record_from_fact(fact, history.key), + return [{**record_from_fact(fact, history.key, expand_graphs=False), "_webui_replay_identity": f"turn:{ordinal}:record:{position}"} for position, fact in history.read_entries(ordinal, max_records=max_records, max_bytes=max_bytes)] diff --git a/nanobot/webui/outbound_delivery.py b/nanobot/webui/outbound_delivery.py index 5a0621953..1c26e5aa0 100644 --- a/nanobot/webui/outbound_delivery.py +++ b/nanobot/webui/outbound_delivery.py @@ -1,5 +1,6 @@ from __future__ import annotations +import asyncio import json from collections.abc import Callable, Mapping, Sequence from dataclasses import dataclass @@ -24,6 +25,8 @@ from nanobot.bus.outbound_events import ( ) from nanobot.bus.queue import MessageBus from nanobot.bus.runtime_events import SubagentTaskChanged +from nanobot.context_graph import ContextGraph +from nanobot.context_sources import PromptSourcesEvent from nanobot.events import ModelRequestEvent from nanobot.pairing.events import PairingChanged from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY @@ -32,6 +35,7 @@ from nanobot.session.webui_turns import ( mark_websocket_turn_transcript_persistence_failed, websocket_turn_transcript_persistence_failed, ) +from nanobot.webui.context_observer import ContextGraphObserver from nanobot.webui.media_gateway import WebUIMediaGateway from nanobot.webui.metadata import ( WEBSOCKET_TURN_OWNER_METADATA_KEY, @@ -44,6 +48,7 @@ from nanobot.webui.outbound_wire import ( GoalStateWirePayload, GoalStatusWirePayload, MessageWirePayload, + NotificationProjection, RuntimeModelWirePayload, SessionUpdatedWirePayload, StreamWirePayload, @@ -73,6 +78,12 @@ WebUIAudience: TypeAlias = ChatAudience | Literal["all_connections", "authentica _ACTIVITY_BATCH_BYTES = 128 * 1024 +async def _encode_payload(payload: Mapping[str, object]) -> str: + if "context_graph" in payload or "context_snapshot" in payload: + return await asyncio.to_thread(json.dumps, payload, ensure_ascii=False) + return json.dumps(payload, ensure_ascii=False) + + class WebUIOutboundTransport(Protocol): """Snapshot recipients and enqueue already projected public JSON frames.""" @@ -100,17 +111,39 @@ class WebUIOutboundDelivery: self._transcripts = transcripts self._temporary_chats = temporary_chats self._session_projection = session_projection + self._context_graph = ContextGraphObserver(transcripts.sessions) self._stream_text_buffers: dict[tuple[str, str], list[str]] = {} self._reasoning_text_buffers: dict[tuple[str, str], list[str]] = {} + async def _project_notification(self, msg: OutboundMessage) -> NotificationProjection | None: + event = msg.event + if not isinstance(event, ModelRequestEvent | ContextCompactionEvent): + return project_notification(msg.chat_id, event, msg.metadata) + persistent = self._temporary_chats.should_persist_transcript(msg.chat_id) + if isinstance(event, ModelRequestEvent): + graph: ContextGraph = {"nodes": [], "edges": []} + try: + graph = await self._context_graph.snapshot(msg.chat_id, msg.metadata, persistent=persistent) + except Exception: + logger.exception("Unable to restore context graph") + return project_notification(msg.chat_id, event, msg.metadata, context_graph=graph) + if event.phase == "succeeded": + try: + await self._context_graph.reset(msg.chat_id, msg.metadata, persistent=persistent) + except Exception: + logger.exception("Unable to reset context graph") + return project_notification(msg.chat_id, event, msg.metadata) + def bind_pairing(self, bus: MessageBus, *, channel: str) -> Callable[[], None]: async def queue_changed(event: PairingChanged) -> None: await bus.publish_event(event, channel=channel, chat_id="*") return bus.subscribe(queue_changed, PairingChanged) - def discard(self, chat_id: str) -> None: + def discard(self, chat_id: str, *, complete: bool = False) -> None: """Forget unclosed streams when a turn ends or its chat is discarded.""" + if not complete or self._temporary_chats.should_persist_transcript(chat_id): + self._context_graph.discard(chat_id) for buffers in (self._stream_text_buffers, self._reasoning_text_buffers): for key in tuple(buffers): if key[0] == chat_id: @@ -134,7 +167,9 @@ class WebUIOutboundDelivery: *, label: str, ) -> None: - raw = json.dumps(payload, ensure_ascii=False) + if not recipients: + return + raw = await _encode_payload(payload) for connection in recipients: await self._transport.webui_send_raw(connection, raw, label=label) @@ -182,10 +217,10 @@ class WebUIOutboundDelivery: for msg in messages: progress = msg.event if isinstance(msg.event, ProgressEvent) else None if progress is not None: - body = self._message_payload(msg, progress) + body = await self._message_payload(msg, progress) persistent, label = True, " " else: - notification = project_notification(msg.chat_id, msg.event, msg.metadata) + notification = await self._project_notification(msg) assert notification is not None body = dict(notification.payload) persistent = notification.persistence == "turn_activity" @@ -195,7 +230,7 @@ class WebUIOutboundDelivery: msg.chat_id, body, metadata=msg.metadata, phase="activity", include_source=progress is not None, ) try: - raw = json.dumps(body, ensure_ascii=False) + raw = await _encode_payload(body) size = len(raw.encode("utf-8")) except (TypeError, ValueError, RecursionError) as exc: logger.warning("WebUI activity encoding failed for {}: {}", msg.chat_id, exc) @@ -212,6 +247,12 @@ class WebUIOutboundDelivery: async def send(self, msg: OutboundMessage) -> None: event = msg.event + if isinstance(event, PromptSourcesEvent): + await self._context_graph.observe_prompt( + msg.chat_id, event.sources, msg.metadata, + persistent=self._temporary_chats.should_persist_transcript(msg.chat_id), + ) + return if isinstance(event, PairingChanged): await self._fanout( self._transport.webui_recipients("authenticated_webui"), @@ -248,7 +289,7 @@ class WebUIOutboundDelivery: body["provenance"] = event.provenance await self._fanout(recipients, body, label=" user_message ") return - notification = project_notification(msg.chat_id, event, msg.metadata) + notification = await self._project_notification(msg) if notification is not None: if recipients or notification.deliver_offline: await self._send_payload( @@ -373,7 +414,7 @@ class WebUIOutboundDelivery: chat_id, persisted=persisted, metadata=metadata, phase=phase, ) - def _message_payload(self, msg: OutboundMessage, progress: ProgressEvent | None) -> dict[str, Any]: + async def _message_payload(self, msg: OutboundMessage, progress: ProgressEvent | None) -> dict[str, Any]: text = msg.content user_shell = msg.metadata.get(INBOUND_META_USER_SHELL) is True payload: MessageWirePayload = { @@ -401,6 +442,10 @@ class WebUIOutboundDelivery: payload["latency_ms"] = int(latency) if progress and progress.tool_events: payload["tool_events"] = project_tool_events(progress.tool_events) + await self._context_graph.observe_tools( + msg.chat_id, payload["tool_events"], msg.metadata, + persistent=self._temporary_chats.should_persist_transcript(msg.chat_id), + ) agent_ui = msg.metadata.get(OUTBOUND_META_AGENT_UI) if agent_ui is not None: payload["agent_ui"] = agent_ui @@ -410,7 +455,7 @@ class WebUIOutboundDelivery: async def _send_message(self, msg: OutboundMessage, progress: ProgressEvent | None) -> None: recipients = self._transport.webui_recipients(ChatAudience(msg.chat_id)) - body = self._message_payload(msg, progress) + body = await self._message_payload(msg, progress) await self._persist_turn_transcript_event( msg.chat_id, body, metadata=msg.metadata, phase="activity" if progress else "answer", include_source=True, @@ -528,7 +573,7 @@ class WebUIOutboundDelivery: if persisted: # A durable incomplete marker allows HTTP recovery after restart. clear_websocket_turn_if_current(chat_id, turn_owner) - self.discard(chat_id) + self.discard(chat_id, complete=True) await self._fanout(recipients, body, label=f" {body['event']} ") async def _send_goal_state(self, chat_id: str, blob: dict[str, Any]) -> None: diff --git a/nanobot/webui/outbound_wire.py b/nanobot/webui/outbound_wire.py index 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, ContextSnapshot from nanobot.events import AgentEvent, CompactionReason, ModelRequestEvent from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY @@ -97,6 +98,8 @@ class TurnEndWirePayload(_ChatWirePayload): class ModelRequestWirePayload(_ChatWirePayload): + request_usage: dict[str, int] | None + context_graph: NotRequired[ContextGraph] event: Literal["model_request"] request_id: str run_id: str @@ -108,6 +111,7 @@ class ModelRequestWirePayload(_ChatWirePayload): class ContextCompactionWirePayload(_ChatWirePayload): + context_snapshot: NotRequired[ContextSnapshot] event: Literal["context_compaction"] compaction_id: str phase: Literal["started", "succeeded", "failed", "cancelled"] @@ -253,6 +257,7 @@ class NotificationProjection: def project_notification( chat_id: str, event: AgentEvent | None, metadata: Mapping[str, object] | None = None, + *, context_graph: ContextGraph | None = None, ) -> NotificationProjection | None: """Keep notification serialization and persistence decisions at one boundary.""" if isinstance(event, ModelRequestEvent): @@ -260,7 +265,10 @@ def project_notification( "event": "model_request", "chat_id": chat_id, "request_id": event.request_id, "run_id": event.run_id, "sequence": event.sequence, "phase": event.phase, + "request_usage": event.request_usage.to_turn_dict() if event.request_usage is not None else None, } + if context_graph is not None: + payload["context_graph"] = context_graph if event.usage is not None: payload["usage"] = event.usage.to_turn_dict() payload["round_usages"] = [usage.to_turn_dict() for usage in event.round_usages[-8:]] diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py index 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_message from nanobot.session.manager import Session, SessionManager from nanobot.session.sqlite_store import SessionConflictError @@ -233,7 +239,7 @@ def _record_json_line(record: dict[str, Any]) -> str: def _records_bytes(records: list[dict[str, Any]]) -> int: total = 0 for record in records: - total += len(_record_json_line(record).encode("utf-8")) + 1 + total += len(_record_json_line(record).encode("utf-8")) + graph_size_adjustment(record) + 1 return total @@ -581,9 +587,6 @@ class WebUITranscriptRecorder: for event in events: try: fact = fact_from_record(_record_for_append(event)) - if len(events) > 1: - # An invalid member must not roll back otherwise valid activity. - fact.encode() facts.append(fact) except (ValueError, TypeError) as exc: self._log.warning("history append failed for {}: {}", chat_id, exc) @@ -591,8 +594,12 @@ class WebUITranscriptRecorder: if not facts: return False try: - await self.sessions.state.append_history(webui_session_key(chat_id), facts, - expected_generation=generation) + errors = await self.sessions.state.append_history(webui_session_key(chat_id), facts, + expected_generation=generation, + skip_invalid=len(events) > 1) + for error in errors: + self._log.warning("history append failed for {}: {}", chat_id, error) + valid = valid and not errors except (OSError, ValueError, TypeError, sqlite3.Error, SessionConflictError, SessionOperationQueueFullError) as exc: self._log.warning("history append failed for {}: {}", chat_id, exc) return False @@ -1510,6 +1517,8 @@ def _client_projection_event( "compaction_id": compaction_id, "phase": phase, } + if (snapshot := decode_snapshot(record.get("context_snapshot"))) is not None: + projected["context_snapshot"] = snapshot reason = record.get("reason") if isinstance(reason, str) and reason in {"idle", "context_pressure", "manual", "provider_native"}: projected["reason"] = reason @@ -1528,6 +1537,10 @@ def _client_projection_event( ): return None projected.update(request_id=request_id, run_id=run_id, sequence=sequence, phase=phase) + if "request_usage" in record: + projected["request_usage"] = _sanitize_turn_usage(record["request_usage"]) or None + if (graph := decode_graph(record.get("context_graph"))) is not None: + projected["context_graph"] = graph latency_ms = record.get("latency_ms") if isinstance(latency_ms, int | float) and latency_ms >= 0: projected["latency_ms"] = int(latency_ms) @@ -1757,6 +1770,7 @@ def build_session_thread_response( "active_turn_id": turn_id if active else None} +@graph_decoding() def build_webui_thread_response( session_key: str, *, diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py index 516d5c1f1..5bc602a4c 100644 --- a/nanobot/webui/ws_http.py +++ b/nanobot/webui/ws_http.py @@ -18,7 +18,7 @@ import time from collections.abc import Awaitable, Callable, Mapping from dataclasses import dataclass, field from pathlib import Path -from typing import TYPE_CHECKING, Any, Protocol, cast +from typing import TYPE_CHECKING, Any, Protocol, TypeVar, cast from urllib.parse import quote, unquote, urlsplit, urlunsplit from loguru import logger @@ -29,6 +29,7 @@ from websockets.http11 import Response from nanobot.agent.subagent import SubagentControlError from nanobot.agent.subagent_status import SubagentSessionError from nanobot.command.application import builtin_command_palette +from nanobot.context_graph import ContextGraph from nanobot.cron.binding import CronBindingError, binding_revision from nanobot.cron.session_turns import is_bound_cron_job from nanobot.cron.types import CronJob, CronSchedule @@ -348,8 +349,58 @@ def _resolve_bootstrap_model_name( return _default_model_name_from_config(config_path) or "" -class _HistoryProjection(Protocol): - def __call__(self, request: WsRequest, key: str, *, history: HistoryReader) -> Response: ... +_ProjectionResult = TypeVar("_ProjectionResult", covariant=True) + + +class _HistoryProjection(Protocol[_ProjectionResult]): + def __call__(self, request: WsRequest, key: str, *, history: HistoryReader) -> _ProjectionResult: ... + + +@dataclass +class _PreparedThreadResponse: + data: dict[str, Any] + headers: list[tuple[str, str]] + + +def _encode_thread_response(data: dict[str, Any], *, graph_references: bool, **kwargs: Any) -> Response: + if graph_references: + graphs: dict[str, object] = {} + references: dict[int, tuple[str, ContextGraph]] = {} + nodes: list[object] = [] + edges: list[object] = [] + node_ids: dict[int, int] = {} + edge_ids: dict[int, int] = {} + + def index(value: object, values: list[object], ids: dict[int, int]) -> int: + identity = id(value) + if identity not in ids: + ids[identity] = len(values) + values.append(value) + return ids[identity] + + def reference(graph: ContextGraph) -> str: + identity = id(graph) + if identity not in references: + key = str(len(graphs)) + references[identity] = (key, graph) + graphs[key] = { + "nodes": [index(node, nodes, node_ids) for node in graph["nodes"]], + "edges": [index(edge, edges, edge_ids) for edge in graph["edges"]], + } + return references[identity][0] + + for event in data.get("events", []): + if "context_graph" in event: + event["context_graph_ref"] = reference(event.pop("context_graph")) + snapshot = event.get("context_snapshot") + if isinstance(snapshot, dict) and "graph" in snapshot: + snapshot = cast(dict[str, Any], snapshot) + event["context_snapshot"] = {**snapshot, "graph_ref": reference(snapshot["graph"])} + event["context_snapshot"].pop("graph") + data["context_graphs"] = graphs + data["context_graph_nodes"] = nodes + data["context_graph_edges"] = edges + return _http_json_response(data, **kwargs) class GatewayHTTPHandler: @@ -1048,8 +1099,8 @@ class GatewayHTTPHandler: return self.session_manager.read_session_version(key) if self.session_manager is not None else None async def _project_session_history( - self, request: WsRequest, key: str, project: _HistoryProjection, - ) -> Response: + self, request: WsRequest, key: str, project: _HistoryProjection[_ProjectionResult], + ) -> _ProjectionResult | Response: if not self.check_api_token(request): return _http_error(401, "Unauthorized") decoded = _decode_api_key(key) @@ -1111,11 +1162,20 @@ class GatewayHTTPHandler: timer = loop.call_later(0.05, sample_event_loop_lag) started = time.perf_counter() - def project(request: WsRequest, key: str, *, history: HistoryReader) -> Response: + def project(request: WsRequest, key: str, *, history: HistoryReader) -> Response | _PreparedThreadResponse: return self._handle_webui_thread_get(request, key, history=history, diagnostics=diagnostics) try: - response = await self._project_session_history(request, key, project) + prepared = await self._project_session_history(request, key, project) + if isinstance(prepared, _PreparedThreadResponse): + response = await asyncio.to_thread( + _encode_thread_response, prepared.data, + graph_references=_query_first(_parse_query(request.path), "context_graph_encoding") == "references-v1", + accept_encoding=_combined_list_header(request.headers, "Accept-Encoding"), + extra_headers=prepared.headers, metrics=diagnostics.response, + ) + else: + response = prepared finally: active = False timer.cancel() @@ -1170,7 +1230,7 @@ class GatewayHTTPHandler: *, history: HistoryReader, diagnostics: _WebUIThreadDiagnostics | None = None, - ) -> Response: + ) -> Response | _PreparedThreadResponse: if not self.check_api_token(request): return _http_error(401, "Unauthorized") decoded_key = _decode_api_key(key) @@ -1215,6 +1275,7 @@ class GatewayHTTPHandler: include_model_requests = _query_first(query, "include_model_requests") == "1" revision_variant = { "include_model_requests": include_model_requests, + "context_graph_encoding": _query_first(query, "context_graph_encoding"), "active_turn_id": active_turn_id, "active_turn_started_at": active_turn_started_at, "active_turn_transcript_persistence_failed": ( @@ -1267,11 +1328,8 @@ class GatewayHTTPHandler: if final_revision is not None and final_revision == initial_revision: response_headers.append(("ETag", _quoted_etag(final_revision))) data["revision"] = final_revision - return _http_json_response( - data, - accept_encoding=_combined_list_header(request.headers, "Accept-Encoding"), - extra_headers=response_headers, - metrics=diagnostics.response if diagnostics is not None else None, + return _PreparedThreadResponse( + data=data, headers=response_headers, ) def _handle_webui_trace_detail_get(self, request: WsRequest, key: str, *, history: HistoryReader) -> Response: diff --git a/pyproject.toml b/pyproject.toml index 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.py new file mode 100644 index 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.py index 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) + + +@pytest.mark.asyncio +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 + + +@pytest.mark.asyncio +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.py index 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 Path from unittest.mock import AsyncMock, MagicMock import 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.py index 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) == 1 diff --git a/tests/command/test_compact_command.py b/tests/command/test_compact_command.py index 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.py new file mode 100644 index 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 + + +@pytest.mark.parametrize("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() + + +@pytest.mark.parametrize("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())) == [] + + +@pytest.mark.parametrize("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] + + +@pytest.mark.parametrize("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.py new file mode 100644 index 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)) + + +@pytest.mark.asyncio +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.py index 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): +@pytest.mark.parametrize("measured", [False, True]) +def test_model_request_persists_through_reconnect_projection(history, tmp_path, phase, measured): from nanobot.events import ModelRequestEvent from nanobot.providers.base import LLMUsage from 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 None assert projection.persistence == "turn_activity" diff --git a/tests/webui/test_context_observer.py b/tests/webui/test_context_observer.py new file mode 100644 index 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") + + +@pytest.mark.parametrize("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 + + +@pytest.mark.parametrize("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.tsx new file mode 100644 index 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(null); + if (new URLSearchParams(location.search).has("drawer")) return
+ + {opened} +
; + return
{opened}{new URLSearchParams(location.search).has("pair") &&
}
; +} +await initializeI18n(); +createRoot(document.getElementById("root")!).render(); diff --git a/webui/browser/context-graph.html b/webui/browser/context-graph.html new file mode 100644 index 000000000..bd81f9e4e --- /dev/null +++ b/webui/browser/context-graph.html @@ -0,0 +1 @@ +Context graph interaction
diff --git a/webui/browser/context-graph.spec.ts b/webui/browser/context-graph.spec.ts new file mode 100644 index 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.ts index 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 an await 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 nav await 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 and expect((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 sc await 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 retries await 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, bu await 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 o await 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 o await 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 o await 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.ts index 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.ts index 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 returns await 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.tsx index 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" ? : surface === "skill-detail" ? - : surface === "session-jobs" ? jobs} onEdit={async () => jobs} /> : surface === "linear-members" ? : null} } diff --git a/webui/browser/skeleton-layout.spec.ts b/webui/browser/skeleton-layout.spec.ts index 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.tsx index 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: - {context.composerPortalTarget && createPortal(composer, context.composerPortalTarget)} + {context.composerPortalTarget && createPortal(
{composer}
, context.composerPortalTarget)} } /> ; diff --git a/webui/browser/typography.spec.ts b/webui/browser/typography.spec.ts index 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.lock index 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/css-tree@2.3.11", "", {}, "sha512-aEokibJOI77uIlqoBOkVbaQGC9zII0A+JH1kcTNKW2CwyYWD8KM6qdo+4c77wD3wZOQfJuNWAr9M4hdk+YhDIg=="], + "@types/d3-force": ["@types/d3-force@3.0.10", "", {}, "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw=="], + "@types/debug": ["@types/debug@4.1.13", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="], "@types/esrecurse": ["@types/esrecurse@4.3.1", "", {}, "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw=="], @@ -530,6 +534,14 @@ "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], + "d3-dispatch": ["d3-dispatch@3.0.2", "", {}, "sha512-sAzH4Y4nsLo8eSqw5jKiZt+LU2wZmL/qS+OkxQGjhwazB/D7TY34R/QK1eshfGr7cZEKymKZ/Haem7m+lu98Sg=="], + + "d3-force": ["d3-force@3.0.1", "", { "dependencies": { "d3-dispatch": "1 - 3", "d3-quadtree": "1 - 3", "d3-timer": "1 - 3" } }, "sha512-kAaaHLFebBYwgi5cYBXAI8vKrQFMCD2MEswj2QuPKKbdU1wYLc8WXtS7O8F/b6POCIe3gJjY6hkDstHi1yMETQ=="], + + "d3-quadtree": ["d3-quadtree@3.0.2", "", {}, "sha512-9Lu9mqJKRbIk0d6mKDjpvPURaPdwHVK5CYbcdd0/4vBgz4ldz/7TIOse3kNERsByGNfld58KEco507AztJWyTQ=="], + + "d3-timer": ["d3-timer@3.0.2", "", {}, "sha512-1Il1aliroVSErrv5aulRBxAY+7+DnaoLIWGd1C6SsBTWDeobWiP/V69vwb8vT6abR1kKwaNe1196pmaQ1fK90A=="], + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], "decamelize": ["decamelize@1.2.0", "", {}, "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA=="], diff --git a/webui/package-lock.json b/webui/package-lock.json index 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.json index 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.tsx index 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 ? ( {lines.map((_, index) => index + 1).join("\n")} + style={{ minWidth: `calc(${String(lines.length).length}ch + 1.15rem)` }}>{lines.map((_, index) => index + 1).join("\n")} {renderText(code)} ) : showLineNumbers ? ( diff --git a/webui/src/components/FilePreviewPanelView.tsx b/webui/src/components/FilePreviewPanelView.tsx index 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, onImageOpenChange onOpenFilePreview?: (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 = ; + return (
- {markdown ? ( -
- -
- ) : null} + {markdown && (actionsHost ? createPortal(modeControl, actionsHost) :
{modeControl}
)}
+ {...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" ? (
@@ -57,9 +61,9 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange {previewKind === "image" ?
: <> - {previewKind === "markdown" ?
-
- {[t("filePreview.preview"), t("filePreview.source")].map((label) => {label})} + {previewKind === "markdown" && !actionsHost ?
+
+ {modeLabel}
: null} {previewKind === "markdown" && mode === "preview" ?
@@ -67,10 +71,10 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange {["w-full", "w-5/6", "w-3/4"].map((width) =>
)} -
:
+
:
{["w-2/3", "w-full", "w-5/6", "w-3/4", "w-1/2", "w-3/5"].map((width) =>
-
-
+
+
)}
} } diff --git a/webui/src/components/MarkdownTextRenderer.tsx b/webui/src/components/MarkdownTextRenderer.tsx index 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 (
{messageText} diff --git a/webui/src/components/PreviewPane.tsx b/webui/src/components/PreviewPane.tsx index 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()); const tabList = useRef(null); const pendingFocus = useRef(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, onClos onCloseTab(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 ; + ; } diff --git a/webui/src/components/ViewportCodeRows.tsx b/webui/src/components/ViewportCodeRows.tsx index 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 ( + style={{ minWidth: lineNumberWidth }}> {rows.map((_, index) => start + index + 1).join("\n")} @@ -78,7 +79,8 @@ export function ViewportCodeRows({ rows, stylesheet, useInlineStyles }: RowsProp return ( {chunks.map((chunk, index) => )} + stylesheet={tokenStyles} useInlineStyles={useInlineStyles} highlighted={visible.has(index)} + lineNumberWidth={`calc(${String(rows.length).length}ch + 1.15rem)`} />)} ); } diff --git a/webui/src/components/settings/SkillsCatalogSettings.tsx b/webui/src/components/settings/SkillsCatalogSettings.tsx index 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", )} >
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(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 = ( - - ); - return ( - - - {bottomSheet ? trigger : ( - - {trigger} - - {contextDescription} - - - )} + const triggerWithTooltip = + + {trigger} + {contextDescription} + + ; - setOpen(false)}> -
- {contextPercentage !== null ? ( - <> -
-
- - {t("thread.composer.context.contextTitle", { - defaultValue: "Context", - })} - - - {formatCompactTokenCount(context!.contextTokens)} / {formatCompactTokenCount( - context!.contextWindowTokens!, - )} - -
- - {contextPercentage}% - -
-
-
-
- - ) : null} - - {normalizedRounds.length > 0 ? ( - <> -
- - {t("thread.composer.context.recentRounds", { - defaultValue: "Recent rounds", - })} - - - {t("thread.composer.context.inputTrend", { - defaultValue: "Input tokens", - })} - -
-
- {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 => !!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 ( - 1 - && index === normalizedRounds.length - 1 - && "justify-end", - index === normalizedRounds.length - 1 && "opacity-100", - )} - > - - - - {cachedKnown ? ( - <> - {notReusedTokens > 0 ? ( - - ) : null} - {cachedTokens > 0 ? ( - - ) : null} - - ) : ( - - )} - - - event.preventDefault(), - } : {})} - > - - {timestampLabel} - - - {detailRows.map((row) => ( - - - {row.label} - - - {row.value} - - - ))} - - {detailNote ? ( - - {detailNote} - - ) : null} - - - - ); - })} -
- - ) : null} - -
- - - - ); -} - -function UsagePanel({ bottomSheet, onDismiss, children }: { - bottomSheet: boolean; - onDismiss: () => void; - children: ReactNode; -}) { - const { t } = useTranslation(); - const panelRef = useRef(null); - const [panelNode, setPanelNode] = useState(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) => { - if (gesture.current?.pointerId !== event.pointerId) return; - gesture.current = null; - suppressClick.current = true; - setDragging(false); - setOffset(0); + const inspector = { setOpen(false); onOpenFile(path); } : undefined} />; + const onPanelKeyDown = (event: KeyboardEvent) => { + if (event.key === "Escape" && !event.defaultPrevented) { event.preventDefault(); close(); } }; - if (bottomSheet) { - return ( - - -
- {title} -
-
- - {children} - -
-
- ); - } - - return ( - - {children} - - ); + return <> + {triggerHost === undefined ? triggerWithTooltip : triggerHost && createPortal(triggerWithTooltip, triggerHost)} + {narrow ? + { 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; + }}> + {t("thread.composer.context.panelTitle")} + {inspector} + + : createPortal( + {inspector} + , sidebarHost ?? document.body)} + ; } diff --git a/webui/src/components/thread/ContextGraphScene.tsx b/webui/src/components/thread/ContextGraphScene.tsx new file mode 100644 index 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(null); + const canvas = useRef(null); + const paletteProbe = useRef(null); + const palette = useRef(); + const nodeElements = useRef(new Map()); + const focused = useRef(null); + const positions = useRef(new Map()); + const particles = useRef(new Map()); + const simulation = useRef>(); + const settlement = useRef | null>(null); + const paintedGraph = useRef(); + const [presentation] = useState(createGraphPresentation); + const [frame, setFrame] = useState(presentation.frame); + const [size, setSize] = useState({ width: 550, height: 300 }); + const [active, setActive] = useState(null); + const [hovered, setHovered] = useState(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(() => (
+ {graph.nodes.map((node) => )} +
), [graph.nodes, active, schedule]); + return
{ + 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 }); + }}> + + {onExpand && } + {!graph.nodes.length && !frame.nodes.length &&

{t("thread.composer.context.noFiles")}

} +
; +}); diff --git a/webui/src/components/thread/ContextInspector.tsx b/webui/src/components/thread/ContextInspector.tsx new file mode 100644 index 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(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) => + }> + + +
+
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]")}> +
+
+ + +
+
+ {used === null ? "—" : `${estimated ? "≈" : ""}${Math.round(used)}%`} + {meterHover && (hasTokenUsage || cached !== undefined || duration !== undefined || replay !== null) &&
+
+ {hasTokenUsage && <>
{t("thread.composer.context.panelTitle")}
{t("thread.composer.context.tokenUsage", { + used: tokens === undefined ? "—" : `${estimated ? "≈" : ""}${tokenNumbers.format(tokens / 1000)}k`, + limit: windowTokens ? `${tokenNumbers.format(windowTokens / 1000)}k` : "—", + })}
} + {cached !== undefined && !!input && <>
{t("thread.composer.context.cacheHitRate")}
{Math.round(cached / input * 100)}%
} + {duration !== undefined && <>
{t("thread.composer.context.duration")}
{formatTurnLatency(duration)}
} + {replay && <>
{t("thread.composer.context.history")}
+
{replay.index + 1}/{replay.frames.length}
} +
+
} +
+ { + 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 }); + }} /> +
+
; + return + {!expanded && content(false)} + + + {t("thread.composer.context.panelTitle")} + {content(true)} + + + ; +} diff --git a/webui/src/components/thread/ContextReplayButton.tsx b/webui/src/components/thread/ContextReplayButton.tsx new file mode 100644 index 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 ; +} diff --git a/webui/src/components/thread/PromptNavigator.tsx b/webui/src/components/thread/PromptNavigator.tsx index 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(null); const [listTop, setListTop] = useState(0); + const [highlighted, setHighlighted] = useState(0); + const inputRef = useRef(null); + const triggerRef = useRef(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 ( <> - - + { 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" > -
- + {t("thread.promptNavigator.title")} - -
+ +
- { 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" />
-
-
setListTop(event.currentTarget.scrollTop)} onKeyDown={(event) => { const button = (event.target as HTMLElement).closest("[data-prompt-row]"); @@ -125,6 +152,8 @@ export function PromptNavigator({ setHighlighted(firstRow + offset)} locale={i18n.resolvedLanguage || i18n.language} prompt={prompt} onJump={jump} @@ -137,8 +166,8 @@ export function PromptNavigator({
)}
-
-
+ + ); } @@ -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} > -
+
{prompt.preview}
{timestamp ? ( -
+
{timestamp}
) : null} diff --git a/webui/src/components/thread/SessionInfoPopover.tsx b/webui/src/components/thread/SessionInfoPopover.tsx index 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 ; } diff --git a/webui/src/components/thread/SessionInfoPopoverView.tsx b/webui/src/components/thread/SessionInfoPopoverView.tsx index 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, >
-
-
- {t("thread.sessionInfo.title")} -
-
- {title || t("thread.sessionInfo.untitled")} -
-
- -
+
{t("thread.sessionInfo.automations")} diff --git a/webui/src/components/thread/SubagentTasks.tsx b/webui/src/components/thread/SubagentTasks.tsx index 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} { if (!open) setSelectedId(null); }}> { event.preventDefault(); diff --git a/webui/src/components/thread/ThreadComposer.tsx b/webui/src/components/thread/ThreadComposer.tsx index 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(null); const tabFocusRequested = useRef(false); const [compactControls, setCompactControls] = useState(false); + const [usageTriggerHost, setUsageTriggerHost] = useState(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) ? ( - + const usageControl = !voiceRecorder.isRecording && (contextUsage || recentRoundUsage.length || contextSnapshots.length) ? ( + ) : 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 ? : null} @@ -2981,12 +2992,13 @@ export function ThreadComposer({
{usageInMeta && usageControl || mobileWorkspaceControls && accessControl ? (
- {usageInMeta ? usageControl : null} + {usageInMeta && usageControl ? : null} {mobileWorkspaceControls ? accessControl : null}
) : null}
) : null} + {usageControl} ); } diff --git a/webui/src/components/thread/ThreadMessages.tsx b/webui/src/components/thread/ThreadMessages.tsx index 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(); }}> - {label} + {label} {actions} diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx index 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[]): ComposerRo const seenTurns = new Set(); 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(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(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(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(null); const [conversationElement, setConversationElement] = useState(null); const composerSurfaceRef = useRef(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(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({
); const sessionInfoAction = historyKey ? ( - + ) : undefined; const promptNavigatorAction = historyKey ? ( 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")}> -
+
: null} activeTurnId={viewportTurnId} activeTurnStartedHere={activeTurnStartedHere} conversationKey={historyKey} @@ -1523,16 +1584,17 @@ export function ThreadShell({ {headerPortalTarget && headerActive ? createPortal(threadHeader, headerPortalTarget) : null} - {composerPortalTarget ? createPortal( + {createPortal( , - composerPortalTarget, - ) : null} + composerMount, + )} {activePreview && previewSessionKey ? ( }
- {columns.map((column, columnIndex) => (!compact || columnIndex === currentColumnIndex) && (!compact || columnIndex === currentColumnIndex) && { 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.ts new file mode 100644 index 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 } +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, + view: GraphCamera, palette: GraphPalette, highlighted: string | null, focused: string | null, + width: number, height: number, pixelRatio: number, discovered: ReadonlySet) { + context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); + context.clearRect(0, 0, width, height); + const groups = new Map(); + 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.ts new file mode 100644 index 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(); + const edges = new Map(); + let wanted = new Set(); + let wantedEdges = new Set(); + let related = new Set(); + 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.tsx index 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, React.ComponentPropsWithoutRef & { + contained?: boolean; positionerStyle?: React.CSSProperties; placement?: "center" | "bottom"; overlayClassName?: string; } ->(({ positionerStyle, placement, overlayClassName, ...props }, ref) => ( - -
(({ contained, positionerStyle, placement, overlayClassName, ...props }, ref) => { + const Overlay = contained ? "div" : DialogOverlay; + return +
- -)); +
; +}); DialogPositionedContent.displayName = "DialogPositionedContent"; interface DialogContentProps extends React.ComponentPropsWithoutRef { + portalContainer?: HTMLElement | null; showCloseButton?: boolean; overlayClassName?: string; layoutAnchor?: HTMLElement | null; @@ -71,10 +74,73 @@ interface DialogContentProps const DialogContent = React.forwardRef< React.ElementRef, 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(null); const contentNode = React.useRef(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(null); + const backdropFrame = React.useRef(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(); @@ -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 ( - + @@ -146,8 +222,45 @@ const DialogContent = React.forwardRef< {children} {showCloseButton ? ( - - + { + 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("[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" ? ) : null} diff --git a/webui/src/components/ui/floating-surface.ts b/webui/src/components/ui/floating-surface.ts index 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.tsx index 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 <> -
1 ? dragging ? "cursor-grabbing" : "cursor-grab" : "cursor-zoom-in", className)} +
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.tsx index 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 ( - + { + header?: ReactNode; + width: number; + isClosing?: boolean; + open?: boolean; + floating?: boolean; + contentClassName?: string; +} + +export const SidebarPanelActionsContext = createContext(null); + +/** Retain the same surface through exit, including an interrupted close. */ +export const SidebarPanel = forwardRef(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 ? : null; +}); + +/** Shared nonmodal side slot. Contents keep their final width while the slot opens. */ +const SidebarPanelContent = forwardRef(function SidebarPanelContent({ + width, isClosing = false, floating = false, header, contentClassName, className, style, children, ...props +}, forwardedRef) { + const panel = useRef(null); + const [entered, setEntered] = useState(false); + const [actionsHost, setActionsHost] = useState(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 ; +}); diff --git a/webui/src/components/workbench/PaneWorkbench.tsx b/webui/src/components/workbench/PaneWorkbench.tsx index 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()} > - - {t("workbench.layout", { defaultValue: "Pane layout" })} - - { @@ -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.tsx index c012eb2da..27b0b8bf7 100644 --- a/webui/src/dev/gallery/content.tsx +++ b/webui/src/dev/gallery/content.tsx @@ -65,7 +65,7 @@ function SessionPreview() { }}> { setMode(next); setJobs(exampleJobs(now)); setAction(null); }} /> - 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: '' }, { title: "previews.session.title", files: ["webui/src/components/thread/SessionInfoPopoverView.tsx"], Preview: SessionPreview, description: "previews.session.description", options: "previews.session.options", - code: '' }, + code: '' }, { title: "previews.subagent.title", files: ["webui/src/components/thread/SubagentThreadView.tsx"], Preview: SubagentPreview, description: "previews.subagent.description", options: "previews.subagent.options", code: '' }, diff --git a/webui/src/dev/gallery/conversation.tsx b/webui/src/dev/gallery/conversation.tsx index 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() {
; } +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
- + + rounds={rounds} snapshots={contextSnapshots} showLabel />

{t("previews.usage.hint")}

; } diff --git a/webui/src/dev/gallery/foundations.tsx b/webui/src/dev/gallery/foundations.tsx index 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
+ +
+ {open && {t("controls.sidebarPanel.title")}}> +

{t("controls.sidebarPanel.content")}

+
} +
+
; +} + export const foundationExamples: ComponentExample[] = [ + { title: "controls.sidebarPanel.title", files: ["sidebar-panel"], Preview: Sidebars, + description: "controls.sidebarPanel.description", options: "controls.sidebarPanel.options", + code: 'Details}>{children}' }, { 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.json index 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.json index 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.json index 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.json index 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.json index 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.json index 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.json index 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.json index 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.json index 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.json index 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.css index 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.json index 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.json index 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.json index 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.json index 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.json index 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.json index 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.json index 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.json index 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.json index 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.json index 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.ts index 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 = 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): WebuiThreadPersistedPay if (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(); + 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 = (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 = { ...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.ts new file mode 100644 index 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, width: number, height: number) { + const simulation = forceSimulation() + .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(width / 2).strength(CENTER_STRENGTH)) + .force("y", forceY(height / 2).strength(CENTER_STRENGTH)) + .force("link", forceLink().id((node) => node.path).distance(250 * GRAPH_SCALE)) + .force("charge", forceManyBody().strength(-Math.pow(10, 3) * GRAPH_SCALE ** 2)) + .force("collision", forceCollide().radius(60 * GRAPH_SCALE).strength(0.5)); + updateGraphSimulation(simulation, graph, previous, width, height); + return simulation; +} + +export function updateGraphSimulation(simulation: ReturnType>, graph: ContextGraph, + previous: ReadonlyMap, width: number, height: number) { + const existing = new Map(simulation.nodes().map((node) => [node.path, node])); + const placed = new Map(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(); + 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>>("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>>("collision")!.radius((node) => node.radius); + simulation.force>>("x")!.x(width / 2); + simulation.force>>("y")!.y(height / 2); +} + +/** Preserve the simulation steps while bounding work per animated frame. */ +export function advanceGraphSimulation(simulation: ReturnType, 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) { + 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.ts new file mode 100644 index 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; + 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; + 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; + 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, +): 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.ts index 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 & { 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.ts new file mode 100644 index 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; diff --git a/webui/src/lib/thread-event-projection.ts b/webui/src/lib/thread-event-projection.ts index 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.ts index 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 & InboundTurnMetadata) + | (Extract & 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.ts index 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(key: (value: T) => string) { + const values: T[] = []; + const identities = new Map(); + const keys = new Map(); + 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((node) => JSON.stringify([node.path, node.name, node.tokens, node.state])); + const edges = table((edge) => JSON.stringify([edge.source, edge.target])); + const references = new Map(); + const graphs: Record = {}; + 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 { @@ -32,7 +79,7 @@ export class WebuiThreadCache extends MemoryLruCache { 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) => ({ + event: "model_request", chat_id: "chat", request_id: id, run_id: "run", sequence: 2, + phase: "completed", ...fields, + }); + const payload = (events: unknown[], fields: Record = {}) => ({ 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.tsx index 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(); + 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(); let next = 0; diff --git a/webui/src/tests/composer-usage-popover.test.tsx b/webui/src/tests/composer-usage-popover.test.tsx index 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); -} +const first: ContextSnapshot = { id: "1", contextWindowTokens: 10000, usage: { prompt_tokens: 1000 }, + graph: { nodes: [{ path: "/a.md", name: "a.md", state: "loaded", tokens: 100 }], edges: [] } }; -async function openSheet() { - const user = userEvent.setup(); - render( - , - ); - 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 }; -} - -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(); + const content = (snapshots: ContextSnapshot[]) => <>