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

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

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

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

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

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

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

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

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

* fix(webui): remove redundant context sidebar header

* style(webui): clarify context replay icon

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

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

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

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

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

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

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

* fix(webui): animate context sidebar closing

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

No files matched your search

+2
View File
@@ -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
+10 -2
View File
@@ -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 ""
+7
View File
@@ -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)
+14
View File
@@ -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:
+5
View File
@@ -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,
+17 -10
View File
@@ -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"(?<![\w$])\$([A-Za-z0-9_-]+)")
@@ -166,7 +167,7 @@ class SkillsLoader:
with self.snapshot():
return self._load_skill(name)
def _load_skill(self, name: str) -> str | None:
def _load_skill(self, name: str, *, for_context: bool = False) -> str | None:
skills = self.list_skills(filter_unavailable=False)
available = {skill["name"] for skill in skills}
resolved = name if name in available else self._skill_aliases().get(name, name)
@@ -175,10 +176,14 @@ class SkillsLoader:
return 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}`")
+1
View File
@@ -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
+2
View File
@@ -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",
}
@@ -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"]
@@ -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": []}
+2 -1
View File
@@ -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,
)
+2 -1
View File
@@ -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,
+85
View File
@@ -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
+70
View File
@@ -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}
+1
View File
@@ -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)
+112
View File
@@ -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}
+18 -6
View File
@@ -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()
+250
View File
@@ -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
+29 -12
View File
@@ -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."""
+6 -4
View File
@@ -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",
)
+7 -2
View File
@@ -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
+2 -1
View File
@@ -26,6 +26,7 @@ UPDATE_RETRY_CAPABILITY = "webui.update-jobs.retry-handoff.v1"
UPDATE_SETTLE_HANDOFF_CAPABILITY = "webui.update-jobs.settle-handoff.v1"
UPDATE_FLOW_CAPABILITY = "webui.update-flow.v1"
UPDATE_CHANNEL_CAPABILITY = "webui.update-channels.v1"
CONTEXT_GRAPH_REFERENCES_CAPABILITY = "webui.context-graph.references.v1"
PROMPT_NAVIGATION_CAPABILITY = "webui.prompt-navigation.v1"
@@ -46,7 +47,7 @@ def webui_contract() -> dict[str, object]:
BINARY_ATTACHMENTS_CAPABILITY, UPDATE_PLAN_CAPABILITY,
UPDATE_JOB_CAPABILITY, UPDATE_PREPARATION_CAPABILITY, UPDATE_EXECUTION_CAPABILITY,
UPDATE_RETRY_CAPABILITY, UPDATE_SETTLE_HANDOFF_CAPABILITY, UPDATE_FLOW_CAPABILITY, UPDATE_CHANNEL_CAPABILITY,
PROMPT_NAVIGATION_CAPABILITY,
PROMPT_NAVIGATION_CAPABILITY, CONTEXT_GRAPH_REFERENCES_CAPABILITY,
],
}
+179
View File
@@ -0,0 +1,179 @@
"""Observe completed reads on the ordered display stream, outside agent execution."""
from __future__ import annotations
import asyncio
import re
from collections.abc import Mapping
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, cast
from loguru import logger
from nanobot.context_graph import ContextGraph, ContextNode, graph_from_sources
from nanobot.context_sources import PromptSource, SourceReceipt, parse_source_receipt
from nanobot.file_references import source_receipt
from nanobot.session.display_history import (
HISTORY_GENERATION_METADATA_KEY,
HistoryKind,
HistoryReader,
)
from nanobot.session.history_graph import decode_graph
from nanobot.session.manager import SessionManager
from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY
from nanobot.webui.session_identity import webui_session_key
def merge_graph(target: ContextGraph, incoming: ContextGraph, *, accumulate: bool = False) -> ContextGraph:
nodes: dict[str, ContextNode] = {node["path"]: node.copy() for node in target["nodes"]}
for node in incoming["nodes"]:
previous = nodes.get(node["path"])
if previous is None:
nodes[node["path"]] = node.copy()
elif node["state"] == "loaded":
previous["name"] = node["name"]
previous["state"] = "loaded"
previous["tokens"] = (previous["tokens"] + node["tokens"] if accumulate
else max(previous["tokens"], node["tokens"]))
edges = {(edge["source"], edge["target"]): edge for edge in target["edges"]}
edges.update({(edge["source"], edge["target"]): edge for edge in incoming["edges"]})
return {"nodes": list(nodes.values()), "edges": list(edges.values())}
def read_source(event: Mapping[str, Any]) -> SourceReceipt | None:
"""Use only the returned numbered text, never reread a source or link target."""
if event.get("name") != "read_file" or event.get("phase") != "end":
return None
arguments, result = event.get("arguments"), event.get("result")
if not isinstance(arguments, dict) or not isinstance(result, str):
return None
path = cast(dict[str, object], arguments).get("path")
if not isinstance(path, str) or not path:
return None
file = Path(path).expanduser()
if not file.is_absolute():
directory = event.get("working_directory")
if not isinstance(directory, str) or not Path(directory).is_absolute():
return None
file = Path(directory) / file
# ReadFileTool uses numbered lines even for a clipped first line. Its notices
# and unchanged-file response have no such prefix and must not count twice.
lines: list[str] = []
for line in result.splitlines():
match = re.match(r"^\d+\| ?(.*)$", line)
if match is None:
break
lines.append(match.group(1))
if not lines:
return None
return source_receipt(file, "\n".join(lines))
@dataclass
class _State:
graph: ContextGraph = field(default_factory=lambda: {"nodes": [], "edges": []})
calls: set[tuple[str | None, str]] = field(default_factory=set)
def apply(self, event: Mapping[str, Any], turn_id: str | None = None) -> None:
call_id = event.get("call_id")
source = parse_source_receipt(event.get("context_source"))
if not isinstance(call_id, str) or (turn_id, call_id) in self.calls or source is None:
return
self.graph = merge_graph(self.graph, graph_from_sources([source]), accumulate=True)
self.calls.add((turn_id, call_id))
def _restore(history: HistoryReader, generation: str | None) -> _State:
state = _State()
revision = history.revision
if revision is None or generation != revision[0]:
return state
pending: list[tuple[Mapping[str, Any], str | None]] = []
for turn in history.turns(reverse=True):
for _, fact in reversed(history.read_entries(turn.ordinal)):
boundary = fact.kind is HistoryKind.COMPACTION and fact.content.get("phase") == "succeeded"
graph = decode_graph(fact.content.get("context_graph")) if fact.kind is HistoryKind.MODEL_REQUEST else None
if boundary or graph is not None:
if graph is not None:
state.graph = graph
for event, turn_id in reversed(pending):
state.apply(event, turn_id)
return state
events = fact.content.get("tool_events")
if not isinstance(events, list):
continue
for event in reversed(cast(list[object], events)):
if isinstance(event, dict) and "context_source" in event:
pending.append((cast(dict[str, Any], event), fact.turn_id))
for event, turn_id in reversed(pending):
state.apply(event, turn_id)
return state
class ContextGraphObserver:
"""Display delivery serializes each chat; other chats have independent state."""
def __init__(self, sessions: SessionManager | None) -> None:
self._sessions = sessions
self._states: dict[tuple[str, str | None], _State] = {}
def discard(self, chat_id: str) -> None:
for key in tuple(self._states):
if key[0] == chat_id:
del self._states[key]
async def _state(self, chat_id: str, metadata: Mapping[str, Any], *, persistent: bool) -> _State:
raw_generation = metadata.get(HISTORY_GENERATION_METADATA_KEY)
generation = raw_generation if isinstance(raw_generation, str) else None
key = (chat_id, generation)
if key not in self._states:
self.discard(chat_id)
state = await self._sessions.state.project_history(
webui_session_key(chat_id), lambda history: _restore(history, generation),
) if persistent and self._sessions is not None else _State()
self._states[key] = state
return self._states[key]
async def observe_tools(
self, chat_id: str, events: list[dict[str, Any]], metadata: Mapping[str, Any], *, persistent: bool,
) -> None:
for event in events:
if event.get("name") != "read_file" or event.get("phase") != "end":
continue
try:
source = await asyncio.to_thread(read_source, event)
if source is not None:
state = await self._state(chat_id, metadata, persistent=persistent)
event["context_source"] = source
turn_id = metadata.get(WEBUI_TURN_METADATA_KEY)
state.apply(event, turn_id if isinstance(turn_id, str) else None)
except Exception:
# A presentation parser failure must not lose the tool result.
logger.exception("Unable to observe file read for context graph")
async def observe_prompt(
self, chat_id: str, sources: tuple[PromptSource, ...], metadata: Mapping[str, Any], *, persistent: bool,
) -> None:
if not sources:
return
def project() -> ContextGraph:
receipts = [source_receipt(source.path, source.content, loaded=source.loaded) for source in sources]
return graph_from_sources(receipts)
try:
graph = await asyncio.to_thread(project)
state = await self._state(chat_id, metadata, persistent=persistent)
state.graph = merge_graph(state.graph, graph)
except Exception:
logger.exception("Unable to observe prompt sources for context graph")
async def snapshot(
self, chat_id: str, metadata: Mapping[str, Any], *, persistent: bool,
) -> ContextGraph:
state = await self._state(chat_id, metadata, persistent=persistent)
return state.graph
async def reset(self, chat_id: str, metadata: Mapping[str, Any], *, persistent: bool) -> None:
state = await self._state(chat_id, metadata, persistent=persistent)
state.graph = {"nodes": [], "edges": []}
state.calls.clear()
+32
View File
@@ -0,0 +1,32 @@
"""Turn-scoped prompt observation installed by WebUI runtime composition."""
from __future__ import annotations
from nanobot.agent.hook import AgentHook, AgentRunHookContext, AgentTurnHookContext
from nanobot.context_sources import PromptSourcesEvent, capture_sources
from nanobot.events import EventSink
class ContextSourceHook(AgentHook):
def __init__(self, events: EventSink) -> None:
super().__init__()
self._events = events
self._capture = capture_sources()
self._sources = self._capture.__enter__()
def has_run_hooks(self) -> bool:
# Cleanup owns no transcript; avoid copying all messages for this observer.
return False
async def before_model_request(self) -> None:
sources = tuple(self._sources)
self._sources.clear()
if sources:
await self._events.emit(PromptSourcesEvent(sources))
async def on_finally(self, context: AgentRunHookContext) -> None:
self._sources.clear()
self._capture.__exit__(None, None, None)
def create_context_source_hook(context: AgentTurnHookContext) -> AgentHook | None:
return ContextSourceHook(context.events) if context.events.accepts(PromptSourcesEvent) else None
+5 -4
View File
@@ -5,6 +5,7 @@ from typing import Any
from nanobot.bus.events import INBOUND_META_LOCAL_MEDIA
from nanobot.session.display_history import HistoryFact, HistoryKind, HistoryReader
from nanobot.session.history_graph import expand_graph_fields
from nanobot.webui.session_identity import webui_chat_id
_EVENTS = {
@@ -31,7 +32,7 @@ _CONTENT_FIELDS = frozenset({
"merge_next", "latency_ms", "usage", "round_usages", "context_window_tokens", "goal_state",
"outcome", "failure_kind", "failure_error_kind", "failure_attempts", "failure_message",
"transcript_incomplete", "stream_id", "compaction_id", "phase", "reason", "render_as",
"request_id", "run_id", "sequence",
"request_usage", "request_id", "run_id", "sequence", "context_graph", "context_snapshot",
})
@@ -63,14 +64,14 @@ def fact_from_record(record: Mapping[str, Any]) -> HistoryFact:
return fact
def record_from_fact(fact: HistoryFact, key: str) -> dict[str, Any]:
def record_from_fact(fact: HistoryFact, key: str, *, expand_graphs: bool = True) -> dict[str, Any]:
if fact.kind in _MESSAGE_KINDS.values():
event = "message"
message_kind = next(name for name, kind in _MESSAGE_KINDS.items() if kind is fact.kind)
else:
event = next(name for name, kind in _EVENTS.items() if kind is fact.kind)
message_kind = None
record = {"event": event, "chat_id": webui_chat_id(key), **fact.content,
record = {"event": event, "chat_id": webui_chat_id(key), **(expand_graph_fields(fact.content) if expand_graphs else fact.content),
"created_at_ms": fact.created_at_ms}
if message_kind:
record["kind"] = message_kind
@@ -86,6 +87,6 @@ def record_from_fact(fact: HistoryFact, key: str) -> dict[str, Any]:
def turn_records(
history: HistoryReader, ordinal: int, *, max_records: int | None = None, max_bytes: int | None = None,
) -> list[dict[str, Any]]:
return [{**record_from_fact(fact, history.key),
return [{**record_from_fact(fact, history.key, expand_graphs=False),
"_webui_replay_identity": f"turn:{ordinal}:record:{position}"}
for position, fact in history.read_entries(ordinal, max_records=max_records, max_bytes=max_bytes)]
+54 -9
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import asyncio
import json
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
@@ -24,6 +25,8 @@ from nanobot.bus.outbound_events import (
)
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import SubagentTaskChanged
from nanobot.context_graph import ContextGraph
from nanobot.context_sources import PromptSourcesEvent
from nanobot.events import ModelRequestEvent
from nanobot.pairing.events import PairingChanged
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
@@ -32,6 +35,7 @@ from nanobot.session.webui_turns import (
mark_websocket_turn_transcript_persistence_failed,
websocket_turn_transcript_persistence_failed,
)
from nanobot.webui.context_observer import ContextGraphObserver
from nanobot.webui.media_gateway import WebUIMediaGateway
from nanobot.webui.metadata import (
WEBSOCKET_TURN_OWNER_METADATA_KEY,
@@ -44,6 +48,7 @@ from nanobot.webui.outbound_wire import (
GoalStateWirePayload,
GoalStatusWirePayload,
MessageWirePayload,
NotificationProjection,
RuntimeModelWirePayload,
SessionUpdatedWirePayload,
StreamWirePayload,
@@ -73,6 +78,12 @@ WebUIAudience: TypeAlias = ChatAudience | Literal["all_connections", "authentica
_ACTIVITY_BATCH_BYTES = 128 * 1024
async def _encode_payload(payload: Mapping[str, object]) -> str:
if "context_graph" in payload or "context_snapshot" in payload:
return await asyncio.to_thread(json.dumps, payload, ensure_ascii=False)
return json.dumps(payload, ensure_ascii=False)
class WebUIOutboundTransport(Protocol):
"""Snapshot recipients and enqueue already projected public JSON frames."""
@@ -100,17 +111,39 @@ class WebUIOutboundDelivery:
self._transcripts = transcripts
self._temporary_chats = temporary_chats
self._session_projection = session_projection
self._context_graph = ContextGraphObserver(transcripts.sessions)
self._stream_text_buffers: dict[tuple[str, str], list[str]] = {}
self._reasoning_text_buffers: dict[tuple[str, str], list[str]] = {}
async def _project_notification(self, msg: OutboundMessage) -> NotificationProjection | None:
event = msg.event
if not isinstance(event, ModelRequestEvent | ContextCompactionEvent):
return project_notification(msg.chat_id, event, msg.metadata)
persistent = self._temporary_chats.should_persist_transcript(msg.chat_id)
if isinstance(event, ModelRequestEvent):
graph: ContextGraph = {"nodes": [], "edges": []}
try:
graph = await self._context_graph.snapshot(msg.chat_id, msg.metadata, persistent=persistent)
except Exception:
logger.exception("Unable to restore context graph")
return project_notification(msg.chat_id, event, msg.metadata, context_graph=graph)
if event.phase == "succeeded":
try:
await self._context_graph.reset(msg.chat_id, msg.metadata, persistent=persistent)
except Exception:
logger.exception("Unable to reset context graph")
return project_notification(msg.chat_id, event, msg.metadata)
def bind_pairing(self, bus: MessageBus, *, channel: str) -> Callable[[], None]:
async def queue_changed(event: PairingChanged) -> None:
await bus.publish_event(event, channel=channel, chat_id="*")
return bus.subscribe(queue_changed, PairingChanged)
def discard(self, chat_id: str) -> None:
def discard(self, chat_id: str, *, complete: bool = False) -> None:
"""Forget unclosed streams when a turn ends or its chat is discarded."""
if not complete or self._temporary_chats.should_persist_transcript(chat_id):
self._context_graph.discard(chat_id)
for buffers in (self._stream_text_buffers, self._reasoning_text_buffers):
for key in tuple(buffers):
if key[0] == chat_id:
@@ -134,7 +167,9 @@ class WebUIOutboundDelivery:
*,
label: str,
) -> None:
raw = json.dumps(payload, ensure_ascii=False)
if not recipients:
return
raw = await _encode_payload(payload)
for connection in recipients:
await self._transport.webui_send_raw(connection, raw, label=label)
@@ -182,10 +217,10 @@ class WebUIOutboundDelivery:
for msg in messages:
progress = msg.event if isinstance(msg.event, ProgressEvent) else None
if progress is not None:
body = self._message_payload(msg, progress)
body = await self._message_payload(msg, progress)
persistent, label = True, " "
else:
notification = project_notification(msg.chat_id, msg.event, msg.metadata)
notification = await self._project_notification(msg)
assert notification is not None
body = dict(notification.payload)
persistent = notification.persistence == "turn_activity"
@@ -195,7 +230,7 @@ class WebUIOutboundDelivery:
msg.chat_id, body, metadata=msg.metadata, phase="activity", include_source=progress is not None,
)
try:
raw = json.dumps(body, ensure_ascii=False)
raw = await _encode_payload(body)
size = len(raw.encode("utf-8"))
except (TypeError, ValueError, RecursionError) as exc:
logger.warning("WebUI activity encoding failed for {}: {}", msg.chat_id, exc)
@@ -212,6 +247,12 @@ class WebUIOutboundDelivery:
async def send(self, msg: OutboundMessage) -> None:
event = msg.event
if isinstance(event, PromptSourcesEvent):
await self._context_graph.observe_prompt(
msg.chat_id, event.sources, msg.metadata,
persistent=self._temporary_chats.should_persist_transcript(msg.chat_id),
)
return
if isinstance(event, PairingChanged):
await self._fanout(
self._transport.webui_recipients("authenticated_webui"),
@@ -248,7 +289,7 @@ class WebUIOutboundDelivery:
body["provenance"] = event.provenance
await self._fanout(recipients, body, label=" user_message ")
return
notification = project_notification(msg.chat_id, event, msg.metadata)
notification = await self._project_notification(msg)
if notification is not None:
if recipients or notification.deliver_offline:
await self._send_payload(
@@ -373,7 +414,7 @@ class WebUIOutboundDelivery:
chat_id, persisted=persisted, metadata=metadata, phase=phase,
)
def _message_payload(self, msg: OutboundMessage, progress: ProgressEvent | None) -> dict[str, Any]:
async def _message_payload(self, msg: OutboundMessage, progress: ProgressEvent | None) -> dict[str, Any]:
text = msg.content
user_shell = msg.metadata.get(INBOUND_META_USER_SHELL) is True
payload: MessageWirePayload = {
@@ -401,6 +442,10 @@ class WebUIOutboundDelivery:
payload["latency_ms"] = int(latency)
if progress and progress.tool_events:
payload["tool_events"] = project_tool_events(progress.tool_events)
await self._context_graph.observe_tools(
msg.chat_id, payload["tool_events"], msg.metadata,
persistent=self._temporary_chats.should_persist_transcript(msg.chat_id),
)
agent_ui = msg.metadata.get(OUTBOUND_META_AGENT_UI)
if agent_ui is not None:
payload["agent_ui"] = agent_ui
@@ -410,7 +455,7 @@ class WebUIOutboundDelivery:
async def _send_message(self, msg: OutboundMessage, progress: ProgressEvent | None) -> None:
recipients = self._transport.webui_recipients(ChatAudience(msg.chat_id))
body = self._message_payload(msg, progress)
body = await self._message_payload(msg, progress)
await self._persist_turn_transcript_event(
msg.chat_id, body, metadata=msg.metadata,
phase="activity" if progress else "answer", include_source=True,
@@ -528,7 +573,7 @@ class WebUIOutboundDelivery:
if persisted:
# A durable incomplete marker allows HTTP recovery after restart.
clear_websocket_turn_if_current(chat_id, turn_owner)
self.discard(chat_id)
self.discard(chat_id, complete=True)
await self._fanout(recipients, body, label=f" {body['event']} ")
async def _send_goal_state(self, chat_id: str, blob: dict[str, Any]) -> None:
+8
View File
@@ -11,6 +11,7 @@ from nanobot.bus.outbound_events import (
RetryStatusEvent,
TurnEndEvent,
)
from nanobot.context_graph import ContextGraph, ContextSnapshot
from nanobot.events import AgentEvent, CompactionReason, ModelRequestEvent
from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY
@@ -97,6 +98,8 @@ class TurnEndWirePayload(_ChatWirePayload):
class ModelRequestWirePayload(_ChatWirePayload):
request_usage: dict[str, int] | None
context_graph: NotRequired[ContextGraph]
event: Literal["model_request"]
request_id: str
run_id: str
@@ -108,6 +111,7 @@ class ModelRequestWirePayload(_ChatWirePayload):
class ContextCompactionWirePayload(_ChatWirePayload):
context_snapshot: NotRequired[ContextSnapshot]
event: Literal["context_compaction"]
compaction_id: str
phase: Literal["started", "succeeded", "failed", "cancelled"]
@@ -253,6 +257,7 @@ class NotificationProjection:
def project_notification(
chat_id: str, event: AgentEvent | None, metadata: Mapping[str, object] | None = None,
*, context_graph: ContextGraph | None = None,
) -> NotificationProjection | None:
"""Keep notification serialization and persistence decisions at one boundary."""
if isinstance(event, ModelRequestEvent):
@@ -260,7 +265,10 @@ def project_notification(
"event": "model_request", "chat_id": chat_id,
"request_id": event.request_id, "run_id": event.run_id,
"sequence": event.sequence, "phase": event.phase,
"request_usage": event.request_usage.to_turn_dict() if event.request_usage is not None else None,
}
if context_graph is not None:
payload["context_graph"] = context_graph
if event.usage is not None:
payload["usage"] = event.usage.to_turn_dict()
payload["round_usages"] = [usage.to_turn_dict() for usage in event.round_usages[-8:]]
+20 -6
View File
@@ -28,6 +28,12 @@ from nanobot.session.display_history import (
HistoryFact,
HistoryReader,
)
from nanobot.session.history_graph import (
decode_graph,
decode_snapshot,
graph_decoding,
graph_size_adjustment,
)
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import Session, SessionManager
from nanobot.session.sqlite_store import SessionConflictError
@@ -233,7 +239,7 @@ def _record_json_line(record: dict[str, Any]) -> str:
def _records_bytes(records: list[dict[str, Any]]) -> int:
total = 0
for record in records:
total += len(_record_json_line(record).encode("utf-8")) + 1
total += len(_record_json_line(record).encode("utf-8")) + graph_size_adjustment(record) + 1
return total
@@ -581,9 +587,6 @@ class WebUITranscriptRecorder:
for event in events:
try:
fact = fact_from_record(_record_for_append(event))
if len(events) > 1:
# An invalid member must not roll back otherwise valid activity.
fact.encode()
facts.append(fact)
except (ValueError, TypeError) as exc:
self._log.warning("history append failed for {}: {}", chat_id, exc)
@@ -591,8 +594,12 @@ class WebUITranscriptRecorder:
if not facts:
return False
try:
await self.sessions.state.append_history(webui_session_key(chat_id), facts,
expected_generation=generation)
errors = await self.sessions.state.append_history(webui_session_key(chat_id), facts,
expected_generation=generation,
skip_invalid=len(events) > 1)
for error in errors:
self._log.warning("history append failed for {}: {}", chat_id, error)
valid = valid and not errors
except (OSError, ValueError, TypeError, sqlite3.Error, SessionConflictError, SessionOperationQueueFullError) as exc:
self._log.warning("history append failed for {}: {}", chat_id, exc)
return False
@@ -1510,6 +1517,8 @@ def _client_projection_event(
"compaction_id": compaction_id,
"phase": phase,
}
if (snapshot := decode_snapshot(record.get("context_snapshot"))) is not None:
projected["context_snapshot"] = snapshot
reason = record.get("reason")
if isinstance(reason, str) and reason in {"idle", "context_pressure", "manual", "provider_native"}:
projected["reason"] = reason
@@ -1528,6 +1537,10 @@ def _client_projection_event(
):
return None
projected.update(request_id=request_id, run_id=run_id, sequence=sequence, phase=phase)
if "request_usage" in record:
projected["request_usage"] = _sanitize_turn_usage(record["request_usage"]) or None
if (graph := decode_graph(record.get("context_graph"))) is not None:
projected["context_graph"] = graph
latency_ms = record.get("latency_ms")
if isinstance(latency_ms, int | float) and latency_ms >= 0:
projected["latency_ms"] = int(latency_ms)
@@ -1757,6 +1770,7 @@ def build_session_thread_response(
"active_turn_id": turn_id if active else None}
@graph_decoding()
def build_webui_thread_response(
session_key: str,
*,
+71 -13
View File
@@ -18,7 +18,7 @@ import time
from collections.abc import Awaitable, Callable, Mapping
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Any, Protocol, cast
from typing import TYPE_CHECKING, Any, Protocol, TypeVar, cast
from urllib.parse import quote, unquote, urlsplit, urlunsplit
from loguru import logger
@@ -29,6 +29,7 @@ from websockets.http11 import Response
from nanobot.agent.subagent import SubagentControlError
from nanobot.agent.subagent_status import SubagentSessionError
from nanobot.command.application import builtin_command_palette
from nanobot.context_graph import ContextGraph
from nanobot.cron.binding import CronBindingError, binding_revision
from nanobot.cron.session_turns import is_bound_cron_job
from nanobot.cron.types import CronJob, CronSchedule
@@ -348,8 +349,58 @@ def _resolve_bootstrap_model_name(
return _default_model_name_from_config(config_path) or ""
class _HistoryProjection(Protocol):
def __call__(self, request: WsRequest, key: str, *, history: HistoryReader) -> Response: ...
_ProjectionResult = TypeVar("_ProjectionResult", covariant=True)
class _HistoryProjection(Protocol[_ProjectionResult]):
def __call__(self, request: WsRequest, key: str, *, history: HistoryReader) -> _ProjectionResult: ...
@dataclass
class _PreparedThreadResponse:
data: dict[str, Any]
headers: list[tuple[str, str]]
def _encode_thread_response(data: dict[str, Any], *, graph_references: bool, **kwargs: Any) -> Response:
if graph_references:
graphs: dict[str, object] = {}
references: dict[int, tuple[str, ContextGraph]] = {}
nodes: list[object] = []
edges: list[object] = []
node_ids: dict[int, int] = {}
edge_ids: dict[int, int] = {}
def index(value: object, values: list[object], ids: dict[int, int]) -> int:
identity = id(value)
if identity not in ids:
ids[identity] = len(values)
values.append(value)
return ids[identity]
def reference(graph: ContextGraph) -> str:
identity = id(graph)
if identity not in references:
key = str(len(graphs))
references[identity] = (key, graph)
graphs[key] = {
"nodes": [index(node, nodes, node_ids) for node in graph["nodes"]],
"edges": [index(edge, edges, edge_ids) for edge in graph["edges"]],
}
return references[identity][0]
for event in data.get("events", []):
if "context_graph" in event:
event["context_graph_ref"] = reference(event.pop("context_graph"))
snapshot = event.get("context_snapshot")
if isinstance(snapshot, dict) and "graph" in snapshot:
snapshot = cast(dict[str, Any], snapshot)
event["context_snapshot"] = {**snapshot, "graph_ref": reference(snapshot["graph"])}
event["context_snapshot"].pop("graph")
data["context_graphs"] = graphs
data["context_graph_nodes"] = nodes
data["context_graph_edges"] = edges
return _http_json_response(data, **kwargs)
class GatewayHTTPHandler:
@@ -1048,8 +1099,8 @@ class GatewayHTTPHandler:
return self.session_manager.read_session_version(key) if self.session_manager is not None else None
async def _project_session_history(
self, request: WsRequest, key: str, project: _HistoryProjection,
) -> Response:
self, request: WsRequest, key: str, project: _HistoryProjection[_ProjectionResult],
) -> _ProjectionResult | Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
decoded = _decode_api_key(key)
@@ -1111,11 +1162,20 @@ class GatewayHTTPHandler:
timer = loop.call_later(0.05, sample_event_loop_lag)
started = time.perf_counter()
def project(request: WsRequest, key: str, *, history: HistoryReader) -> Response:
def project(request: WsRequest, key: str, *, history: HistoryReader) -> Response | _PreparedThreadResponse:
return self._handle_webui_thread_get(request, key, history=history, diagnostics=diagnostics)
try:
response = await self._project_session_history(request, key, project)
prepared = await self._project_session_history(request, key, project)
if isinstance(prepared, _PreparedThreadResponse):
response = await asyncio.to_thread(
_encode_thread_response, prepared.data,
graph_references=_query_first(_parse_query(request.path), "context_graph_encoding") == "references-v1",
accept_encoding=_combined_list_header(request.headers, "Accept-Encoding"),
extra_headers=prepared.headers, metrics=diagnostics.response,
)
else:
response = prepared
finally:
active = False
timer.cancel()
@@ -1170,7 +1230,7 @@ class GatewayHTTPHandler:
*,
history: HistoryReader,
diagnostics: _WebUIThreadDiagnostics | None = None,
) -> Response:
) -> Response | _PreparedThreadResponse:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
decoded_key = _decode_api_key(key)
@@ -1215,6 +1275,7 @@ class GatewayHTTPHandler:
include_model_requests = _query_first(query, "include_model_requests") == "1"
revision_variant = {
"include_model_requests": include_model_requests,
"context_graph_encoding": _query_first(query, "context_graph_encoding"),
"active_turn_id": active_turn_id,
"active_turn_started_at": active_turn_started_at,
"active_turn_transcript_persistence_failed": (
@@ -1267,11 +1328,8 @@ class GatewayHTTPHandler:
if final_revision is not None and final_revision == initial_revision:
response_headers.append(("ETag", _quoted_etag(final_revision)))
data["revision"] = final_revision
return _http_json_response(
data,
accept_encoding=_combined_list_header(request.headers, "Accept-Encoding"),
extra_headers=response_headers,
metrics=diagnostics.response if diagnostics is not None else None,
return _PreparedThreadResponse(
data=data, headers=response_headers,
)
def _handle_webui_trace_detail_get(self, request: WsRequest, key: str, *, history: HistoryReader) -> Response:
+1
View File
@@ -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",
+59
View File
@@ -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"]]
+54
View File
@@ -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"]
+4 -1
View File
@@ -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)
+22
View File
@@ -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
+2 -4
View File
@@ -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"]
+173
View File
@@ -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()
+259
View File
@@ -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")}]
+3 -1
View File
@@ -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"
+166
View File
@@ -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),
])
+39
View File
@@ -0,0 +1,39 @@
import { useState } from "react";
import { createRoot } from "react-dom/client";
import { ContextInspector } from "@/components/thread/ContextInspector";
import { ComposerUsagePopover } from "@/components/thread/ComposerUsagePopover";
import { TooltipProvider } from "@/components/ui/tooltip";
import { initializeI18n } from "@/i18n";
import type { ContextSnapshot } from "@/lib/types";
import "../src/globals.css";
const snapshots: ContextSnapshot[] = [
{ id: "first", contextWindowTokens: 10000, usage: { prompt_tokens: 1000 }, graph: {
nodes: [{ path: "/a.md", name: "a.md", state: "loaded", tokens: 100 }], edges: [],
} },
{ id: "second", contextWindowTokens: 10000, usage: { prompt_tokens: 2000 }, graph: {
nodes: [{ path: "/a.md", name: "a.md", state: "loaded", tokens: 100 }, { path: "/b.md", name: "b.md", state: "discovered", tokens: 0 }],
edges: [{ source: "/a.md", target: "/b.md" }],
} },
];
const largeNodes = Array.from({ length: 500 }, (_, index) => ({ path: `/file-${index}.md`, name: `file-${index}.md`, state: "loaded" as const, tokens: 100 }));
const large: ContextSnapshot[] = [{ id: "large", contextWindowTokens: 100000, usage: { prompt_tokens: 50000 }, graph: {
nodes: largeNodes, edges: largeNodes.slice(1).map((node, index) => ({ source: largeNodes[Math.floor(index / 2)].path, target: node.path })),
} }];
function Fixture() {
const [showLarge, setShowLarge] = useState(false);
const [pythonLoaded, setPythonLoaded] = useState(false);
const frames = new URLSearchParams(location.search).has("single") ? snapshots.map((snapshot) => ({ ...snapshot, graph: snapshots[0].graph })) : snapshots;
const inspectedFrames = pythonLoaded ? [...frames, { ...frames[1], id: "python", graph: {
nodes: [...frames[1].graph.nodes, { path: "/worker.py", name: "worker.py", state: "loaded" as const, tokens: 200 }], edges: frames[1].graph.edges,
} }] : frames;
const [opened, setOpened] = useState("");
const [sidebarHost, setSidebarHost] = useState<HTMLElement | null>(null);
if (new URLSearchParams(location.search).has("drawer")) return <main ref={setSidebarHost} className="relative" style={{ height: "100dvh" }}>
<ComposerUsagePopover sidebarHost={sidebarHost} context={null} rounds={[]} snapshots={frames} onOpenFile={setOpened} />
<output>{opened}</output>
</main>;
return <main className="mx-auto max-w-2xl p-4"><ContextInspector context={null} rounds={[]} snapshots={showLarge ? large : inspectedFrames} onOpenFile={setOpened} /><output>{opened}</output>{new URLSearchParams(location.search).has("pair") && <section aria-label="Second graph"><ContextInspector context={null} rounds={[]} snapshots={frames} /></section>}<button onClick={() => setShowLarge(true)}>Load 500 nodes</button><button onClick={() => setPythonLoaded(true)}>Read Python file</button></main>;
}
await initializeI18n();
createRoot(document.getElementById("root")!).render(<TooltipProvider><Fixture /></TooltipProvider>);
+1
View File
@@ -0,0 +1 @@
<!doctype html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width,initial-scale=1" /><title>Context graph interaction</title></head><body><div id="root"></div><script type="module" src="/browser/context-graph-fixture.tsx"></script></body></html>
+205
View File
@@ -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);
});
+29 -29
View File
@@ -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",
]);
});
+1 -1
View File
@@ -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();
+3 -3
View File
@@ -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();
+1 -1
View File
@@ -137,7 +137,7 @@ function SkeletonSurface() {
: surface === "automations" ? <AutomationsSettings payload={empty ? null : { jobs }} loading={loading} filter="all" actionKey={null} error={state === "error" ? "Preview read failed" : null}
onFilterChange={noop} onAction={noop} onRequestEdit={noop} onRequestDelete={noop} />
: surface === "skill-detail" ? <SkillsCatalogSettings skills={[skill]} />
: surface === "session-jobs" ? <SessionInfoPopoverView title="Project review" jobs={empty ? [] : jobs} loading={loading} loadFailed={state === "error"} now={now}
: surface === "session-jobs" ? <SessionInfoPopoverView jobs={empty ? [] : jobs} loading={loading} loadFailed={state === "error"} now={now}
onAction={async () => jobs} onEdit={async () => jobs} />
: surface === "linear-members" ? <LinearMemberAccessView snapshot={{ payload: empty ? null : members, loading, error: state === "error" ? "Preview read failed" : null, saves: {} }} onLoad={noop} onSetAllowed={noop} /> : null}
</main>}
+2 -2
View File
@@ -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();
+1 -1
View File
@@ -62,7 +62,7 @@ function ThemeChatFixture({ theme, toggle }: { theme: "light" | "dark"; toggle:
<ThreadViewport messages={messages} isStreaming={false} conversationKey={activeKey}
navigationFrame={context.navigationFrame} composer={null} />
<ThreadHistoryStatus loading={false} error={null} exhausted onRetry={noop} />
{context.composerPortalTarget && createPortal(composer, context.composerPortalTarget)}
{context.composerPortalTarget && createPortal(<div data-active-composer>{composer}</div>, context.composerPortalTarget)}
</div>} />
</div>
</main>;
+10 -1
View File
@@ -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")!;
+12
View File
@@ -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=="],
+50
View File
@@ -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",
+2
View File
@@ -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",
+3 -3
View File
@@ -59,7 +59,7 @@ const LazyHighlightedCode = lazy(async () => {
customStyle={{
background: "transparent",
margin: 0,
padding: chrome === "none" ? "0.75rem 1rem" : "1rem 3.5rem 1rem 1.25rem",
padding: viewportHighlight ? "0.75rem 1rem 0.75rem 0.5rem" : chrome === "none" ? "0.75rem 1rem" : "1rem 3.5rem 1rem 1.25rem",
fontFamily: "inherit",
fontSize: "inherit",
lineHeight: "inherit",
@@ -134,7 +134,7 @@ function CodeTextBlock({
showLineNumbers ? "whitespace-pre" : "whitespace-pre-wrap",
chrome === "default"
? "py-4 pl-5 pr-14"
: compact ? "px-4 py-3" : "p-3",
: compact ? "py-3 pl-2 pr-4" : "p-3",
className,
)}
data-testid={testId}
@@ -143,7 +143,7 @@ function CodeTextBlock({
{showLineNumbers && compact ? (
<span className="flex min-w-max">
<span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground"
style={{ minWidth: "4.25em" }}>{lines.map((_, index) => index + 1).join("\n")}</span>
style={{ minWidth: `calc(${String(lines.length).length}ch + 1.15rem)` }}>{lines.map((_, index) => index + 1).join("\n")}</span>
<span>{renderText(code)}</span>
</span>
) : showLineNumbers ? (
+20 -16
View File
@@ -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 = <button type="button" onClick={() => setMode(value => value === "preview" ? "source" : "preview")}
className="touch-target inline-flex h-8 items-center justify-center rounded-control px-3 text-xs text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
{modeLabel}
</button>;
return (
<section aria-label={t("filePreview.aria")} data-testid="file-preview-panel" className="flex min-h-0 flex-1 flex-col">
{markdown ? (
<div className="flex shrink-0 items-center justify-end px-4 py-2">
<SegmentedControl value={mode} onChange={setMode} ariaLabel={t("filePreview.displayMode")}
options={[{ value: "preview", label: t("filePreview.preview") }, { value: "source", label: t("filePreview.source") }]}
itemClassName="px-3 [@media(pointer:coarse)]:min-h-9" />
</div>
) : null}
{markdown && (actionsHost ? createPortal(modeControl, actionsHost) : <div className="flex shrink-0 justify-end px-4 py-2">{modeControl}</div>)}
<div key={mode} data-file-preview-scroll tabIndex={0}
className="min-h-0 flex-1 overflow-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/60">
{...surfaceFocusProps}
className="min-h-0 flex-1 overflow-auto outline-none data-[keyboard-focus]:ring-2 data-[keyboard-focus]:ring-inset data-[keyboard-focus]:ring-ring/60">
{state.status === "loading" ? (
<div role="status" aria-label={t("filePreview.loading", { defaultValue: "Loading preview..." })}
className="h-full" aria-busy="true">
@@ -57,9 +61,9 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange
{previewKind === "image" ? <div className="flex h-full items-center justify-center p-4">
<div className="aspect-[8/5] w-full max-w-sm rounded-compact bg-muted/40" />
</div> : <>
{previewKind === "markdown" ? <div className="flex justify-end px-4 py-2">
<div className="inline-flex min-h-8 items-center gap-1 rounded-full bg-muted/40 p-1 text-ui-label">
{[t("filePreview.preview"), t("filePreview.source")].map((label) => <span key={label} className="invisible px-3 py-1 [@media(pointer:coarse)]:min-h-9">{label}</span>)}
{previewKind === "markdown" && !actionsHost ? <div className="flex justify-end px-4 py-2">
<div className="touch-target inline-flex h-8 items-center rounded-control bg-muted/40 px-3 text-xs">
<span className="invisible">{modeLabel}</span>
</div>
</div> : null}
{previewKind === "markdown" && mode === "preview" ? <div className="markdown-content px-5 pb-6 pt-1 sm:px-6">
@@ -67,10 +71,10 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange
{["w-full", "w-5/6", "w-3/4"].map((width) => <div key={width} className="mt-4 flex h-[1lh] items-center">
<div className={`h-3 rounded bg-muted/40 ${width}`} />
</div>)}
</div> : <div className="px-4 py-3 font-mono text-code">
</div> : <div className="py-3 pl-2 pr-4 font-mono text-code">
{["w-2/3", "w-full", "w-5/6", "w-3/4", "w-1/2", "w-3/5"].map((width) => <div key={width} className="flex h-[1lh] items-center">
<div className="w-[4.25em] shrink-0 pr-[1.15rem]"><div className="ml-auto h-3 w-2 rounded bg-muted/40" /></div>
<div className={`h-3 max-w-[calc(100%-4.25em)] rounded bg-muted/40 ${width}`} />
<div className="w-[calc(1ch+1.15rem)] shrink-0 pr-[1.15rem]"><div className="ml-auto h-3 w-2 rounded bg-muted/40" /></div>
<div className={`h-3 max-w-[calc(100%-1ch-1.15rem)] rounded bg-muted/40 ${width}`} />
</div>)}
</div>}
</>}
@@ -1,3 +1,4 @@
import { surfaceFocusProps } from "@/lib/surface-focus";
import {
Children,
isValidElement,
@@ -686,7 +687,7 @@ export default function MarkdownTextRenderer({
void _node;
return (
<div
data-testid="markdown-data-table"
data-testid="markdown-data-table" {...surfaceFocusProps}
data-table-kind="data"
role="region"
tabIndex={0}
@@ -694,7 +695,7 @@ export default function MarkdownTextRenderer({
className={cn(
"not-prose mb-5 mt-3 w-full max-w-full overflow-x-auto rounded-lg",
"border border-border/65 bg-muted/20",
"overscroll-x-contain focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
"overscroll-x-contain outline-none data-[keyboard-focus]:ring-2 data-[keyboard-focus]:ring-ring",
)}
>
<table
@@ -703,9 +704,9 @@ export default function MarkdownTextRenderer({
"[&_thead]:bg-muted/45 [&_thead]:text-muted-foreground",
"[&_th]:border-b [&_th]:border-border/65 [&_th]:px-3 [&_th]:py-2",
"[&_th]:text-left [&_th]:font-medium [&_th]:whitespace-normal",
"[&_th]:[overflow-wrap:anywhere]",
"[&_th]:[overflow-wrap:normal]",
"[&_td]:border-b [&_td]:border-border/55 [&_td]:px-3 [&_td]:py-2",
"[&_td]:whitespace-normal [&_td]:[overflow-wrap:anywhere]",
"[&_td]:whitespace-normal [&_td]:[overflow-wrap:normal]",
"[&_th:not(:last-child)]:border-r [&_th:not(:last-child)]:border-border/45",
"[&_td:not(:last-child)]:border-r [&_td:not(:last-child)]:border-border/45",
"[&_tbody_tr:last-child_td]:border-b-0",
+1 -1
View File
@@ -503,7 +503,7 @@ export function MessageBubble({
"text-left text-reading whitespace-pre-wrap [overflow-wrap:anywhere]",
temporary
? "border border-dashed border-muted-foreground/40 bg-transparent"
: "bg-secondary/70",
: "user-message-surface bg-secondary/70",
)}
>
{messageText}
+18 -28
View File
@@ -1,4 +1,6 @@
import { useEffect, useId, useRef, useState, type CSSProperties, type PointerEvent, type ReactNode } from "react";
import { surfaceFocusProps } from "@/lib/surface-focus";
import { useEffect, useId, useRef, type PointerEvent, type ReactNode } from "react";
import { SidebarPanel } from "@/components/ui/sidebar-panel";
import { PanelRightClose, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { FileReferenceIcon, fileKindForPath, splitFilePath } from "@/components/FileReferenceChip";
@@ -6,6 +8,7 @@ import { FileActions } from "@/components/FileActions";
import { SidebarSelectionHighlight, SIDEBAR_SELECTION_ITEM_CLASS } from "@/components/SidebarSelectionHighlight";
import type { PreviewTab } from "@/hooks/useFilePreviewState";
import { cn } from "@/lib/utils";
import { sidePanelSurfaceClassName } from "@/components/ui/floating-surface";
/** One stable sidebar shell: switching targets never replays its opening animation. */
export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onCloseTab, onClose, onResizeStart, children }: {
@@ -21,14 +24,9 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
}) {
const { t } = useTranslation();
const id = useId();
const [entered, setEntered] = useState(false);
const buttons = useRef(new Map<string, HTMLButtonElement>());
const tabList = useRef<HTMLDivElement>(null);
const pendingFocus = useRef<string | null>(null);
useEffect(() => {
const frame = requestAnimationFrame(() => setEntered(true));
return () => cancelAnimationFrame(frame);
}, []);
useEffect(() => {
const revealActiveTab = () => buttons.current.get(activeId)?.parentElement?.scrollIntoView?.({ block: "nearest", inline: "nearest" });
revealActiveTab();
@@ -48,29 +46,18 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, 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 <aside aria-label={t("previewTabs.title")} data-testid="preview-pane" data-file-preview-panel
style={{
"--file-preview-width": `${width}px`,
"--file-preview-slot-width": !entered || isClosing ? "0px" : `${width}px`,
"--file-preview-mobile-width": !entered || isClosing ? "0px" : "100%",
} as CSSProperties}
className={cn("file-preview-pane absolute inset-y-0 right-0 z-30 w-[var(--file-preview-mobile-width)] overflow-hidden transition-[width] duration-300 ease-out motion-reduce:transition-none", isClosing && "pointer-events-none")}
>
<div className={cn("file-preview-content absolute inset-y-0 right-0 flex w-[100cqw] flex-col border-l border-border/60 bg-background pb-[env(safe-area-inset-bottom)] transition-opacity duration-200 motion-reduce:transition-none", !entered || isClosing ? "opacity-0" : "opacity-100")}>
<button type="button" aria-label={t("filePreview.resize")} onPointerDown={onResizeStart}
className="file-preview-resize group absolute inset-y-0 left-0 z-20 hidden w-2 cursor-col-resize touch-none justify-start focus-visible:outline-none">
<span aria-hidden className="h-full w-px bg-foreground/25 opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100" />
</button>
<div className="flex min-h-10 shrink-0 items-center gap-1 border-b border-border/40 px-2">
return <SidebarPanel aria-label={t("previewTabs.title")} data-testid="preview-pane" data-file-preview-panel
width={width} isClosing={isClosing} contentClassName={sidePanelSurfaceClassName}
header={<>
<div ref={tabList} role="tablist" aria-label={t("previewTabs.title")} className="min-w-0 flex-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
<SidebarSelectionHighlight activeId={activeId} scope="preview-tabs" targetSelector="[data-preview-tab-active]"
className="relative isolate flex w-max min-w-full items-center gap-1"
highlightClassName="rounded-compact">
highlightClassName="rounded-none rounded-t-2xl">
{tabs.map((tab, index) => {
const selected = tab.id === activeId;
const name = splitFilePath(tab.value).name;
const item = <div key={tab.id} role="presentation" data-preview-tab-active={selected ? "" : undefined}
className={cn(SIDEBAR_SELECTION_ITEM_CLASS, "group flex min-h-8 max-w-56 shrink-0 items-center rounded-compact", selected ? "text-foreground" : "text-muted-foreground hover:bg-muted/50 hover:text-foreground")}>
className={cn(SIDEBAR_SELECTION_ITEM_CLASS, "group flex min-h-8 max-w-56 shrink-0 items-center rounded-t-2xl", selected ? "text-foreground" : "text-muted-foreground hover:bg-muted/50 hover:text-foreground")}>
<button type="button" role="tab" id={`${id}-tab-${index}`} aria-selected={selected} aria-controls={`${id}-panel`}
tabIndex={selected ? 0 : -1} title={tab.value}
ref={(node) => { if (node) buttons.current.set(tab.id, node); else buttons.current.delete(tab.id); }}
@@ -87,7 +74,7 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
onSelect(tabs[next].id);
buttons.current.get(tabs[next].id)?.focus();
}}
className="touch-target flex h-8 min-w-0 items-center gap-1.5 rounded-compact pl-2.5 pr-1.5 text-[12.5px] font-medium leading-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
className="touch-target flex h-8 min-w-0 items-center gap-1.5 rounded-t-2xl pl-2.5 pr-1.5 text-[12.5px] font-medium leading-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
<span aria-hidden className="flex size-3.5 shrink-0 items-center justify-center text-muted-foreground">
<FileReferenceIcon kind={fileKindForPath(tab.value)} className="size-3.5" />
</span>
@@ -106,11 +93,14 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
{tabs.length > 1 ? <button type="button" className={iconButton} onClick={onClose} aria-label={t("previewTabs.closeAll")} title={t("previewTabs.closeAll")}>
<PanelRightClose className="size-4" aria-hidden />
</button> : null}
</div>
<div role="tabpanel" id={`${id}-panel`} aria-labelledby={`${id}-tab-${tabs.findIndex((tab) => tab.id === activeId)}`} tabIndex={0}
className="flex min-h-0 flex-1 flex-col focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
</>}>
<button type="button" aria-label={t("filePreview.resize")} onPointerDown={onResizeStart}
className="file-preview-resize group absolute inset-y-0 left-0 z-20 hidden w-2 cursor-col-resize touch-none justify-start focus-visible:outline-none">
<span aria-hidden className="h-full w-px bg-foreground/25 opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100" />
</button>
<div role="tabpanel" {...surfaceFocusProps} id={`${id}-panel`} aria-labelledby={`${id}-tab-${tabs.findIndex((tab) => tab.id === activeId)}`} tabIndex={0}
className="flex min-h-0 flex-1 flex-col outline-none data-[keyboard-focus]:ring-2 data-[keyboard-focus]:ring-inset data-[keyboard-focus]:ring-ring">
{children}
</div>
</div>
</aside>;
</SidebarPanel>;
}
+5 -3
View File
@@ -10,15 +10,16 @@ function textOf(node: Row): string {
return node.type === "text" ? String(node.value ?? "") : (node.children ?? []).map(textOf).join("");
}
const CodeChunk = memo(function CodeChunk({ rows, text, start, stylesheet, useInlineStyles, highlighted }: RowsProps & {
const CodeChunk = memo(function CodeChunk({ rows, text, start, stylesheet, useInlineStyles, highlighted, lineNumberWidth }: RowsProps & {
text: string;
start: number;
highlighted: boolean;
lineNumberWidth: string;
}) {
return (
<span data-code-chunk={start / CHUNK_LINES} className="flex min-w-max">
<span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground"
style={{ minWidth: "4.25em" }}>
style={{ minWidth: lineNumberWidth }}>
{rows.map((_, index) => start + index + 1).join("\n")}
</span>
<span data-highlighted={highlighted}>
@@ -78,7 +79,8 @@ export function ViewportCodeRows({ rows, stylesheet, useInlineStyles }: RowsProp
return (
<span ref={rootRef} className="block min-w-max" data-testid="viewport-code-rows">
{chunks.map((chunk, index) => <CodeChunk key={chunk.start} {...chunk}
stylesheet={tokenStyles} useInlineStyles={useInlineStyles} highlighted={visible.has(index)} />)}
stylesheet={tokenStyles} useInlineStyles={useInlineStyles} highlighted={visible.has(index)}
lineNumberWidth={`calc(${String(rows.length).length}ch + 1.15rem)`} />)}
</span>
);
}
@@ -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",
)}
>
<div
@@ -1,82 +1,72 @@
import { Fragment, useCallback, useMemo, useRef, useState, type PointerEvent, type ReactNode } from "react";
import { useEffect, useId, useRef, useState, type KeyboardEvent } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { Sheet, SheetContent, SheetTitle, SheetTrigger } from "@/components/ui/sheet";
import { FloatingPortalContext } from "@/components/ui/floating-portal";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { formatCompactTokenCount } from "@/lib/format";
import { formatTurnLatency } from "@/lib/format-time";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { SidebarPanel } from "@/components/ui/sidebar-panel";
import { ContextInspector } from "./ContextInspector";
import type { ContextSnapshot } from "@/lib/types";
import { cn } from "@/lib/utils";
export interface ComposerContextUsage {
estimated?: boolean;
contextTokens: number;
contextWindowTokens?: number;
}
export interface ComposerRoundUsage {
id: string;
timestamp: number;
inputTokens: number;
outputTokens?: number;
cachedTokens?: number;
estimatedTokens?: number;
generationMs?: number;
}
interface NormalizedRoundUsage extends ComposerRoundUsage {
cachedTokens?: number;
outputTokens: number;
}
function normalizeRounds(
rounds: readonly ComposerRoundUsage[],
): NormalizedRoundUsage[] {
return rounds
.filter((round) => Number.isFinite(round.inputTokens) && round.inputTokens > 0)
.map((round) => ({
...round,
inputTokens: Math.max(0, round.inputTokens),
outputTokens: Number.isFinite(round.outputTokens)
? Math.max(0, round.outputTokens ?? 0)
: 0,
...(Number.isFinite(round.cachedTokens)
? { cachedTokens: Math.min(round.inputTokens, Math.max(0, round.cachedTokens ?? 0)) }
: {}),
}));
}
export function ComposerUsagePopover({
context,
rounds,
snapshots = [],
onOpenFile,
showLabel = false,
compactLabel = false,
bottomSheet = false,
sidebarHost,
triggerHost,
open: controlledOpen,
onOpenChange,
}: {
context: ComposerContextUsage | null;
rounds: readonly ComposerRoundUsage[];
snapshots?: readonly ContextSnapshot[];
onOpenFile?: (path: string) => void;
showLabel?: boolean;
compactLabel?: boolean;
bottomSheet?: boolean;
sidebarHost?: HTMLElement | null;
triggerHost?: HTMLElement | null;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}) {
const { t, i18n } = useTranslation();
const [open, setOpen] = useState(false);
const normalizedRounds = useMemo(() => normalizeRounds(rounds), [rounds]);
const { t } = useTranslation();
const [localOpen, setLocalOpen] = useState(false);
const open = controlledOpen ?? localOpen;
const interactedOutside = useRef(false);
const setOpen = (next: boolean) => { if (next) interactedOutside.current = false; setLocalOpen(next); onOpenChange?.(next); };
const triggerRef = useRef<HTMLButtonElement>(null);
const panelId = useId();
const [narrow, setNarrow] = useState(false);
useEffect(() => {
const measure = () => setNarrow((sidebarHost?.clientWidth ?? window.innerWidth) < 780);
measure();
const observer = new ResizeObserver(measure);
if (sidebarHost) observer.observe(sidebarHost);
window.addEventListener("resize", measure);
return () => { observer.disconnect(); window.removeEventListener("resize", measure); };
}, [sidebarHost]);
const close = () => { setOpen(false); requestAnimationFrame(() => triggerRef.current?.focus()); };
const hasRounds = rounds.some((round) => Number.isFinite(round.inputTokens) && round.inputTokens > 0);
const hasContext = !!context
&& Number.isFinite(context.contextTokens)
&& context.contextTokens >= 0
&& Number.isFinite(context.contextWindowTokens)
&& (context.contextWindowTokens ?? 0) > 0;
if (!hasContext && normalizedRounds.length === 0) {
if (!open && !hasContext && !hasRounds && !snapshots.length) {
return null;
}
@@ -99,37 +89,21 @@ export function ComposerUsagePopover({
? detailsLabel
: t("thread.composer.context.tooltip", {
defaultValue: "Context {{percent}}%",
percent: contextPercentage,
percent: `${context?.estimated ? "≈" : ""}${contextPercentage}`,
});
const triggerLabel = contextPercentage === null
? detailsLabel
: `${contextDescription}. ${detailsLabel}`;
const ringCircumference = 2 * Math.PI * 6;
const ringLength = ringCircumference * meterPercentage / 100;
const maxInputTokens = Math.max(0, ...normalizedRounds.map((round) => round.inputTokens));
const numberFormatter = new Intl.NumberFormat(i18n.language);
const percentageFormatter = new Intl.NumberFormat(i18n.language, {
style: "percent",
maximumFractionDigits: 0,
});
const roundDateFormatter = new Intl.DateTimeFormat(i18n.language, {
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
});
const Root = bottomSheet ? Sheet : Popover;
const Trigger = bottomSheet ? SheetTrigger : PopoverTrigger;
const RoundRoot = bottomSheet ? Popover : Tooltip;
const RoundTrigger = bottomSheet ? PopoverTrigger : TooltipTrigger;
const RoundContent = bottomSheet ? PopoverContent : TooltipContent;
const RoundBar = bottomSheet ? "button" : "span";
const showTextLabel = showLabel && (!compactLabel || contextPercentage !== null);
const trigger = (
<Trigger asChild>
<button
type="button"
ref={triggerRef}
onClick={() => setOpen(!open)}
aria-expanded={open}
aria-controls={open ? panelId : undefined}
data-testid="composer-context-usage"
aria-label={triggerLabel}
className={cn(
@@ -184,372 +158,43 @@ export function ComposerUsagePopover({
)}
{showTextLabel ? (
<span aria-hidden className="whitespace-nowrap tabular-nums">
{compactLabel && contextPercentage !== null ? `${contextPercentage}%` : contextDescription}
{compactLabel && contextPercentage !== null ? `${context?.estimated ? "≈" : ""}${contextPercentage}%` : contextDescription}
</span>
) : null}
</button>
</Trigger>
);
return (
<Root open={open} onOpenChange={setOpen}>
<TooltipProvider>
{bottomSheet ? trigger : (
<Tooltip>
<TooltipTrigger asChild>{trigger}</TooltipTrigger>
<TooltipContent
side="top"
align="center"
sideOffset={8}
className="w-fit max-w-[calc(100vw-2rem)] rounded-full border-border/70 px-2.5 py-1 text-xs font-medium shadow-[0_8px_24px_rgba(15,23,42,0.13)]"
>
<span className="whitespace-nowrap tabular-nums">{contextDescription}</span>
</TooltipContent>
</Tooltip>
)}
const triggerWithTooltip = <TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>{trigger}</TooltipTrigger>
<TooltipContent side="top" className="text-xs">{contextDescription}</TooltipContent>
</Tooltip>
</TooltipProvider>;
<UsagePanel bottomSheet={bottomSheet} onDismiss={() => setOpen(false)}>
<div className="px-4 pb-4 pt-3.5">
{contextPercentage !== null ? (
<>
<div className="flex items-baseline justify-between gap-3">
<div className="flex min-w-0 items-baseline gap-2">
<span className={cn("shrink-0 font-medium text-foreground", bottomSheet ? "text-sm" : "text-[12px]")}>
{t("thread.composer.context.contextTitle", {
defaultValue: "Context",
})}
</span>
<span className={cn("truncate tabular-nums text-muted-foreground", bottomSheet ? "text-xs" : "text-[11px]")}>
{formatCompactTokenCount(context!.contextTokens)} / {formatCompactTokenCount(
context!.contextWindowTokens!,
)}
</span>
</div>
<span className={cn("shrink-0 tabular-nums text-muted-foreground", bottomSheet ? "text-xs" : "text-[11px]")}>
{contextPercentage}%
</span>
</div>
<div
role="progressbar"
aria-label={contextDescription}
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={contextPercentage}
className="mt-2 h-1 overflow-hidden rounded-full bg-muted"
>
<div
className={cn(
"h-full rounded-full",
status === "critical" && "bg-destructive",
status === "caution" && "bg-amber-500",
status === "normal" && "bg-foreground/45",
)}
style={{ width: `${contextPercentage}%` }}
/>
</div>
</>
) : null}
{normalizedRounds.length > 0 ? (
<>
<div className={cn(
"flex items-baseline justify-between gap-3",
contextPercentage === null ? "mt-0" : "mt-5",
)}>
<span className={cn("font-medium text-foreground", bottomSheet ? "text-sm" : "text-[12px]")}>
{t("thread.composer.context.recentRounds", {
defaultValue: "Recent rounds",
})}
</span>
<span className={cn("text-muted-foreground", bottomSheet ? "text-xs" : "text-[11px]")}>
{t("thread.composer.context.inputTrend", {
defaultValue: "Input tokens",
})}
</span>
</div>
<div
role="group"
aria-label={t("thread.composer.context.inputTrend", {
defaultValue: "Input tokens",
})}
className="mt-2 flex h-28 items-end gap-1.5 border-b border-border/60"
>
{normalizedRounds.map((round, index) => {
const cachedKnown = typeof round.cachedTokens === "number";
const cachedTokens = round.cachedTokens ?? 0;
const notReusedTokens = Math.max(0, round.inputTokens - cachedTokens);
const cacheHitRate = cachedKnown
? percentageFormatter.format(cachedTokens / round.inputTokens)
: null;
const cachedHeight = cachedKnown
? cachedTokens / round.inputTokens * 100
: 0;
const barHeight = round.inputTokens / maxInputTokens * 108;
const timestampLabel = roundDateFormatter.format(round.timestamp);
const detailRows = [
{
key: "input",
label: t("thread.composer.context.input", {
defaultValue: "Input tokens",
}),
value: numberFormatter.format(round.inputTokens),
},
cachedKnown
? {
key: "cache-hit-rate",
label: t("thread.composer.context.cacheHitRate", {
defaultValue: "KV cache hit rate",
}),
value: cacheHitRate!,
}
: null,
{
key: "output",
label: t("thread.composer.context.output", {
defaultValue: "Output tokens",
}),
value: numberFormatter.format(round.outputTokens),
},
typeof round.generationMs === "number"
? {
key: "duration",
label: t("thread.composer.context.duration", {
defaultValue: "Generation time",
}),
value: formatTurnLatency(round.generationMs, i18n.language),
}
: null,
].filter((row): row is NonNullable<typeof row> => !!row);
const detailNote = (round.estimatedTokens ?? 0) > 0
? t("message.usage.estimated", {
defaultValue: "Includes estimated usage",
})
: null;
const detailLabel = [
timestampLabel,
...detailRows.map((row) => `${row.label} ${row.value}`),
detailNote,
].filter((part): part is string => !!part).join(". ");
return (
<span
key={round.id}
className={cn(
"flex h-full min-w-0 flex-1 items-end justify-center rounded-sm",
bottomSheet && "relative",
"opacity-70 transition-opacity hover:opacity-100",
index === 0 && "justify-start",
normalizedRounds.length > 1
&& index === normalizedRounds.length - 1
&& "justify-end",
index === normalizedRounds.length - 1 && "opacity-100",
)}
>
<RoundRoot>
<RoundTrigger asChild>
<RoundBar
type={bottomSheet ? "button" : undefined}
role={bottomSheet ? undefined : "img"}
tabIndex={0}
aria-label={detailLabel}
data-testid="round-usage-bar"
className={cn(
"flex w-full max-w-7 flex-col overflow-hidden rounded-t-[3px] bg-muted",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
// Let touch users hit the entire column, even when a
// round's proportional bar is less than a pixel high.
bottomSheet && "before:absolute before:inset-0 before:content-[''] data-[state=open]:ring-2 data-[state=open]:ring-foreground/20",
)}
style={{ height: `${barHeight}px` }}
>
{cachedKnown ? (
<>
{notReusedTokens > 0 ? (
<span
className="kv-cache-not-reused block w-full"
style={{ height: `${100 - cachedHeight}%` }}
/>
) : null}
{cachedTokens > 0 ? (
<span
className="kv-cache-reused block w-full"
style={{ height: `${cachedHeight}%` }}
/>
) : null}
</>
) : (
<span className="block h-full w-full bg-muted-foreground/25" />
)}
</RoundBar>
</RoundTrigger>
<RoundContent
side="top"
align="center"
className="max-w-72 px-3 py-2 text-[11px]"
{...(bottomSheet ? {
"aria-label": timestampLabel,
onOpenAutoFocus: (event: Event) => event.preventDefault(),
} : {})}
>
<span
className="block font-medium text-foreground"
>
{timestampLabel}
</span>
<span className="mt-1 grid grid-cols-[max-content_max-content] gap-x-3 gap-y-0.5">
{detailRows.map((row) => (
<Fragment key={row.key}>
<span className="text-muted-foreground">
{row.label}
</span>
<span className="text-end tabular-nums text-foreground">
{row.value}
</span>
</Fragment>
))}
</span>
{detailNote ? (
<span
className="mt-1 block text-muted-foreground"
>
{detailNote}
</span>
) : null}
</RoundContent>
</RoundRoot>
</span>
);
})}
</div>
</>
) : null}
</div>
</UsagePanel>
</TooltipProvider>
</Root>
);
}
function UsagePanel({ bottomSheet, onDismiss, children }: {
bottomSheet: boolean;
onDismiss: () => void;
children: ReactNode;
}) {
const { t } = useTranslation();
const panelRef = useRef<HTMLDivElement | null>(null);
const [panelNode, setPanelNode] = useState<HTMLDivElement | null>(null);
const sheetRef = useCallback((node: HTMLDivElement | null) => {
panelRef.current = node;
setPanelNode(node);
}, []);
const gesture = useRef<{ pointerId: number; x: number; y: number; time: number } | null>(null);
const suppressClick = useRef(false);
const [offset, setOffset] = useState(0);
const [dragging, setDragging] = useState(false);
const title = t("thread.composer.context.panelTitle", { defaultValue: "Context usage" });
const focusPanel = (event: Event) => {
event.preventDefault();
gesture.current = null;
suppressClick.current = false;
setOffset(0);
setDragging(false);
panelRef.current?.focus({ preventScroll: true });
};
const cancelDrag = (event: PointerEvent<HTMLButtonElement>) => {
if (gesture.current?.pointerId !== event.pointerId) return;
gesture.current = null;
suppressClick.current = true;
setDragging(false);
setOffset(0);
const inspector = <ContextInspector sidebar expandable={!narrow} context={context} rounds={rounds} snapshots={snapshots}
onOpenFile={onOpenFile ? (path) => { setOpen(false); onOpenFile(path); } : undefined} />;
const onPanelKeyDown = (event: KeyboardEvent<HTMLElement>) => {
if (event.key === "Escape" && !event.defaultPrevented) { event.preventDefault(); close(); }
};
if (bottomSheet) {
return (
<SheetContent
ref={sheetRef}
side="bottom"
aria-describedby={undefined}
showCloseButton={false}
onOpenAutoFocus={focusPanel}
style={{ translate: `0 ${offset}px`, ...(dragging ? { transition: "none" } : {}) }}
className={cn(
"mx-auto max-h-[60dvh] w-full max-w-md gap-0 rounded-t-3xl border-t border-border/60 p-0 shadow-xl outline-none",
"transition-[translate]",
"data-[state=open]:duration-300 data-[state=open]:ease-out data-[state=closed]:duration-200 data-[state=closed]:ease-in",
)}
>
<button
type="button"
aria-label={t("common.close")}
className="mx-auto flex h-11 w-24 shrink-0 touch-none select-none items-center justify-center rounded-full cursor-grab active:cursor-grabbing focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onPointerDown={(event) => {
if (event.button !== 0 || !event.isPrimary || gesture.current) return;
event.currentTarget.setPointerCapture(event.pointerId);
gesture.current = { pointerId: event.pointerId, x: event.clientX, y: event.clientY, time: event.timeStamp };
suppressClick.current = false;
setDragging(true);
}}
onPointerMove={(event) => {
const start = gesture.current;
if (!start || start.pointerId !== event.pointerId) return;
const dy = event.clientY - start.y;
const dx = event.clientX - start.x;
if (Math.abs(dy) > 5 || Math.abs(dx) > 5) suppressClick.current = true;
setOffset(Math.max(0, dy));
}}
onPointerUp={(event) => {
const start = gesture.current;
if (!start || start.pointerId !== event.pointerId) return;
gesture.current = null;
const dy = Math.max(0, event.clientY - start.y);
const dx = Math.abs(event.clientX - start.x);
const threshold = Math.max(48, Math.min(96, (panelRef.current?.offsetHeight ?? 320) * 0.3));
const elapsed = Math.max(1, event.timeStamp - start.time);
const dismiss = dy > dx && (dy >= threshold || (dy > 20 && dy / elapsed > 0.5));
suppressClick.current ||= dy > 5 || dx > 5;
event.currentTarget.releasePointerCapture(event.pointerId);
setDragging(false);
if (dismiss) onDismiss();
else setOffset(0);
}}
onPointerCancel={cancelDrag}
onLostPointerCapture={cancelDrag}
onClick={(event) => {
// A completed drag also emits a click; don't close after a snap-back.
if (suppressClick.current && event.detail !== 0) {
event.preventDefault();
suppressClick.current = false;
return;
}
onDismiss();
}}
>
<span aria-hidden="true" className="h-1 w-8 rounded-full bg-foreground/15" />
</button>
<div className="shrink-0 px-5 pb-2">
<SheetTitle className="text-base font-medium">{title}</SheetTitle>
</div>
<div className="min-h-0 overflow-y-auto overscroll-contain px-1 pb-[max(0.75rem,env(safe-area-inset-bottom))]">
<FloatingPortalContext.Provider value={panelNode}>
{children}
</FloatingPortalContext.Provider>
</div>
</SheetContent>
);
}
return (
<PopoverContent
ref={panelRef}
side="top"
align="end"
sideOffset={10}
onOpenAutoFocus={focusPanel}
aria-label={title}
className="w-[min(22rem,calc(100vw-1.5rem))] p-0"
>
{children}
</PopoverContent>
);
return <>
{triggerHost === undefined ? triggerWithTooltip : triggerHost && createPortal(triggerWithTooltip, triggerHost)}
{narrow ? <Dialog open={open} onOpenChange={setOpen} modal={!sidebarHost}>
<DialogContent portalContainer={sidebarHost} placement="bottom" id={panelId} aria-describedby={undefined}
data-testid="context-sidebar"
overlayClassName={cn("context-drawer-backdrop", sidebarHost && "absolute bg-black/25 backdrop-blur-[8px] sm:bg-transparent sm:backdrop-blur-none")}
className="context-drawer-panel flex h-[85%] min-h-0 max-w-none flex-col gap-2 p-4 pt-5 pb-[max(1rem,env(safe-area-inset-bottom))]"
onCloseAutoFocus={(event) => { event.preventDefault(); if (!interactedOutside.current) triggerRef.current?.focus({ preventScroll: true }); }}
onInteractOutside={(event) => {
if (event.target instanceof Node && triggerRef.current?.contains(event.target)) event.preventDefault();
else interactedOutside.current = true;
}}>
<DialogTitle className="sr-only">{t("thread.composer.context.panelTitle")}</DialogTitle>
{inspector}
</DialogContent>
</Dialog> : createPortal(<SidebarPanel open={open} width={420} floating={!sidebarHost} id={panelId}
aria-label={t("thread.composer.context.panelTitle")} data-testid="context-sidebar" onKeyDown={onPanelKeyDown}>
{inspector}
</SidebarPanel>, sidebarHost ?? document.body)}
</>;
}
@@ -0,0 +1,294 @@
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useReducedMotion } from "motion/react";
import { Maximize2, Minimize2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { formatCompactTokenCount } from "@/lib/format";
import { createGraphSimulation, updateGraphSimulation, advanceGraphSimulation, startGraphSettlement, type GraphParticle, type GraphPosition } from "@/lib/context-graph-layout";
import type { ContextGraph } from "@/lib/types";
import { createGraphPresentation } from "./graph-presentation";
import { paintGraph, readGraphPalette, type GraphPalette } from "./graph-canvas";
const surface = "context-inspector-surface select-none rounded-[20px] bg-card";
export const ContextGraphScene = memo(function ContextGraphScene({ graph, epoch, expanded, onExpand, onOpenFile, onReady, sidebar = false }: {
graph: ContextGraph; epoch?: string; expanded: boolean; onExpand?: () => void; onOpenFile?: (path: string) => void; onReady?: (graph: ContextGraph) => void; sidebar?: boolean;
}) {
const { t } = useTranslation();
const container = useRef<HTMLDivElement>(null);
const canvas = useRef<HTMLCanvasElement>(null);
const paletteProbe = useRef<HTMLSpanElement>(null);
const palette = useRef<GraphPalette>();
const nodeElements = useRef(new Map<string, HTMLButtonElement>());
const focused = useRef<string | null>(null);
const positions = useRef(new Map<string, GraphPosition>());
const particles = useRef(new Map<string, GraphParticle>());
const simulation = useRef<ReturnType<typeof createGraphSimulation>>();
const settlement = useRef<ReturnType<typeof startGraphSettlement> | null>(null);
const paintedGraph = useRef<ContextGraph>();
const [presentation] = useState(createGraphPresentation);
const [frame, setFrame] = useState(presentation.frame);
const [size, setSize] = useState({ width: 550, height: 300 });
const [active, setActive] = useState<string | null>(null);
const [hovered, setHovered] = useState<string | null>(null);
const currentNodes = useMemo(() => new Map(graph.nodes.map((node) => [node.path, node])), [graph]);
const discovered = useMemo(() => new Set(graph.nodes.filter((node) => node.state === "discovered").map((node) => node.path)), [graph]);
const selected = active ? currentNodes.get(active) : undefined;
const candidate = active ?? hovered;
const highlighted = candidate && currentNodes.has(candidate) ? candidate : null;
const reducedMotion = !!useReducedMotion();
const clock = useRef({ frame: 0, previous: 0, visible: true, geometry: true });
const draw = useRef<(time: number) => void>(() => {});
const view = useRef({ x: 0, y: 0, k: 1 });
const interacted = useRef(false);
const fittedSize = useRef("");
const layoutKey = useRef("");
const pruneEpoch = useRef(false);
const previousEpoch = useRef(epoch);
const pan = useRef<{ id: number; x: number; y: number } | null>(null);
const dragging = useRef<{ id: number; path: string; x: number; y: number; moved: boolean } | null>(null);
const restoreNodeFocus = useRef(false);
const schedule = useCallback(() => {
if (!clock.current.frame && clock.current.visible && !document.hidden) clock.current.frame = requestAnimationFrame((time) => draw.current(time));
}, []);
const setView = useCallback((next: typeof view.current) => {
view.current = next;
schedule();
}, [schedule]);
draw.current = (time) => {
const state = clock.current;
state.frame = 0;
if (!state.visible || document.hidden) return;
const elapsed = state.previous ? time - state.previous : 1000 / 60;
state.previous = time;
const sim = simulation.current;
if (settlement.current) {
if (!settlement.current()) { schedule(); return; }
settlement.current = null; state.geometry = true;
}
const running = !!sim && (sim.alpha() > sim.alphaMin() || sim.alphaTarget() > 0);
if (sim && running && !reducedMotion) { advanceGraphSimulation(sim, elapsed); state.geometry = true; }
const change = presentation.advance(elapsed, reducedMotion);
if (change.removed) {
setFrame(presentation.frame);
if (pruneEpoch.current) {
const retained = new Set(presentation.frame.nodes.map((node) => node.path));
for (const path of positions.current.keys()) if (!retained.has(path)) positions.current.delete(path);
}
}
if (!change.moving) pruneEpoch.current = false;
if (state.geometry && sim) for (const particle of sim.nodes()) {
const point = positions.current.get(particle.path);
if (point) { point.x = particle.x; point.y = particle.y; }
else positions.current.set(particle.path, { x: particle.x, y: particle.y });
}
const bitmap = canvas.current;
const context = bitmap?.getContext("2d");
if (bitmap && context && palette.current) {
// Keep motion within a pixel budget; the final stationary paint restores
// native resolution for crisp labels without paying that cost every frame.
const ratio = running || change.moving
? Math.min(window.devicePixelRatio || 1, 1.5, Math.sqrt(1_000_000 / (size.width * size.height)))
: window.devicePixelRatio || 1;
const width = Math.round(size.width * ratio), height = Math.round(size.height * ratio);
if (bitmap.width !== width || bitmap.height !== height) { bitmap.width = width; bitmap.height = height; }
paintGraph(context, presentation.frame, positions.current, view.current, palette.current, highlighted, focused.current,
size.width, size.height, ratio, discovered);
if (paintedGraph.current !== graph) { paintedGraph.current = graph; onReady?.(graph); }
}
state.geometry = false;
if (change.moving || (running && !reducedMotion)) schedule();
// The next animation starts a new clock; idle time must not consume its labels.
else state.previous = 0;
};
useEffect(() => {
if (previousEpoch.current === epoch) return;
previousEpoch.current = epoch;
pruneEpoch.current = true;
palette.current?.labels.clear();
const retained = new Set(graph.nodes.map((node) => node.path));
for (const node of presentation.frame.nodes) retained.add(node.path);
for (const path of positions.current.keys()) if (!retained.has(path)) positions.current.delete(path);
}, [epoch, graph, presentation]);
useEffect(() => {
const element = container.current;
if (!element) return;
const observer = new ResizeObserver(([entry]) => setSize({ width: entry.contentRect.width, height: entry.contentRect.height }));
observer.observe(element);
const visibility = () => { clock.current.previous = 0; if (document.hidden) { cancelAnimationFrame(clock.current.frame); clock.current.frame = 0; } else schedule(); };
document.addEventListener("visibilitychange", visibility);
window.addEventListener("resize", schedule);
const intersection = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver((entries) => {
// Drawer entry can batch offscreen and onscreen records together. The
// newest record owns visibility; the first can leave painting suspended.
const entry = entries[entries.length - 1];
clock.current.visible = entry.isIntersecting;
if (entry.isIntersecting) { clock.current.previous = 0; schedule(); }
else { cancelAnimationFrame(clock.current.frame); clock.current.frame = 0; clock.current.previous = 0; }
});
intersection?.observe(element);
return () => { observer.disconnect(); intersection?.disconnect(); document.removeEventListener("visibilitychange", visibility); window.removeEventListener("resize", schedule); cancelAnimationFrame(clock.current.frame); clock.current.frame = 0; simulation.current?.stop(); };
}, [schedule]);
useEffect(() => {
const sim = simulation.current ?? createGraphSimulation(graph, positions.current, size.width, size.height);
if (simulation.current) updateGraphSimulation(sim, graph, positions.current, size.width, size.height);
simulation.current = sim.stop();
particles.current = new Map(sim.nodes().map((node) => [node.path, node]));
const nextLayout = JSON.stringify([graph.nodes.map((node) => node.path), graph.edges, size]);
settlement.current = reducedMotion && (layoutKey.current !== nextLayout || sim.alpha() > sim.alphaMin()) ? startGraphSettlement(sim) : null;
if (!reducedMotion && layoutKey.current !== nextLayout) sim.alpha(Math.max(sim.alpha(), 0.3));
layoutKey.current = nextLayout;
clock.current.geometry = true;
const key = `${size.width}:${size.height}`;
if (!interacted.current && graph.nodes.length && fittedSize.current !== key) {
const radius = Math.sqrt(graph.nodes.length * (60 * 0.36) ** 2 / Math.PI);
const k = Math.max(0.01, Math.min(1, (size.width - 100) / Math.max(1, radius * 6), (size.height - 80) / Math.max(1, radius * 6)));
setView({ k, x: size.width / 2 * (1 - k), y: size.height / 2 * (1 - k) });
fittedSize.current = key;
}
schedule();
}, [graph, size, reducedMotion, schedule, setView]);
useEffect(() => {
setActive((path) => path && currentNodes.has(path) ? path : null);
setHovered((path) => path && currentNodes.has(path) ? path : null);
}, [currentNodes]);
useEffect(() => {
setFrame(presentation.update(graph, highlighted));
schedule();
}, [graph, highlighted, presentation, schedule]);
useLayoutEffect(() => { clock.current.geometry = true; schedule(); }, [frame, schedule]);
useEffect(() => {
const element = container.current;
if (!element) return;
const wheel = (event: WheelEvent) => {
event.preventDefault(); interacted.current = true;
const rect = element.getBoundingClientRect();
const x = event.clientX - rect.left, y = event.clientY - rect.top, old = view.current;
const k = Math.max(0.25, Math.min(4, old.k * Math.exp(-event.deltaY * 0.002)));
setView({ k, x: x - (x - old.x) * k / old.k, y: y - (y - old.y) * k / old.k });
setActive(null);
};
element.addEventListener("wheel", wheel, { passive: false });
return () => element.removeEventListener("wheel", wheel);
}, [setView]);
const anchor = useRef({ getBoundingClientRect: () => new DOMRect() });
anchor.current.getBoundingClientRect = () => {
const rect = container.current?.getBoundingClientRect(), point = active ? positions.current.get(active) : undefined;
return new DOMRect((rect?.x ?? 0) + (point?.x ?? 0) * view.current.k + view.current.x - 22,
(rect?.y ?? 0) + (point?.y ?? 0) * view.current.k + view.current.y - 22, 44, 44);
};
const endDrag = (id: number, cancelled: boolean) => {
const drag = dragging.current;
if (!drag || drag.id !== id) return;
const particle = particles.current.get(drag.path);
if (particle) {
if (particle.fx != null) particle.x = particle.fx;
if (particle.fy != null) particle.y = particle.fy;
particle.fx = null; particle.fy = null;
clock.current.geometry = true;
}
simulation.current?.alphaTarget(0);
if (!cancelled && !drag.moved) setActive((path) => path === drag.path ? null : drag.path);
dragging.current = null;
schedule();
};
const nodeAt = (clientX: number, clientY: number, radius: number) => {
const rect = container.current?.getBoundingClientRect();
if (!rect) return null;
const x = clientX - rect.left, y = clientY - rect.top;
let closest: string | null = null;
let distance = Infinity;
for (let index = presentation.frame.nodes.length - 1; index >= 0; index--) {
const node = presentation.frame.nodes[index], point = positions.current.get(node.path);
if (!point || !currentNodes.has(node.path)) continue;
const candidateDistance = Math.hypot(point.x * view.current.k + view.current.x - x, point.y * view.current.k + view.current.y - y);
if (candidateDistance <= Math.max(radius, node.radius) && candidateDistance < distance) { closest = node.path; distance = candidateDistance; }
}
return closest;
};
useLayoutEffect(() => {
const update = () => { if (paletteProbe.current) palette.current = readGraphPalette(paletteProbe.current); schedule(); };
update();
const observer = new MutationObserver(update);
observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "style"] });
return () => observer.disconnect();
}, [schedule]);
const controls = useMemo(() => (<div className="sr-only">
{graph.nodes.map((node) => <button key={node.path} type="button" data-context-node={node.path} aria-label={node.name} aria-expanded={active === node.path} aria-haspopup="dialog"
ref={(element) => { if (element) nodeElements.current.set(node.path, element); else nodeElements.current.delete(node.path); }}
onFocus={(e) => { focused.current = e.currentTarget.matches(":focus-visible") ? node.path : null; setHovered(node.path); schedule(); }}
onKeyDown={() => { focused.current = node.path; schedule(); }}
onBlur={() => { focused.current = null; setHovered(null); schedule(); }}
onClick={() => setActive((path) => path === node.path ? null : node.path)}>{node.name}</button>)}
</div>), [graph.nodes, active, schedule]);
return <div ref={container} className={cn(surface, "relative isolate overflow-clip touch-none cursor-grab active:cursor-grabbing", sidebar ? "min-h-0 flex-1" : expanded ? "h-[min(65dvh,600px)]" : "h-[300px]")}
onPointerDown={(e) => {
if (!(e.target instanceof Node) || !e.currentTarget.contains(e.target)) return;
if (e.button !== 0 || !e.isPrimary || (e.target instanceof Element && e.target.closest("button"))) return;
// Keep the node's managed focus. Touch compatibility mouse events would
// otherwise focus the drawer and immediately dismiss its node popover.
e.preventDefault();
interacted.current = true;
const path = nodeAt(e.clientX, e.clientY, e.pointerType === "mouse" ? 12 : 22);
if (path) {
nodeElements.current.get(path)?.focus({ preventScroll: true });
dragging.current = { id: e.pointerId, path, x: e.clientX, y: e.clientY, moved: false };
pan.current = null;
} else { pan.current = { id: e.pointerId, x: e.clientX, y: e.clientY }; setActive(null); }
e.currentTarget.setPointerCapture(e.pointerId);
}}
onPointerMove={(e) => {
if (!(e.target instanceof Node) || !e.currentTarget.contains(e.target)) return;
const drag = dragging.current;
if (drag && drag.id === e.pointerId) {
const dx = e.clientX - drag.x, dy = e.clientY - drag.y;
if (!drag.moved && Math.hypot(dx, dy) < 5) return;
drag.moved = true; drag.x = e.clientX; drag.y = e.clientY; setActive(null); setHovered(drag.path);
const particle = particles.current.get(drag.path);
if (particle) {
particle.fx = (particle.fx ?? particle.x) + dx / view.current.k; particle.fy = (particle.fy ?? particle.y) + dy / view.current.k;
if (reducedMotion) { particle.x = particle.fx; particle.y = particle.fy; clock.current.geometry = true; }
else simulation.current?.alphaTarget(0.25);
schedule();
}
} else if (pan.current?.id === e.pointerId) {
const old = view.current, previous = pan.current;
setView({ ...old, x: old.x + e.clientX - previous.x, y: old.y + e.clientY - previous.y });
pan.current = { id: e.pointerId, x: e.clientX, y: e.clientY };
} else if (e.pointerType === "mouse") setHovered(nodeAt(e.clientX, e.clientY, 12));
}}
onPointerLeave={() => { if (!dragging.current) setHovered(null); }}
onPointerUp={(e) => { endDrag(e.pointerId, false); if (pan.current?.id === e.pointerId) pan.current = null; }}
onPointerCancel={(e) => { endDrag(e.pointerId, true); if (pan.current?.id === e.pointerId) pan.current = null; }}
onLostPointerCapture={(e) => { endDrag(e.pointerId, true); if (pan.current?.id === e.pointerId) pan.current = null; }}
onDoubleClick={(e) => {
if (!(e.target instanceof Node) || !e.currentTarget.contains(e.target)) return;
if ((e.target instanceof Element && e.target.closest("button")) || nodeAt(e.clientX, e.clientY, 22)) return;
const points = [...particles.current.values()];
if (!points.length) return;
const xs = points.map((p) => p.x), ys = points.map((p) => p.y);
const left = Math.min(...xs), right = Math.max(...xs), top = Math.min(...ys), bottom = Math.max(...ys);
const k = Math.max(0.01, Math.min(1, (size.width - 140) / Math.max(1, right - left), (size.height - 110) / Math.max(1, bottom - top)));
interacted.current = false; setView({ k, x: size.width / 2 - (left + right) / 2 * k, y: (size.height + 22) / 2 - (top + bottom) / 2 * k });
}}>
<span ref={paletteProbe} aria-hidden className="invisible absolute bg-background text-muted-foreground" />
{onExpand && <button type="button" onClick={onExpand} aria-label={t(expanded ? "thread.composer.context.collapse" : "thread.composer.context.expand")}
className="absolute right-2 top-2 z-10 flex size-9 items-center justify-center rounded-full bg-background/90 text-muted-foreground hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
{expanded ? <Minimize2 size={15} /> : <Maximize2 size={15} />}
</button>}
{!graph.nodes.length && !frame.nodes.length && <p className="absolute inset-0 flex items-center justify-center px-6 text-center text-xs text-muted-foreground">{t("thread.composer.context.noFiles")}</p>}
<canvas ref={canvas} aria-hidden="true" className="absolute inset-0 size-full" />
{controls}
<Popover open={!!selected} onOpenChange={(open) => { if (!open) setActive(null); }}>
<PopoverAnchor virtualRef={anchor} />
{selected && <PopoverContent updatePositionStrategy="always" side="bottom" sideOffset={12} collisionPadding={12} onOpenAutoFocus={(e) => e.preventDefault()}
onEscapeKeyDown={() => { restoreNodeFocus.current = true; }}
onCloseAutoFocus={(e) => { e.preventDefault(); if (restoreNodeFocus.current) nodeElements.current.get(selected.path)?.focus(); restoreNodeFocus.current = false; }} onInteractOutside={(e) => { if (e.target instanceof Element && container.current?.contains(e.target) && e.target.closest("[data-context-node],canvas")) e.preventDefault(); }} className="flex w-auto select-none items-center gap-4 rounded-xl px-3 py-2.5 font-sans text-ui-label">
<span className="text-muted-foreground">{t(selected.state === "loaded" ? "thread.composer.context.loaded" : "thread.composer.context.unloaded")}</span>
{selected.state === "loaded" && <span className="tabular-nums text-muted-foreground">{t("thread.composer.context.estimatedNodeTokens", { value: formatCompactTokenCount(selected.tokens) })}</span>}
{onOpenFile && <button type="button" className="min-h-8 font-sans text-ui-label text-orange-600 dark:text-orange-400 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" onClick={() => onOpenFile(selected.path)}>{t("thread.composer.context.openFile")}</button>}
</PopoverContent>}
</Popover>
</div>;
});
@@ -0,0 +1,99 @@
import { lazy, Suspense, useCallback, useEffect, useId, useRef, useState } from "react";
import { LayoutGroup, motion, useReducedMotion } from "motion/react";
import { useTranslation } from "react-i18next";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { cn } from "@/lib/utils";
import { formatTurnLatency } from "@/lib/format-time";
import type { ContextGraph, ContextSnapshot } from "@/lib/types";
import type { ComposerContextUsage, ComposerRoundUsage } from "./ComposerUsagePopover";
import { ContextReplayButton } from "./ContextReplayButton";
const ContextGraphScene = lazy(() => import("./ContextGraphScene").then(module => ({ default: module.ContextGraphScene })));
const EMPTY_GRAPH: ContextGraph = { nodes: [], edges: [] };
const surface = "context-inspector-surface select-none rounded-[20px] bg-card";
export function ContextInspector({ context, rounds, snapshots, onOpenFile, sidebar = false, expandable = true }: {
context: ComposerContextUsage | null; rounds: readonly ComposerRoundUsage[];
snapshots: readonly ContextSnapshot[]; onOpenFile?: (path: string) => void; sidebar?: boolean; expandable?: boolean;
}) {
const { t, i18n } = useTranslation();
const layoutId = useId();
const reducedMotion = useReducedMotion();
const [expanded, setExpanded] = useState(false);
const [replay, setReplay] = useState<{ frames: readonly ContextSnapshot[]; index: number; startedAt: number; interval: number } | null>(null);
const [readyGraph, setReadyGraph] = useState<ContextGraph | null>(null);
const [meterHover, setMeterHover] = useState(false);
const epoch = snapshots[0]?.id;
useEffect(() => { setReplay(null); }, [epoch]);
useEffect(() => {
if (!replay || readyGraph !== replay.frames[replay.index].graph) return;
// Keep a shared timeline instead of adding rendering time to every step.
// Advance only after painting each snapshot, even when catching up.
const remaining = replay.startedAt + (replay.index + 1) * replay.interval - performance.now();
const timer = window.setTimeout(() => setReplay((current) => current && current.index + 1 < current.frames.length
? { ...current, index: current.index + 1 } : null), Math.max(0, remaining));
return () => window.clearTimeout(timer);
}, [replay, readyGraph]);
const snapshot = replay ? replay.frames[replay.index] : snapshots.at(-1);
const latestRound = rounds.at(-1);
const tokens = snapshot ? snapshot.estimatedTokens ?? snapshot.usage?.context_tokens ?? snapshot.usage?.prompt_tokens : context?.contextTokens;
const estimated = snapshot?.estimatedTokens !== undefined || (!snapshot?.usage && context?.estimated);
const windowTokens = snapshot?.contextWindowTokens ?? context?.contextWindowTokens;
const tokenNumbers = new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 1 });
const hasTokenUsage = tokens !== undefined || !!windowTokens;
const used = tokens !== undefined && windowTokens ? Math.min(100, tokens / windowTokens * 100) : null;
const cached = snapshot ? snapshot.usage?.cached_tokens : latestRound?.cachedTokens;
const input = snapshot ? snapshot.usage?.prompt_tokens : latestRound?.inputTokens;
const cachedWidth = cached !== undefined && windowTokens ? Math.min(used ?? 0, cached / windowTokens * 100) : 0;
const duration = snapshot ? snapshot.usage?.generation_ms : latestRound?.generationMs;
const toggleExpanded = useCallback(() => setExpanded((value) => !value), []);
const openFileCallback = useRef(onOpenFile);
openFileCallback.current = onOpenFile;
const openFile = useCallback((path: string) => { setExpanded(false); openFileCallback.current?.(path); }, []);
const content = (large: boolean) => <motion.div layoutId={layoutId} transition={{ duration: reducedMotion ? 0 : 0.25, ease: [0.2, 0, 0, 1] }} className={cn("flex flex-col gap-3", sidebar && !large && "h-full min-h-0")}>
<Suspense fallback={<div aria-busy="true" className={cn(surface, "min-h-[300px]", sidebar && !large && "min-h-0 flex-1")} />}>
<ContextGraphScene graph={snapshot?.graph ?? EMPTY_GRAPH} epoch={epoch} onReady={setReadyGraph} expanded={large} sidebar={sidebar && !large} onExpand={expandable ? toggleExpanded : undefined} onOpenFile={onOpenFile ? openFile : undefined} />
</Suspense>
<div className="flex shrink-0 items-center gap-3">
<div onPointerEnter={() => setMeterHover(true)} onPointerLeave={() => setMeterHover(false)} className={cn(surface, "relative flex h-14 min-w-0 flex-1 items-center gap-4 px-4 transition-transform duration-150 ease-out motion-reduce:transition-none", meterHover && "scale-[1.015]")}>
<div className="flex h-11 flex-1 items-center">
<div role="progressbar" aria-label={t("thread.composer.context.contextTitle")} aria-valuemin={0} aria-valuemax={100} aria-valuenow={used === null ? undefined : Math.round(used)} className="relative h-1.5 w-full overflow-hidden rounded-full bg-muted">
<span className="absolute inset-y-0 left-0 rounded-full bg-muted-foreground/45 transition-[width] duration-150 ease-out motion-reduce:transition-none" style={{ width: `${used ?? 0}%` }} />
<span className="absolute inset-y-0 left-0 rounded-full bg-orange-500 transition-[width] duration-150 ease-out motion-reduce:transition-none" style={{ width: `${cachedWidth}%` }} />
</div>
</div>
<span className="text-sm tabular-nums">{used === null ? "—" : `${estimated ? "≈" : ""}${Math.round(used)}%`}</span>
{meterHover && (hasTokenUsage || cached !== undefined || duration !== undefined || replay !== null) && <div className="pointer-events-none absolute bottom-full right-0 z-20 mb-2 min-w-48 rounded-xl bg-popover px-3 py-2.5 font-sans text-xs font-normal leading-5 shadow-lg">
<dl className="grid grid-cols-[auto_auto] items-baseline gap-x-6 gap-y-1">
{hasTokenUsage && <><dt className="whitespace-nowrap text-muted-foreground">{t("thread.composer.context.panelTitle")}</dt><dd className="whitespace-nowrap text-right tabular-nums text-popover-foreground">{t("thread.composer.context.tokenUsage", {
used: tokens === undefined ? "—" : `${estimated ? "≈" : ""}${tokenNumbers.format(tokens / 1000)}k`,
limit: windowTokens ? `${tokenNumbers.format(windowTokens / 1000)}k` : "—",
})}</dd></>}
{cached !== undefined && !!input && <><dt className="text-muted-foreground">{t("thread.composer.context.cacheHitRate")}</dt><dd className="whitespace-nowrap text-right tabular-nums text-popover-foreground">{Math.round(cached / input * 100)}%</dd></>}
{duration !== undefined && <><dt className="text-muted-foreground">{t("thread.composer.context.duration")}</dt><dd className="whitespace-nowrap text-right tabular-nums text-popover-foreground">{formatTurnLatency(duration)}</dd></>}
{replay && <><dt className="text-muted-foreground">{t("thread.composer.context.history")}</dt>
<dd className="text-right tabular-nums text-muted-foreground">{replay.index + 1}/{replay.frames.length}</dd></>}
</dl>
</div>}
</div>
<ContextReplayButton disabled={replay !== null || snapshots.length < 2}
onPlay={() => {
setMeterHover(false);
// Scale by request count: our replay unit is a snapshot, not a graph edge.
const stepsPerSecond = Math.min(20, Math.max(5, 0.5 * Math.sqrt(snapshots.length)));
setReplay({ frames: [...snapshots], index: 0, startedAt: performance.now(), interval: 1000 / stepsPerSecond });
}} />
</div>
</motion.div>;
return <LayoutGroup>
{!expanded && content(false)}
<Dialog open={expanded} onOpenChange={setExpanded}>
<DialogContent showCloseButton={false} aria-describedby={undefined} overlayClassName="context-expanded-overlay bg-background/30 backdrop-blur-md" className="w-[min(960px,calc(100vw-2rem))] max-w-none border-0 bg-transparent p-0 shadow-none !animate-none">
<DialogTitle className="sr-only">{t("thread.composer.context.panelTitle")}</DialogTitle>
{content(true)}
</DialogContent>
</Dialog>
</LayoutGroup>;
}
@@ -0,0 +1,12 @@
import { RotateCcw } from "lucide-react";
import { useTranslation } from "react-i18next";
import { HoverHint } from "@/components/ui/tooltip";
export function ContextReplayButton({ disabled, onPlay }: { disabled: boolean; onPlay: () => void }) {
const { t } = useTranslation();
const label = t("thread.composer.context.playHistory");
return <HoverHint content={label} side="top" enabled={!disabled}><button type="button" aria-label={label} disabled={disabled} onClick={onPlay}
className="context-inspector-surface grid size-14 shrink-0 place-items-center rounded-[20px] bg-card text-foreground/80 transition-colors enabled:hover:bg-muted enabled:hover:text-orange-500 disabled:cursor-default disabled:text-foreground/45 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<RotateCcw className="size-[18px]" strokeWidth={2.25} aria-hidden="true" />
</button></HoverHint>;
}
+62 -27
View File
@@ -1,17 +1,12 @@
import {
PromptNavigationIcon,
} from "@/components/icons/product-icons";
import { useMemo, useRef, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { Search } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { SearchInput } from "@/components/ui/input";
import {
Sheet,
SheetContent,
SheetTitle,
} from "@/components/ui/sheet";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import {
type PromptAnchor,
userPromptAnchors,
@@ -24,14 +19,16 @@ interface PromptNavigatorProps {
messages: UIMessage[];
prompts?: PromptAnchor[];
onJumpToPrompt: (promptId: string) => void;
shortcutEnabled?: boolean;
}
const ROW_HEIGHT = 88;
const ROW_HEIGHT = 64;
export function PromptNavigator({
messages,
prompts: suppliedPrompts,
onJumpToPrompt,
shortcutEnabled = true,
}: PromptNavigatorProps) {
const { i18n, t } = useTranslation();
const prompts = useMemo(() => suppliedPrompts ?? userPromptAnchors(messages), [suppliedPrompts, messages]);
@@ -39,6 +36,23 @@ export function PromptNavigator({
const [query, setQuery] = useState("");
const listRef = useRef<HTMLDivElement>(null);
const [listTop, setListTop] = useState(0);
const [highlighted, setHighlighted] = useState(0);
const inputRef = useRef<HTMLInputElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
const keyDown = (event: KeyboardEvent) => {
if (!shortcutEnabled || !prompts.length || event.defaultPrevented || event.repeat || event.isComposing
|| event.altKey || event.shiftKey || !(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "f") return;
if (!open && (triggerRef.current?.closest("[hidden], [aria-hidden=true]") || document.querySelector("[role=dialog][data-state=open]"))) return;
event.preventDefault();
setListTop(0); setOpen(true);
inputRef.current?.focus(); inputRef.current?.select();
};
window.addEventListener("keydown", keyDown);
return () => window.removeEventListener("keydown", keyDown);
}, [shortcutEnabled, prompts.length, open]);
useEffect(() => { if (open) { setQuery(""); setHighlighted(0); setListTop(0); } }, [open]);
const filteredPrompts = useMemo(() => {
const needle = query.trim().toLocaleLowerCase();
@@ -60,6 +74,7 @@ export function PromptNavigator({
return (
<>
<Button
ref={triggerRef}
type="button"
variant="ghost"
size="icon"
@@ -68,41 +83,53 @@ export function PromptNavigator({
"hover:text-foreground",
)}
aria-label={t("thread.promptNavigator.open")}
aria-keyshortcuts="Control+F Meta+F"
onClick={() => { setListTop(0); setOpen(true); }}
>
<PromptNavigationIcon className="h-4 w-4" />
</Button>
<Sheet open={open} onOpenChange={setOpen}>
<SheetContent
side="right"
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent
showCloseButton={false}
aria-describedby={undefined}
className="w-[min(92vw,24rem)] gap-0 p-0 sm:max-w-[24rem]"
onOpenAutoFocus={(event) => { event.preventDefault(); inputRef.current?.focus(); }}
onCloseAutoFocus={(event) => { event.preventDefault(); triggerRef.current?.focus(); }}
className="session-search-dialog flex max-h-[min(40rem,100%)] w-[calc(100vw-2rem)] max-w-[42rem] flex-col gap-0 overflow-hidden p-0"
>
<div className="border-b px-5 pb-4 pt-5">
<SheetTitle className="text-base font-medium">
<DialogTitle className="sr-only">
{t("thread.promptNavigator.title")}
</SheetTitle>
<div className="relative mt-4">
</DialogTitle>
<div className="session-search-input flex h-[62px] shrink-0 items-center gap-3 border-b border-border px-[18px]">
<Search
aria-hidden
className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"
className="h-[18px] w-[18px] shrink-0 text-muted-foreground"
/>
<SearchInput
<input
ref={inputRef}
value={query}
onChange={(event) => {
setQuery(event.target.value);
setListTop(0);
setHighlighted(0);
if (listRef.current) listRef.current.scrollTop = 0;
}}
aria-label={t("thread.promptNavigator.search")}
placeholder={t("thread.promptNavigator.search")}
className="h-10 rounded-full border-border bg-background pl-9 pr-3 text-sm transition-colors"
onKeyDown={(event) => {
if (event.key === "Enter" && filteredPrompts[highlighted]) { event.preventDefault(); jump(filteredPrompts[highlighted].id); }
if ((event.key === "ArrowDown" || event.key === "ArrowUp") && filteredPrompts.length) {
event.preventDefault();
const next = (highlighted + (event.key === "ArrowDown" ? 1 : -1) + filteredPrompts.length) % filteredPrompts.length;
setHighlighted(next);
if (listRef.current) { listRef.current.scrollTop = next * ROW_HEIGHT; setListTop(next * ROW_HEIGHT); }
}
}}
className="h-full min-w-0 flex-1 bg-transparent text-[19px] font-normal leading-none text-foreground outline-none placeholder:text-muted-foreground"
/>
</div>
</div>
<div ref={listRef} className="min-h-0 flex-1 overflow-y-auto px-2 py-2"
<div ref={listRef} className="min-h-0 flex-1 overflow-y-auto overscroll-contain p-2.5 scrollbar-thin scrollbar-track-transparent"
onScroll={(event) => setListTop(event.currentTarget.scrollTop)}
onKeyDown={(event) => {
const button = (event.target as HTMLElement).closest<HTMLButtonElement>("[data-prompt-row]");
@@ -125,6 +152,8 @@ export function PromptNavigator({
<PromptNavigatorRow
key={prompt.id}
row={firstRow + offset}
highlighted={highlighted === firstRow + offset}
onHighlight={() => setHighlighted(firstRow + offset)}
locale={i18n.resolvedLanguage || i18n.language}
prompt={prompt}
onJump={jump}
@@ -137,8 +166,8 @@ export function PromptNavigator({
</div>
)}
</div>
</SheetContent>
</Sheet>
</DialogContent>
</Dialog>
</>
);
}
@@ -148,6 +177,8 @@ interface PromptNavigatorRowProps {
locale: string;
onJump: (promptId: string) => void;
prompt: PromptAnchor;
highlighted: boolean;
onHighlight: () => void;
}
function PromptNavigatorRow({
@@ -155,6 +186,8 @@ function PromptNavigatorRow({
locale,
onJump,
prompt,
highlighted,
onHighlight,
}: PromptNavigatorRowProps) {
const { t } = useTranslation();
const timestamp = fmtDateTime(prompt.createdAt, locale);
@@ -163,17 +196,19 @@ function PromptNavigatorRow({
type="button"
data-prompt-row={row}
className={cn(
"h-[88px] w-full overflow-hidden rounded-control px-3 py-3 text-left transition",
"hover:bg-accent focus-visible:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30",
"h-16 w-full overflow-hidden rounded-control px-3 py-2 text-left transition-colors",
"hover:bg-muted focus-visible:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30",
highlighted && "bg-muted",
)}
aria-label={t("thread.promptNavigator.jumpTo", { label: prompt.label })}
onClick={() => onJump(prompt.id)}
onMouseEnter={onHighlight}
>
<div className="line-clamp-2 whitespace-pre-wrap break-words text-sm leading-5 text-foreground">
<div className="truncate text-[14px] font-medium leading-5 text-foreground">
{prompt.preview}
</div>
{timestamp ? (
<div className="mt-1 text-[10px] leading-4 text-muted-foreground/75">
<div className="mt-1 text-[12px] leading-4 text-muted-foreground">
{timestamp}
</div>
) : null}
@@ -11,16 +11,15 @@ interface SessionInfoPopoverProps {
client: WebUIMutationTransport;
sessionKey: string;
token: string;
title: string;
}
export function SessionInfoPopover({ client, sessionKey, token, title }: SessionInfoPopoverProps) {
export function SessionInfoPopover({ client, sessionKey, token }: SessionInfoPopoverProps) {
const [surfacesOpen, setSurfacesOpen] = useState(false);
const { jobs, loading, loadFailed, now } = useSessionAutomationJobs(surfacesOpen, token, sessionKey);
const act = useCallback(async (action: AutomationAction, job: SessionAutomationJob) =>
(await runAutomationAction(client, action, job.id)).jobs, [client]);
const edit = useCallback(async (job: SessionAutomationJob, values: AutomationUpdatePayload) =>
(await updateAutomation(client, job.id, values)).jobs, [client]);
return <SessionInfoPopoverView title={title} jobs={jobs} loading={loading} loadFailed={loadFailed} now={now}
return <SessionInfoPopoverView jobs={jobs} loading={loading} loadFailed={loadFailed} now={now}
onAction={act} onEdit={edit} onSurfacesOpenChange={setSurfacesOpen} calendarHref="#/automations" />;
}
@@ -49,9 +49,8 @@ const RELATIVE_THRESHOLDS: [number, Intl.RelativeTimeFormatUnit][] = [
[Number.POSITIVE_INFINITY, "year"],
];
export function SessionInfoPopoverView({ title, jobs, loading, loadFailed, now, onAction, onEdit,
export function SessionInfoPopoverView({ jobs, loading, loadFailed, now, onAction, onEdit,
onSurfacesOpenChange, calendarHref, onOpenCalendar }: {
title: string;
jobs: SessionAutomationJob[];
loading: boolean;
loadFailed: boolean;
@@ -201,16 +200,7 @@ export function SessionInfoPopoverView({ title, jobs, loading, loadFailed, now,
>
<div className="flex max-h-[min(var(--radix-popover-content-available-height),32rem)] flex-col">
<div className="px-4 pb-3 pt-3.5">
<div className="min-w-0">
<div className="text-[12px] font-normal text-muted-foreground/75">
{t("thread.sessionInfo.title")}
</div>
<div className="mt-0.5 truncate text-[14px] font-medium text-foreground">
{title || t("thread.sessionInfo.untitled")}
</div>
</div>
<div className="mt-3 flex items-center justify-between gap-3 border-t border-border/45 pt-3">
<div className="flex items-center justify-between gap-3">
<span className="truncate text-[13px] font-medium text-foreground">
{t("thread.sessionInfo.automations")}
</span>
@@ -157,8 +157,7 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
{children}
<Sheet open={!!selected} onOpenChange={(open) => { if (!open) setSelectedId(null); }}>
<SheetContent ref={detailPanel} tabIndex={-1}
className="w-full gap-0 overflow-hidden border-l p-0 outline-none sm:w-[min(32rem,calc(100vw-1rem))] sm:max-w-none"
overlayClassName="bg-black/20 backdrop-blur-[8px]"
className="w-[calc(100vw-1rem)] gap-0 p-0 sm:w-[min(32rem,calc(100vw-1rem))] sm:max-w-none"
closeButtonClassName="right-2 top-2 grid h-11 w-11 place-items-center rounded-full sm:right-3 sm:top-3 sm:h-9 sm:w-9"
onOpenAutoFocus={(event) => {
event.preventDefault();
+16 -4
View File
@@ -241,6 +241,11 @@ interface ThreadComposerProps {
onManageModels?: () => void;
contextUsage?: ComposerContextUsage | null;
recentRoundUsage?: readonly ComposerRoundUsage[];
contextSnapshots?: readonly import("@/lib/types").ContextSnapshot[];
onOpenContextFile?: (path: string) => void;
contextSidebarHost?: HTMLElement | null;
contextSidebarOpen?: boolean;
onContextSidebarOpenChange?: (open: boolean) => void;
variant?: "thread" | "hero";
slashCommands?: SlashCommand[];
onMentionSearch?: () => void;
@@ -1080,6 +1085,11 @@ export function ThreadComposer({
onManageModels,
contextUsage = null,
recentRoundUsage = [],
contextSnapshots = [],
onOpenContextFile,
contextSidebarHost,
contextSidebarOpen,
onContextSidebarOpenChange,
variant = "thread",
slashCommands = [],
onMentionSearch,
@@ -1169,6 +1179,7 @@ export function ThreadComposer({
const formRef = useRef<HTMLFormElement>(null);
const tabFocusRequested = useRef(false);
const [compactControls, setCompactControls] = useState(false);
const [usageTriggerHost, setUsageTriggerHost] = useState<HTMLSpanElement | null>(null);
useEffect(() => {
// Automatic session focus should not open the hint; keyboard navigation should.
@@ -2588,8 +2599,8 @@ export function ThreadComposer({
/>
) : null;
const usageInMeta = mobileWorkspaceControls || compactControls;
const usageControl = !voiceRecorder.isRecording && (contextUsage || recentRoundUsage.length) ? (
<ComposerUsagePopover context={contextUsage} rounds={recentRoundUsage} showLabel={usageInMeta} compactLabel={mobileWorkspaceControls} bottomSheet={usageInMeta} />
const usageControl = !voiceRecorder.isRecording && (contextUsage || recentRoundUsage.length || contextSnapshots.length) ? (
<ComposerUsagePopover triggerHost={usageTriggerHost} context={contextUsage} rounds={recentRoundUsage} snapshots={contextSnapshots} onOpenFile={onOpenContextFile} showLabel={usageInMeta} compactLabel={mobileWorkspaceControls} sidebarHost={contextSidebarHost} open={contextSidebarOpen} onOpenChange={onContextSidebarOpenChange} />
) : null;
const inputTextClasses = cn(
// Keep the overlay's CJK/Latin spacing aligned with the native textarea caret.
@@ -2904,7 +2915,7 @@ export function ThreadComposer({
)}
>
{modelControl}
{!usageInMeta ? usageControl : null}
{!usageInMeta && usageControl ? <span className="contents" ref={setUsageTriggerHost} /> : null}
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
@@ -2981,12 +2992,13 @@ export function ThreadComposer({
</div>
{usageInMeta && usageControl || mobileWorkspaceControls && accessControl ? (
<div className={cn("ml-auto flex shrink-0 items-center gap-1", mobileWorkspaceControls && "h-11 max-w-[calc(100%-3rem)]")}>
{usageInMeta ? usageControl : null}
{usageInMeta && usageControl ? <span className="contents" ref={setUsageTriggerHost} /> : null}
{mobileWorkspaceControls ? accessControl : null}
</div>
) : null}
</div>
) : null}
{usageControl}
</form>
);
}
@@ -466,7 +466,7 @@ function MessageBlockMenu({
data-message-block-menu data-message-mobile-sheet data-message-context-menu-block={contextBlockKey}
className="gap-2 p-4 pt-5 pb-[max(1rem,env(safe-area-inset-bottom))] outline-none"
onCloseAutoFocus={(event) => { if (activity?.expanded) event.preventDefault(); }}>
<DialogTitle className="px-2 pb-2 pe-10 text-sm font-medium text-muted-foreground">{label}</DialogTitle>
<DialogTitle className="px-2 pb-2 text-sm font-medium text-muted-foreground">{label}</DialogTitle>
{actions}
</DialogContent>
</Dialog>
+80 -18
View File
@@ -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<string>();
for (let index = messages.length - 1; index >= 0 && recent.length < 8; index -= 1) {
const message = messages[index];
if (message.compacted) break;
const turnKey = message.turnId || message.id;
if (seenTurns.has(turnKey)) {
continue;
@@ -126,23 +130,13 @@ function recentComposerRoundUsage(messages: ComposerUsageSnapshot[]): ComposerRo
) {
continue;
}
const outputTokens = round.completion_tokens;
const cachedTokens = round.cached_tokens;
const estimatedTokens = round.estimated_tokens;
const generationMs = round.generation_ms;
recent.push({
id: `${turnKey}:${roundIndex}`,
timestamp: message.completedAt ?? message.createdAt,
inputTokens,
...(typeof outputTokens === "number" && Number.isFinite(outputTokens)
? { outputTokens }
: {}),
...(typeof cachedTokens === "number" && Number.isFinite(cachedTokens)
? { cachedTokens }
: {}),
...(typeof estimatedTokens === "number" && Number.isFinite(estimatedTokens)
? { estimatedTokens }
: {}),
...(typeof generationMs === "number" && Number.isFinite(generationMs)
? { generationMs }
: {}),
@@ -540,11 +534,36 @@ export function ThreadShell({
const [submittedViewportTurnId, setSubmittedViewportTurnId] = useState<string | null>(null);
const { state: previewState, openFile, resolveFile, selectTab, closeTab, close: closePreview, setWidth: setFilePreviewWidth } =
useFilePreviewState(previewSessionKey, filePreviewStore);
const [contextSidebarOpen, setContextSidebarOpen] = useState(false);
const [sidebarEnterWidth, setSidebarEnterWidth] = useState(0);
const [contextSidebarHost, setContextSidebarHost] = useState<HTMLElement | null>(null);
const setSidebarHost = useCallback((node: HTMLElement | null) => { shellRef.current = node; setContextSidebarHost(node); }, []);
const [closingPreview, setClosingPreview] = useState<{ key: string; state: FilePreviewState } | null>(null);
const filePreviewClosing = closingPreview?.key === previewSessionKey;
const visiblePreview = filePreviewClosing ? closingPreview.state : previewState;
const activePreview = visiblePreview.tabs.find((tab) => tab.id === visiblePreview.activeId);
const previewOpen = Boolean(activePreview);
const sidebarOpen = previewOpen || contextSidebarOpen;
const [localComposerHost, setLocalComposerHost] = useState<HTMLDivElement | null>(null);
const [composerMount] = useState(() => document.createElement("div"));
const inlineComposer = composerPortalTarget === undefined || (sidebarOpen && composerActive);
const composerDestination = inlineComposer ? localComposerHost : composerPortalTarget;
useLayoutEffect(() => {
// The inline host ref arrives on the next render. Keep the focused input
// attached until that destination is ready.
if (!composerDestination) { if (!inlineComposer) composerMount.remove(); return; }
if (composerMount.parentElement === composerDestination) return;
// Move the host, not the React subtree: drafts, graph replay and exit presence survive.
const focused = document.activeElement instanceof HTMLElement && composerMount.contains(document.activeElement)
? document.activeElement : null;
const selection = document.getSelection();
const range = focused && selection?.rangeCount && composerMount.contains(selection.getRangeAt(0).commonAncestorContainer)
? selection.getRangeAt(0).cloneRange() : null;
composerDestination.appendChild(composerMount);
focused?.focus({ preventScroll: true });
if (range && selection) { selection.removeAllRanges(); selection.addRange(range); }
}, [composerDestination, composerMount, inlineComposer]);
useLayoutEffect(() => () => composerMount.remove(), [composerMount]);
const [filePreviewMaxWidth, setFilePreviewMaxWidth] = useState(FILE_PREVIEW_MAX_WIDTH);
const filePreviewWidth = clampFilePreviewWidth(previewState.width, filePreviewMaxWidth);
const draftKey = session?.key ?? (temporaryChatEnabled ? "new:temporary" : "new:chat");
@@ -560,6 +579,23 @@ export function ThreadShell({
const shellRef = useRef<HTMLElement | null>(null);
const [conversationElement, setConversationElement] = useState<HTMLDivElement | null>(null);
const composerSurfaceRef = useRef<HTMLDivElement | null>(null);
useLayoutEffect(() => {
const shell = contextSidebarHost;
const surface = composerSurfaceRef.current;
if (!sidebarOpen || !inlineComposer || !shell || !surface) return;
// Metadata can wrap below the input card. Align sidebars to the visible
// surface, rather than assuming a fixed composer/footer padding.
const alignSidebar = () => {
const inset = shell.getBoundingClientRect().bottom - surface.getBoundingClientRect().bottom;
shell.style.setProperty("--sidebar-bottom-inset", `${Math.max(0, inset)}px`);
};
alignSidebar();
const observer = new ResizeObserver(alignSidebar);
observer.observe(shell);
observer.observe(composerMount);
observer.observe(surface);
return () => observer.disconnect();
}, [contextSidebarHost, sidebarOpen, inlineComposer, composerDestination, composerMount]);
const filePreviewWidthRef = useRef(FILE_PREVIEW_DEFAULT_WIDTH);
const filePreviewCloseTimerRef = useRef<number | null>(null);
const filePreviewResizeCleanupRef = useRef<(() => void) | null>(null);
@@ -704,6 +740,9 @@ export function ThreadShell({
() => recentComposerRoundUsage(usageSnapshots),
[usageSnapshots],
);
const contextGraphSnapshots = useMemo(
() => composerContextSnapshots(messages, modelRequests), [messages, modelRequests],
);
const currentGoalState = messagesReady ? goalState : undefined;
// Recovery decisions gate queued input, not the ledger-owned run state.
const recoveryNeedsDecision = recoveryState?.status === "awaiting_user"
@@ -1132,10 +1171,20 @@ export function ThreadShell({
}, []);
const handleOpenFilePreview = useCallback((path: string) => {
setSidebarEnterWidth(shellRef.current?.querySelector(".file-preview-pane")?.getBoundingClientRect().width ?? 0);
setContextSidebarOpen(false);
cancelPreviewClose();
openFile(path);
}, [cancelPreviewClose, openFile]);
const handleContextSidebarOpenChange = useCallback((open: boolean) => {
if (open) {
setSidebarEnterWidth(previewOpen ? filePreviewWidth : 0);
cancelPreviewClose(); closePreview();
}
setContextSidebarOpen(open);
}, [previewOpen, filePreviewWidth, cancelPreviewClose, closePreview]);
const handleClosePreviewTab = useCallback((id: string) => {
if (previewState.tabs.length === 1) handleCloseFilePreview();
else {
@@ -1325,7 +1374,13 @@ export function ThreadShell({
onManageModels={onOpenModelSettings}
contextUsage={composerContextUsage}
recentRoundUsage={composerRoundUsage}
contextSnapshots={contextGraphSnapshots}
onOpenContextFile={handleOpenFilePreview}
contextSidebarHost={contextSidebarHost}
contextSidebarOpen={contextSidebarOpen}
onContextSidebarOpenChange={handleContextSidebarOpenChange}
variant={composerVariant}
surfaceRef={composerSurfaceRef}
slashCommands={availableSlashCommands}
onMentionSearch={requestMentionCatalogs}
cliApps={cliApps}
@@ -1379,6 +1434,11 @@ export function ThreadShell({
onManageModels={onOpenModelSettings}
contextUsage={composerContextUsage}
recentRoundUsage={composerRoundUsage}
contextSnapshots={contextGraphSnapshots}
onOpenContextFile={handleOpenFilePreview}
contextSidebarHost={contextSidebarHost}
contextSidebarOpen={contextSidebarOpen}
onContextSidebarOpenChange={handleContextSidebarOpenChange}
variant="hero"
slashCommands={availableSlashCommands}
onMentionSearch={requestMentionCatalogs}
@@ -1420,10 +1480,11 @@ export function ThreadShell({
</div>
);
const sessionInfoAction = historyKey ? (
<SessionInfoPopover client={client} sessionKey={historyKey} token={token} title={title} />
<SessionInfoPopover client={client} sessionKey={historyKey} token={token} />
) : undefined;
const promptNavigatorAction = historyKey ? (
<PromptNavigator
shortcutEnabled={composerActive}
messages={displayMessages}
prompts={promptNavigation.prompts}
onJumpToPrompt={(promptId) => viewportRef.current?.jumpToUserPrompt(promptId)}
@@ -1460,7 +1521,7 @@ export function ThreadShell({
historyEnabled={webuiCapabilities.includes("webui.subagents.history.v1")}
active={composerActive}
enabled={!temporary && !!session?.key.startsWith("websocket:") && webuiCapabilities.includes("webui.subagents.v1")}>
<section ref={shellRef} data-preview-open={previewOpen || undefined} className="thread-preview-layout relative flex min-h-0 flex-1 overflow-hidden">
<section ref={setSidebarHost} style={{ "--sidebar-enter-width": `${sidebarEnterWidth}px`, "--sidebar-enter-mobile-width": sidebarEnterWidth ? "100%" : "0px" } as CSSProperties} data-preview-open={sidebarOpen || undefined} className="thread-preview-layout relative flex min-h-0 flex-1 overflow-hidden">
<div ref={setConversationElement} className={cn(
"thread-conversation relative flex min-w-0 flex-1 flex-col overflow-hidden",
headerPortalTarget === undefined && !hideHeader && "thread-workspace",
@@ -1496,7 +1557,7 @@ export function ThreadShell({
retryStatus={retryStatus}
emptyState={emptyState}
initialLoading={initialHistoryLoading}
composer={composerPortalTarget === undefined ? composer : null}
composer={inlineComposer ? <div ref={setLocalComposerHost} /> : null}
activeTurnId={viewportTurnId}
activeTurnStartedHere={activeTurnStartedHere}
conversationKey={historyKey}
@@ -1523,16 +1584,17 @@ export function ThreadShell({
{headerPortalTarget && headerActive
? createPortal(threadHeader, headerPortalTarget)
: null}
{composerPortalTarget ? createPortal(
{createPortal(
<div
hidden={!composerActive}
aria-hidden={!composerActive}
data-testid={composerActive ? "active-pane-composer" : undefined}
data-active-composer={composerActive || undefined}
>
{composer}
</div>,
composerPortalTarget,
) : null}
composerMount,
)}
{activePreview && previewSessionKey ? (
<FileActionsProvider key={previewSessionKey} value={fileActions}>
<PreviewPane
@@ -1,3 +1,4 @@
import { surfaceFocusProps } from "@/lib/surface-focus";
import { FullAccessIcon, RestrictedAccessIcon, WorkspaceIcon } from "@/components/icons/product-icons";
import type { HTMLAttributes, ReactElement, RefObject } from "react";
import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
@@ -636,8 +637,8 @@ export function WorkspaceProjectPicker({ disabled, scope, defaultScope, controls
</nav>}
<div className={cn("mr-[var(--picker-toolbar-inset)] flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-[var(--picker-field-radius)] bg-[#fcfcfc] dark:bg-muted", compact && showLocations && canBrowse && "hidden")}>
<div ref={attachColumns} data-workspace-columns className="sidebar-scrollbar flex flex-1 min-h-0 min-w-0 overflow-x-auto overscroll-x-contain">
{columns.map((column, columnIndex) => (!compact || columnIndex === currentColumnIndex) && <WorkspaceDirectoryColumn key={columnIndex} options={column.options} selectedPath={column.selectedPath} initialScrollTop={previewingPath ? 0 : currentVisit.scrollTops[columnIndex] ?? 0} visitRevision={history.revision} activeIndex={highlightActive && columnIndex === activeColumn ? activeOption : null}
id={`${optionsId}-${columnIndex}`} data-workspace-column={columnIndex} data-current-directory={columnIndex === currentColumnIndex ? "" : undefined} role="listbox" tabIndex={0} aria-activedescendant={highlightActive && columnIndex === activeColumn && column.options.length ? `${optionsId}-${columnIndex}-${activeOption}` : undefined} aria-label={column.path || t("thread.composer.workspace.projectAria")} aria-busy={columnIndex === currentColumnIndex && loading} style={{ width: `${compact ? 100 : 100 / columnCount}%` }} className="sidebar-scrollbar relative min-w-0 shrink-0 overflow-x-hidden overflow-y-auto px-2 outline-none [scrollbar-gutter:stable] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/50"
{columns.map((column, columnIndex) => (!compact || columnIndex === currentColumnIndex) && <WorkspaceDirectoryColumn key={columnIndex} {...surfaceFocusProps} options={column.options} selectedPath={column.selectedPath} initialScrollTop={previewingPath ? 0 : currentVisit.scrollTops[columnIndex] ?? 0} visitRevision={history.revision} activeIndex={highlightActive && columnIndex === activeColumn ? activeOption : null}
id={`${optionsId}-${columnIndex}`} data-workspace-column={columnIndex} data-current-directory={columnIndex === currentColumnIndex ? "" : undefined} role="listbox" tabIndex={0} aria-activedescendant={highlightActive && columnIndex === activeColumn && column.options.length ? `${optionsId}-${columnIndex}-${activeOption}` : undefined} aria-label={column.path || t("thread.composer.workspace.projectAria")} aria-busy={columnIndex === currentColumnIndex && loading} style={{ width: `${compact ? 100 : 100 / columnCount}%` }} className="sidebar-scrollbar relative min-w-0 shrink-0 overflow-x-hidden overflow-y-auto px-2 outline-none [scrollbar-gutter:stable] data-[keyboard-focus]:ring-2 data-[keyboard-focus]:ring-inset data-[keyboard-focus]:ring-ring/50"
onFocus={event => { if (event.target === event.currentTarget) { setActiveColumn(columnIndex); setActiveIndex(0); } }}
onKeyDown={event => {
if (event.target !== event.currentTarget || event.altKey || event.metaKey || event.ctrlKey || pickingFolder) return;
@@ -0,0 +1,94 @@
import type { GraphPosition } from "@/lib/context-graph-layout";
import type { GraphPresentation } from "./graph-presentation";
type RGB = readonly [number, number, number];
export interface GraphPalette { background: RGB; foreground: string; muted: RGB; font: string; labels: Map<string, string> }
interface GraphCamera { x: number; y: number; k: number }
const orange: RGB = [249, 115, 22];
const blend = (a: RGB, b: RGB, amount: number): RGB => [a[0] + (b[0] - a[0]) * amount, a[1] + (b[1] - a[1]) * amount, a[2] + (b[2] - a[2]) * amount];
const rgb = (value: RGB) => `rgb(${value.map(Math.round).join(" ")})`;
export function readGraphPalette(element: HTMLElement): GraphPalette {
const style = getComputedStyle(element);
const parse = (color: string): RGB => {
const values = color.match(/[\d.]+/g)?.map(Number) ?? [];
return [values[0] ?? 0, values[1] ?? 0, values[2] ?? 0];
};
return { background: parse(style.backgroundColor), muted: parse(style.color), foreground: getComputedStyle(element.parentElement!).color, font: `10px ${style.fontFamily}`, labels: new Map() };
}
export function fitGraphLabel(name: string, measure: (text: string) => number, maxWidth = 128): string {
if (measure(name) <= maxWidth) return name;
const characters = Array.from(name);
let start = 0, end = characters.length;
while (start < end) {
const middle = Math.ceil((start + end) / 2);
if (measure(`${characters.slice(0, middle).join("")}…`) <= maxWidth) start = middle;
else end = middle - 1;
}
return `${characters.slice(0, start).join("")}…`;
}
/** One bitmap paint; neither force ticks nor camera movement mutate per-node DOM. */
export function paintGraph(context: CanvasRenderingContext2D, frame: GraphPresentation, positions: ReadonlyMap<string, GraphPosition>,
view: GraphCamera, palette: GraphPalette, highlighted: string | null, focused: string | null,
width: number, height: number, pixelRatio: number, discovered: ReadonlySet<string>) {
context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
context.clearRect(0, 0, width, height);
const groups = new Map<string, { opacity: number; dashed: boolean; edges: GraphPresentation["edges"] }>();
for (const edge of frame.edges) {
const opacity = edge.presence * edge.emphasis * 0.7;
const dashed = discovered.has(edge.target);
const key = `${opacity}:${dashed}`;
let group = groups.get(key);
if (!group) { group = { opacity, dashed, edges: [] }; groups.set(key, group); }
group.edges.push(edge);
}
context.strokeStyle = "#f97316";
context.lineWidth = 1;
for (const group of groups.values()) {
context.globalAlpha = group.opacity;
context.setLineDash(group.dashed ? [3, 5] : []);
context.beginPath();
for (const edge of group.edges) {
const a = positions.get(edge.source), b = positions.get(edge.target);
if (!a || !b) continue;
context.moveTo(a.x * view.k + view.x, a.y * view.k + view.y);
context.lineTo(b.x * view.k + view.x, b.y * view.k + view.y);
}
context.stroke();
}
context.setLineDash([]);
context.font = palette.font;
context.textAlign = "center";
context.textBaseline = "middle";
for (const node of frame.nodes) {
const point = positions.get(node.path);
if (!point) continue;
const x = point.x * view.k + view.x, y = point.y * view.k + view.y;
const alpha = node.presence * node.emphasis;
const color = blend(palette.muted, orange, node.focus);
context.globalAlpha = alpha;
context.strokeStyle = rgb(color);
context.fillStyle = rgb(blend(palette.background, color, node.loaded));
context.beginPath(); context.arc(x, y, node.radius - 0.5, 0, Math.PI * 2); context.fill(); context.stroke();
if (node.path === focused) {
context.strokeStyle = palette.foreground;
context.lineWidth = 2;
context.beginPath(); context.roundRect(x - 22, y - 22, 44, 44, 4); context.stroke();
context.lineWidth = 1;
}
// Introduce newly loaded files for one second, then fade to the usual zoom visibility.
const labelOpacity = node.path === highlighted ? 1 : Math.max(0, Math.min(1, (view.k - 1) / 3.75), Math.min(1, node.labelRemaining / 600));
if (labelOpacity > 0) {
context.globalAlpha = alpha * labelOpacity;
context.fillStyle = palette.foreground;
let label = palette.labels.get(node.name);
if (label === undefined) {
label = fitGraphLabel(node.name, (text) => context.measureText(text).width);
palette.labels.set(node.name, label);
}
context.fillText(label, x, y + 24);
}
}
context.globalAlpha = 1;
}
@@ -0,0 +1,77 @@
import { nodeRadius } from "@/lib/context-graph-layout";
import type { ContextGraph, ContextGraphNode } from "@/lib/types";
type PresentedNode = ContextGraphNode & { presence: number; emphasis: number; focus: number; radius: number; loaded: number; labelRemaining: number };
type PresentedEdge = ContextGraph["edges"][number] & { presence: number; emphasis: number };
export type GraphPresentation = { nodes: PresentedNode[]; edges: PresentedEdge[] };
const edgeKey = (edge: ContextGraph["edges"][number]) => JSON.stringify([edge.source, edge.target]);
/** Mutable animation state; request graphs remain immutable. The caller owns its clock. */
export function createGraphPresentation() {
const nodes = new Map<string, PresentedNode>();
const edges = new Map<string, PresentedEdge>();
let wanted = new Set<string>();
let wantedEdges = new Set<string>();
let related = new Set<string | null>();
let highlighted: string | null = null;
let frame: GraphPresentation = { nodes: [], edges: [] };
let moving = false;
return {
get frame() { return frame; },
update(graph: ContextGraph, focus: string | null) {
highlighted = focus;
const previouslyWanted = wanted;
wanted = new Set(graph.nodes.map((node) => node.path));
wantedEdges = new Set(graph.edges.map(edgeKey));
related = new Set([focus]);
for (const edge of graph.edges) {
if (edge.source === focus) related.add(edge.target);
if (edge.target === focus) related.add(edge.source);
}
for (const node of graph.nodes) {
const previous = nodes.get(node.path);
if (previous) {
if (node.state !== "loaded") previous.labelRemaining = 0;
// A replay can reintroduce a node before its exit animation removes it.
else if (previous.state !== "loaded" || !previouslyWanted.has(node.path)) previous.labelRemaining = 1600;
Object.assign(previous, node);
}
else nodes.set(node.path, { ...node, presence: 0, emphasis: 1, focus: 0, radius: nodeRadius(node), loaded: Number(node.state === "loaded"), labelRemaining: node.state === "loaded" ? 1600 : 0 });
}
for (const edge of graph.edges) if (!edges.has(edgeKey(edge))) edges.set(edgeKey(edge), { ...edge, presence: 0, emphasis: 1 });
frame = { nodes: [...nodes.values()], edges: [...edges.values()] };
moving = true;
return frame;
},
advance(elapsed: number, reducedMotion: boolean) {
if (!moving) return { moving: false, removed: false };
const amount = reducedMotion ? 1 : 1 - Math.pow(0.9, Math.min(64, Math.max(0, elapsed)) / (1000 / 60));
moving = false;
let removed = false;
const approach = (value: number, target: number) => {
const next = value + (target - value) * amount;
if (Math.abs(next - target) < 0.005) return target;
moving = true;
return next;
};
for (const [path, node] of nodes) {
// Keep the clock alive after the layout settles so new labels can fade out.
node.labelRemaining = Math.max(0, node.labelRemaining - Math.max(0, elapsed));
if (node.labelRemaining > 0) moving = true;
node.presence = approach(node.presence, wanted.has(path) ? 1 : 0);
node.emphasis = approach(node.emphasis, highlighted && !related.has(path) ? 0.2 : 1);
node.focus = approach(node.focus, path === highlighted ? 1 : 0);
node.radius = approach(node.radius, nodeRadius(node));
node.loaded = approach(node.loaded, Number(node.state === "loaded"));
if (!wanted.has(path) && node.presence === 0) { nodes.delete(path); removed = true; }
}
for (const [key, edge] of edges) {
edge.presence = approach(edge.presence, wantedEdges.has(key) ? 1 : 0);
edge.emphasis = approach(edge.emphasis, highlighted && edge.source !== highlighted && edge.target !== highlighted ? 0.2 : 1);
if (!wantedEdges.has(key) && edge.presence === 0) { edges.delete(key); removed = true; }
}
if (removed) frame = { nodes: [...nodes.values()], edges: [...edges.values()] };
return { moving, removed };
},
};
}
+124 -11
View File
@@ -41,26 +41,29 @@ DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogPositionedContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & {
contained?: boolean;
positionerStyle?: React.CSSProperties;
placement?: "center" | "bottom";
overlayClassName?: string;
}
>(({ positionerStyle, placement, overlayClassName, ...props }, ref) => (
<DialogOverlay forceMount className={overlayClassName}>
<div className={cn("fixed inset-0 z-50 flex items-start justify-center overflow-y-auto overscroll-contain", placement !== "bottom" && "p-4")} style={{
>(({ contained, positionerStyle, placement, overlayClassName, ...props }, ref) => {
const Overlay = contained ? "div" : DialogOverlay;
return <Overlay data-dialog-backdrop {...(contained ? {} : { forceMount: true })} className={cn(contained && "absolute inset-0 z-50", overlayClassName)}>
<div className={cn("fixed inset-0 z-50 flex items-start justify-center overscroll-contain", placement === "bottom" ? "overflow-clip" : "overflow-y-auto p-4", contained && "absolute")} style={{
top: "var(--app-viewport-top, 0px)",
height: "var(--app-viewport-height, 100%)",
bottom: "auto",
...positionerStyle,
...(contained ? { top: 0, height: "100%" } : positionerStyle),
}}>
<DialogPrimitive.Content ref={ref} {...props} />
</div>
</DialogOverlay>
));
</Overlay>;
});
DialogPositionedContent.displayName = "DialogPositionedContent";
interface DialogContentProps
extends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> {
portalContainer?: HTMLElement | null;
showCloseButton?: boolean;
overlayClassName?: string;
layoutAnchor?: HTMLElement | null;
@@ -71,10 +74,73 @@ interface DialogContentProps
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
DialogContentProps
>(({ className, children, showCloseButton = true, overlayClassName, placement = "center", layoutAnchor: explicitLayoutAnchor, centerInLayoutAnchor = false, onOpenAutoFocus, ...props }, ref) => {
>(({ className, children, portalContainer, showCloseButton = true, overlayClassName, placement = "center", layoutAnchor: explicitLayoutAnchor, centerInLayoutAnchor = false, onOpenAutoFocus, ...props }, ref) => {
const { t } = useTranslation();
const [container, setContainer] = React.useState<HTMLDivElement | null>(null);
const contentNode = React.useRef<HTMLDivElement | null>(null);
const gesture = React.useRef<{ id: number; start: number; y: number; time: number; speed: number; moved: boolean } | null>(null);
const suppressClick = React.useRef(false);
const settleAnimation = React.useRef<Animation | null>(null);
const backdropFrame = React.useRef<number | null>(null);
const dragBackdrop = React.useRef<{ node: HTMLElement; color: string; blur: number } | null>(null);
const paintBackdrop = (distance: number, height: number) => {
const backdrop = dragBackdrop.current;
if (!backdrop) return;
const remaining = 1 - Math.min(1, Math.max(0, distance) / Math.max(1, height));
backdrop.node.style.backgroundColor = `color-mix(in srgb, ${backdrop.color} ${remaining * 100}%, transparent)`;
backdrop.node.style.backdropFilter = `blur(${backdrop.blur * remaining}px)`;
};
const cancelBackdropFrame = () => {
if (backdropFrame.current !== null) cancelAnimationFrame(backdropFrame.current);
backdropFrame.current = null;
};
React.useEffect(() => () => {
settleAnimation.current?.cancel();
if (backdropFrame.current !== null) cancelAnimationFrame(backdropFrame.current);
}, []);
const finishDrag = (button: HTMLButtonElement, pointerId: number, cancelled: boolean) => {
const drag = gesture.current;
const node = contentNode.current;
if (!drag || drag.id !== pointerId || !node) return;
gesture.current = null;
suppressClick.current = drag.moved;
if (!drag.moved) {
if (dragBackdrop.current) {
const style = dragBackdrop.current.node.style;
for (const property of ["background-color", "backdrop-filter", "transition"]) style.removeProperty(property);
dragBackdrop.current = null;
}
return;
}
const distance = Math.max(0, drag.y - drag.start);
const dismiss = !cancelled && (distance > Math.min(120, node.offsetHeight * 0.22)
|| (distance > 24 && drag.speed > 0.65 && performance.now() - drag.time < 100));
const destination = dismiss ? node.offsetHeight : 0;
const animation = node.animate([{ translate: `0 ${distance}px` }, { translate: `0 ${destination}px` }], {
duration: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? 0 : dismiss ? 180 : 260,
easing: "cubic-bezier(0.2, 0, 0, 1)", fill: "forwards",
});
settleAnimation.current = animation;
const follow = () => {
paintBackdrop(parseFloat(getComputedStyle(node).getPropertyValue("translate").split(" ")[1]) || 0, node.offsetHeight);
backdropFrame.current = requestAnimationFrame(follow);
};
backdropFrame.current = requestAnimationFrame(follow);
animation.onfinish = () => {
cancelBackdropFrame();
node.style.translate = `0 ${destination}px`;
paintBackdrop(destination, node.offsetHeight);
if (!dismiss && dragBackdrop.current) {
const style = dragBackdrop.current.node.style;
for (const property of ["background-color", "backdrop-filter", "transition"]) style.removeProperty(property);
dragBackdrop.current = null;
}
animation.cancel();
settleAnimation.current = null;
if (dismiss) { suppressClick.current = false; button.click(); }
};
};
const inheritedLayoutAnchor = React.useContext(DialogLayoutContext);
const layoutAnchor = explicitLayoutAnchor ?? inheritedLayoutAnchor;
const [layout, setLayout] = React.useState<React.CSSProperties>();
@@ -114,13 +180,22 @@ const DialogContent = React.forwardRef<
}, [layoutAnchor, placement, centerInLayoutAnchor]);
const contentRef = React.useCallback((node: HTMLDivElement | null) => {
contentNode.current = node;
if (!node) {
settleAnimation.current?.cancel();
settleAnimation.current = null;
if (backdropFrame.current !== null) cancelAnimationFrame(backdropFrame.current);
backdropFrame.current = null;
dragBackdrop.current = null;
gesture.current = null;
}
setContainer(node);
if (typeof ref === "function") ref(node);
else if (ref) ref.current = node;
}, [ref]);
return (
<DialogPortal>
<DialogPortal container={portalContainer}>
<DialogPositionedContent
contained={!!portalContainer}
positionerStyle={layout}
placement={placement}
overlayClassName={overlayClassName}
@@ -136,9 +211,10 @@ const DialogContent = React.forwardRef<
modalSurfaceClassName,
"relative grid w-full max-w-lg gap-4 p-6 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 motion-reduce:animate-none",
placement === "bottom"
? "mt-auto max-h-[85dvh] overflow-y-auto overscroll-contain rounded-t-modal pb-[max(1rem,env(safe-area-inset-bottom))] data-[state=open]:slide-in-from-bottom-4 data-[state=closed]:slide-out-to-bottom-4"
? "mt-auto max-h-[85dvh] overflow-y-auto overscroll-contain rounded-t-modal pb-[max(1rem,env(safe-area-inset-bottom))] data-[state=open]:slide-in-from-bottom-full data-[state=closed]:slide-out-to-bottom-full ease-[cubic-bezier(0.2,0,0,1)] duration-300"
: "my-auto origin-center rounded-modal data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",
className,
placement === "bottom" && "pt-9 transition-none",
)}
{...props}
>
@@ -146,8 +222,45 @@ const DialogContent = React.forwardRef<
{children}
</FloatingPortalContext.Provider>
{showCloseButton ? (
<DialogPrimitive.Close className={cn("absolute right-2.5 top-2.5 grid place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none", placement === "bottom" ? "h-11 w-11" : "h-7 w-7")}>
<X className="h-4 w-4" />
<DialogPrimitive.Close
onPointerDown={(event) => {
if (placement !== "bottom" || !event.isPrimary || event.button !== 0) return;
const node = contentNode.current;
const offset = node ? parseFloat(getComputedStyle(node).getPropertyValue("translate").split(" ")[1]) || 0 : 0;
cancelBackdropFrame();
settleAnimation.current?.cancel();
if (node) node.style.translate = `0 ${offset}px`;
const backdrop = node?.closest<HTMLElement>("[data-dialog-backdrop]");
if (backdrop && !dragBackdrop.current) {
const style = getComputedStyle(backdrop);
dragBackdrop.current = { node: backdrop, color: style.backgroundColor,
blur: parseFloat(style.getPropertyValue("backdrop-filter").match(/blur\(([^)]+)/)?.[1] ?? "0") || 0 };
backdrop.style.transition = "none";
backdrop.style.animation = "none";
}
suppressClick.current = false;
gesture.current = { id: event.pointerId, start: event.clientY - offset, y: event.clientY, time: performance.now(), speed: 0, moved: offset > 5 };
event.currentTarget.setPointerCapture(event.pointerId);
}}
onPointerMove={(event) => {
const drag = gesture.current;
if (!drag || drag.id !== event.pointerId) return;
const now = performance.now();
drag.speed = (event.clientY - drag.y) / Math.max(1, now - drag.time);
drag.y = event.clientY; drag.time = now;
drag.moved ||= Math.abs(drag.y - drag.start) > 5;
if (contentNode.current) {
const distance = Math.max(0, drag.y - drag.start);
contentNode.current.style.translate = `0 ${distance}px`;
paintBackdrop(distance, contentNode.current.offsetHeight);
}
}}
onPointerUp={(event) => finishDrag(event.currentTarget, event.pointerId, false)}
onPointerCancel={(event) => finishDrag(event.currentTarget, event.pointerId, true)}
onLostPointerCapture={(event) => finishDrag(event.currentTarget, event.pointerId, true)}
onClick={(event) => { if (suppressClick.current) { event.preventDefault(); suppressClick.current = false; } }}
className={cn("absolute grid place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none", placement === "bottom" ? "left-1/2 top-0 h-8 w-16 -translate-x-1/2 touch-none cursor-grab active:cursor-grabbing" : "right-2.5 top-2.5 h-7 w-7")}>
{placement === "bottom" ? <span aria-hidden="true" className="h-1 w-9 rounded-full bg-current opacity-40" /> : <X className="h-4 w-4" />}
<span className="sr-only">{t("common.close")}</span>
</DialogPrimitive.Close>
) : null}
@@ -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`;
+3 -2
View File
@@ -1,3 +1,4 @@
import { surfaceFocusProps } from "@/lib/surface-focus";
import { useCallback, useEffect, useRef, useState, type PointerEvent } from "react";
import { Minus, Plus } from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -121,8 +122,8 @@ export function ImageViewport({
const buttonClass = "grid size-9 shrink-0 place-items-center rounded-full transition-colors hover:text-foreground disabled:opacity-30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
return <>
<div ref={viewport} data-testid={testId} tabIndex={0} role="group" aria-label={t("lightbox.gestures")}
className={cn("flex min-h-0 min-w-0 touch-none select-none items-center justify-center overflow-hidden focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring", view.scale > 1 ? dragging ? "cursor-grabbing" : "cursor-grab" : "cursor-zoom-in", className)}
<div ref={viewport} data-testid={testId} {...surfaceFocusProps} tabIndex={0} role="group" aria-label={t("lightbox.gestures")}
className={cn("flex min-h-0 min-w-0 touch-none select-none items-center justify-center overflow-hidden outline-none data-[keyboard-focus]:ring-1 data-[keyboard-focus]:ring-ring", view.scale > 1 ? dragging ? "cursor-grabbing" : "cursor-grab" : "cursor-zoom-in", className)}
onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={endPointer} onPointerCancel={endPointer} onLostPointerCapture={endPointer}
onDoubleClick={(event) => zoom(viewRef.current.scale > 1 ? 1 : 2, { x: event.clientX, y: event.clientY })}
onKeyDown={(event) => {
+11 -8
View File
@@ -5,6 +5,7 @@ import { cva, type VariantProps } from "class-variance-authority";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils";
import { modalOverlayClassName, sidePanelSurfaceClassName } from "./floating-surface";
const Sheet = DialogPrimitive.Root;
const SheetTrigger = DialogPrimitive.Trigger;
@@ -29,7 +30,7 @@ const SheetOverlay = React.forwardRef<
SheetOverlay.displayName = DialogPrimitive.Overlay.displayName;
const sheetVariants = cva(
"fixed z-50 flex flex-col gap-4 bg-background outline-none transition ease-in-out",
"fixed z-50 flex flex-col gap-4 bg-background outline-none ease-out",
{
variants: {
side: {
@@ -42,12 +43,14 @@ const sheetVariants = cva(
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
),
left: cn(
"inset-y-0 left-0 h-full w-3/4 sm:max-w-sm",
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left",
"inset-y-2 left-2 w-3/4 max-w-[calc(100vw-1rem)] sm:max-w-sm",
sidePanelSurfaceClassName,
"data-[state=closed]:slide-out-to-left-4 data-[state=open]:slide-in-from-left-4",
),
right: cn(
"inset-y-0 right-0 h-full w-3/4 sm:max-w-sm",
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right",
"inset-y-2 right-2 w-3/4 max-w-[calc(100vw-1rem)] sm:max-w-sm",
sidePanelSurfaceClassName,
"data-[state=closed]:slide-out-to-right-4 data-[state=open]:slide-in-from-right-4",
),
},
},
@@ -83,13 +86,13 @@ const SheetContent = React.forwardRef<
const { t } = useTranslation();
return (
<SheetPortal>
<SheetOverlay className={overlayClassName} />
<SheetOverlay className={cn((side === "right" || side === "left") && modalOverlayClassName, overlayClassName)} />
<DialogPrimitive.Content
ref={ref}
className={cn(
sheetVariants({ side }),
"data-[state=open]:animate-in data-[state=closed]:animate-out",
"duration-300 motion-reduce:transition-none",
"data-[state=open]:fade-in-0 data-[state=closed]:fade-out-0 duration-200 motion-reduce:transition-none",
"motion-reduce:data-[state=open]:animate-none motion-reduce:data-[state=closed]:animate-none",
className,
)}
@@ -99,7 +102,7 @@ const SheetContent = React.forwardRef<
{showCloseButton ? (
<DialogPrimitive.Close
className={cn(
"absolute right-4 top-4 rounded-mark opacity-70 ring-offset-background transition-opacity",
"absolute right-2 top-2 grid size-10 place-items-center rounded-full opacity-70 ring-offset-background transition-opacity",
"hover:opacity-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
"disabled:pointer-events-none",
closeButtonClassName,
+68
View File
@@ -0,0 +1,68 @@
import { createContext, forwardRef, useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type HTMLAttributes, type ReactNode } from "react";
import { useReducedMotion } from "motion/react";
import { cn } from "@/lib/utils";
interface SidebarPanelProps extends HTMLAttributes<HTMLElement> {
header?: ReactNode;
width: number;
isClosing?: boolean;
open?: boolean;
floating?: boolean;
contentClassName?: string;
}
export const SidebarPanelActionsContext = createContext<HTMLElement | null>(null);
/** Retain the same surface through exit, including an interrupted close. */
export const SidebarPanel = forwardRef<HTMLElement, SidebarPanelProps>(function SidebarPanel({
open = true, isClosing, ...props
}, ref) {
const [present, setPresent] = useState(open);
const reducedMotion = useReducedMotion();
useEffect(() => {
if (open) { setPresent(true); return; }
const timer = window.setTimeout(() => setPresent(false), reducedMotion ? 0 : 300);
return () => window.clearTimeout(timer);
}, [open, reducedMotion]);
return open || present ? <SidebarPanelContent {...props} ref={ref} isClosing={isClosing || !open} /> : null;
});
/** Shared nonmodal side slot. Contents keep their final width while the slot opens. */
const SidebarPanelContent = forwardRef<HTMLElement, SidebarPanelProps>(function SidebarPanelContent({
width, isClosing = false, floating = false, header, contentClassName, className, style, children, ...props
}, forwardedRef) {
const panel = useRef<HTMLElement | null>(null);
const [entered, setEntered] = useState(false);
const [actionsHost, setActionsHost] = useState<HTMLElement | null>(null);
const setPanel = useCallback((node: HTMLElement | null) => {
panel.current = node;
if (typeof forwardedRef === "function") forwardedRef(node);
else if (forwardedRef) forwardedRef.current = node;
}, [forwardedRef]);
useLayoutEffect(() => {
// Commit the outgoing slot width before transitioning to the replacement width.
panel.current?.getBoundingClientRect();
let frame = requestAnimationFrame(() => { frame = requestAnimationFrame(() => setEntered(true)); });
return () => cancelAnimationFrame(frame);
}, []);
return <aside {...props} ref={setPanel} data-closing={isClosing || undefined}
style={{
"--file-preview-width": `${width}px`,
"--file-preview-slot-width": isClosing ? "0px" : !entered ? "var(--sidebar-enter-width, 0px)" : `${width}px`,
"--file-preview-mobile-width": isClosing ? "0px" : !entered ? "var(--sidebar-enter-mobile-width, 0px)" : "100%",
...style,
} as CSSProperties}
className={cn("file-preview-pane z-30 min-h-0 w-[var(--file-preview-mobile-width)] overflow-hidden duration-300 ease-[cubic-bezier(0.2,0,0,1)] motion-reduce:transition-none",
entered ? "transition-[width]" : "transition-none",
floating ? "fixed inset-y-2 right-2 max-w-[420px]" : "absolute inset-y-0 right-0", isClosing && "pointer-events-none", className)}>
<div className={cn("file-preview-content absolute inset-y-2 right-2 flex min-h-0 w-[calc(100cqw-1rem)] flex-col pb-[env(safe-area-inset-bottom)] transition-[opacity,transform] duration-200 ease-out motion-reduce:transition-none",
floating && "w-[calc(min(420px,100vw)-1rem)]",
!entered || isClosing ? "translate-x-2 opacity-0" : "translate-x-0 opacity-100", contentClassName)}>
{header && <div className="flex min-h-10 shrink-0 items-center gap-1 border-b border-border/40 px-2 pt-2">
{header}
<div ref={setActionsHost} className="shrink-0" />
</div>}
<SidebarPanelActionsContext.Provider value={actionsHost}>{children}</SidebarPanelActionsContext.Provider>
</div>
</aside>;
});
@@ -25,10 +25,8 @@ import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuLabel,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { HoverHint } from "@/components/ui/tooltip";
@@ -634,10 +632,6 @@ export function PaneWorkbench({
align="end"
onCloseAutoFocus={(event) => event.preventDefault()}
>
<DropdownMenuLabel>
{t("workbench.layout", { defaultValue: "Pane layout" })}
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuRadioGroup
value={layout}
onValueChange={(value) => {
@@ -701,8 +695,8 @@ export function PaneWorkbench({
data-testid="pane-grid"
data-layout={effectiveLayout}
className={cn(
"grid h-full min-h-0 min-w-0 overflow-hidden",
chrome && displayedPanes.length > 1 && "gap-px bg-border/55",
"grid h-full min-h-0 min-w-0 overflow-hidden bg-background",
chrome && displayedPanes.length > 1 && "gap-px",
)}
style={gridStyle}
>
@@ -723,7 +717,10 @@ export function PaneWorkbench({
data-testid={`workbench-pane-${pane.key}`}
onPointerDownCapture={(event) => handlePanePointerDown(pane.key, event)}
onFocusCapture={(event) => handlePaneFocus(pane.key, event)}
className="workbench-pane relative flex min-h-0 min-w-0 overflow-hidden bg-background"
className={cn(
"workbench-pane relative flex min-h-0 min-w-0 overflow-hidden bg-background",
chrome && displayedPanes.length > 1 && "shadow-[0_0_0_1px_hsl(var(--border)/0.55)]",
)}
style={layoutGeometry.paneStyles[index]}
>
{renderPane(pane, {
+2 -2
View File
@@ -65,7 +65,7 @@ function SessionPreview() {
}}>
<StatePicker label={t("previews.session.state")} value={mode} options={["ready", "loading", "error", "empty", "action_error"]}
onChange={(next) => { setMode(next); setJobs(exampleJobs(now)); setAction(null); }} />
<SessionInfoPopoverView title="组件设计" jobs={mode === "ready" || mode === "action_error" ? displayJobs(jobs) : []} loading={mode === "loading"} loadFailed={mode === "error"} now={now}
<SessionInfoPopoverView jobs={mode === "ready" || mode === "action_error" ? displayJobs(jobs) : []} loading={mode === "loading"} loadFailed={mode === "error"} now={now}
onOpenCalendar={() => setAction({ key: "previews.session.openedCalendar" })}
onAction={(operation, job) => {
if (mode === "action_error") return Promise.reject(new Error(t("previews.session.actionError")));
@@ -106,7 +106,7 @@ export const contentExamples: ComponentExample[] = [
code: '<FilePreviewPanelView path={path} state={previewState} imageOpen={imageOpen} onImageOpenChange={setImageOpen} onImageError={reportImageError} />' },
{ title: "previews.session.title", files: ["webui/src/components/thread/SessionInfoPopoverView.tsx"], Preview: SessionPreview,
description: "previews.session.description", options: "previews.session.options",
code: '<SessionInfoPopoverView title={title} jobs={jobs} loading={loading} loadFailed={failed} now={now} onAction={act} onEdit={edit} onOpenCalendar={openCalendar} />' },
code: '<SessionInfoPopoverView jobs={jobs} loading={loading} loadFailed={failed} now={now} onAction={act} onEdit={edit} onOpenCalendar={openCalendar} />' },
{ title: "previews.subagent.title", files: ["webui/src/components/thread/SubagentThreadView.tsx"], Preview: SubagentPreview,
description: "previews.subagent.description", options: "previews.subagent.options",
code: '<SubagentThreadView messages={messages} loading={loading} error={error} isStreaming={running} runStartedAt={startedAt} onRetry={retry} />' },
+23 -6
View File
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
import { FallbackResponseSources } from "@/components/ResponseSourceBadge";
import { AgentActivityCluster } from "@/components/thread/AgentActivityCluster";
import { ComposerUsagePopover, type ComposerRoundUsage } from "@/components/thread/ComposerUsagePopover";
import type { ContextSnapshot } from "@/lib/types";
import { ContextCompactionNotice } from "@/components/thread/ContextCompactionNotice";
import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
import { ModelPresetBadge, type ModelPresetOption } from "@/components/thread/ModelPresetBadge";
@@ -30,9 +31,9 @@ const presets: ModelPresetOption[] = [
{ name: "推理", provider: "anthropic", model: "claude-sonnet-4", reasoningEffort: "high", contextWindowTokens: 200_000 },
];
const rounds: ComposerRoundUsage[] = [
{ id: "gallery-round-1", timestamp: createdAt, inputTokens: 8_200, cachedTokens: 6_000, outputTokens: 620, generationMs: 3_100 },
{ id: "gallery-round-2", timestamp: createdAt + 60_000, inputTokens: 12_000, cachedTokens: 8_200, outputTokens: 980, generationMs: 5_400 },
{ id: "gallery-round-3", timestamp: createdAt + 120_000, inputTokens: 18_500, cachedTokens: 12_000, outputTokens: 1_240, generationMs: 7_200 },
{ inputTokens: 8_200, cachedTokens: 6_000, generationMs: 3_100 },
{ inputTokens: 12_000, cachedTokens: 8_200, generationMs: 5_400 },
{ inputTokens: 18_500, cachedTokens: 12_000, generationMs: 7_200 },
];
const commands: SlashCommand[] = [
{ command: "/status", title: "previews.composer.statusCommand", description: "previews.composer.statusDescription", icon: "activity", lifecycle: "side_channel", acceptsArgs: false },
@@ -102,14 +103,30 @@ function ModelPresetPreview() {
</div>;
}
const contextSnapshots: ContextSnapshot[] = [0, 1, 2].map((round) => ({
id: `context-example-${round}`, contextWindowTokens: 128000,
usage: { prompt_tokens: 28000 + round * 7300, context_tokens: 28000 + round * 7300, cached_tokens: 20000 + round * 7000, generation_ms: 8200 },
graph: {
nodes: [
{ path: "/workspace/MEMORY.md", name: "MEMORY.md", state: "loaded", tokens: 2100 },
{ path: "/workspace/SOUL.md", name: "SOUL.md", state: "loaded", tokens: 380 },
{ path: "/workspace/AGENTS.md", name: "AGENTS.md", state: "loaded", tokens: 1400 },
{ path: "/workspace/skills/nanobot-document/SKILL.md", name: "nanobot-document", state: "loaded", tokens: 550 },
{ path: "/workspace/skills/nanobot-document/references/architecture.md", name: "architecture.md", state: round ? "loaded" : "discovered", tokens: round * 1600 },
{ path: "/workspace/skills/nanobot-document/references/configuration.md", name: "configuration.md", state: "discovered", tokens: 0 },
],
edges: ["architecture.md", "configuration.md"].map((name) => ({ source: "/workspace/skills/nanobot-document/SKILL.md", target: `/workspace/skills/nanobot-document/references/${name}` })),
},
}));
function UsagePreview() {
const { t } = useGalleryTranslation();
const [mode, setMode] = useState<"normal" | "caution" | "critical" | "rounds_only" | "sheet">("normal");
const [mode, setMode] = useState<"normal" | "caution" | "critical" | "rounds_only">("normal");
const tokens = mode === "critical" ? 192_000 : mode === "caution" ? 162_000 : 18_500;
return <div className="space-y-4">
<StatePicker label={t("previews.usage.state")} value={mode} options={["normal", "caution", "critical", "rounds_only", "sheet"]} onChange={setMode} />
<StatePicker label={t("previews.usage.state")} value={mode} options={["normal", "caution", "critical", "rounds_only"]} onChange={setMode} />
<ComposerUsagePopover context={mode === "rounds_only" ? null : { contextTokens: tokens, contextWindowTokens: 200_000 }}
rounds={rounds} showLabel bottomSheet={mode === "sheet"} />
rounds={rounds} snapshots={contextSnapshots} showLabel />
<p className="text-sm text-muted-foreground">{t("previews.usage.hint")}</p>
</div>;
}
+17
View File
@@ -1,4 +1,5 @@
import { useState } from "react";
import { SidebarPanel } from "@/components/ui/sidebar-panel";
import { Plus } from "lucide-react";
import { Button } from "@/components/ui/button";
@@ -250,7 +251,23 @@ function ImageViewports() {
}
const base = "webui/src/components/ui/";
function Sidebars() {
const { t } = useGalleryTranslation();
const [open, setOpen] = useState(true);
return <div className="space-y-3">
<Button onClick={() => setOpen(!open)}>{t("controls.sidebarPanel.toggle")}</Button>
<div className="thread-preview-layout relative h-64 overflow-hidden rounded-xl border">
{open && <SidebarPanel width={320} header={<span>{t("controls.sidebarPanel.title")}</span>}>
<p className="p-4 text-sm">{t("controls.sidebarPanel.content")}</p>
</SidebarPanel>}
</div>
</div>;
}
export const foundationExamples: ComponentExample[] = [
{ title: "controls.sidebarPanel.title", files: ["sidebar-panel"], Preview: Sidebars,
description: "controls.sidebarPanel.description", options: "controls.sidebarPanel.options",
code: '<SidebarPanel width={320} header={<span>Details</span>}>{children}</SidebarPanel>' },
{ title: "controls.button.title", files: ["button"], Preview: Buttons,
description: "controls.button.description",
options: "controls.button.options",
@@ -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"
}
}
@@ -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"
}
}
@@ -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"
}
}
@@ -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"
}
}
@@ -504,5 +504,12 @@
"view": "招待を表示",
"dismissed": "プレビューで今後表示しないを選択しました",
"starred": "プレビューで GitHub リンクを選択しました"
},
"sidebarPanel": {
"title": "サイドパネル",
"toggle": "パネルの表示を切り替え",
"content": "詳細は現在のペイン内に表示されます。",
"description": "共通の開くアニメーションを持つ非モーダルのサイドパネル。",
"options": "width, header, isClosing, floating, contentClassName"
}
}
@@ -504,5 +504,12 @@
"view": "안내 보기",
"dismissed": "미리보기에서 다시 알리지 않기를 선택했습니다",
"starred": "미리보기에서 GitHub 링크를 선택했습니다"
},
"sidebarPanel": {
"title": "사이드 패널",
"toggle": "패널 표시 전환",
"content": "세부 정보는 현재 창 안에 표시됩니다.",
"description": "공통 열기 전환 효과를 사용하는 비모달 사이드 패널입니다.",
"options": "width, header, isClosing, floating, contentClassName"
}
}
@@ -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"
}
}
@@ -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"
}
}
@@ -504,5 +504,12 @@
"view": "查看邀请",
"dismissed": "预览中选择了不再提醒",
"starred": "预览中选择了 GitHub 链接"
},
"sidebarPanel": {
"title": "侧边面板",
"toggle": "切换侧边面板",
"content": "详情保留在当前窗格内。",
"description": "非模态侧边面板,使用统一的展开动画。",
"options": "width, header, isClosing, floating, contentClassName"
}
}
@@ -504,5 +504,12 @@
"view": "查看邀請",
"dismissed": "已在預覽中選取不再提醒",
"starred": "已在預覽中選取 GitHub 連結"
},
"sidebarPanel": {
"title": "側邊面板",
"toggle": "切換側邊面板",
"content": "詳細資訊保留在目前的窗格內。",
"description": "非模態側邊面板,使用統一的展開動畫。",
"options": "width, header, isClosing, floating, contentClassName"
}
}
+61 -7
View File
@@ -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 {
+12 -9
View File
@@ -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": {
+12 -9
View File
@@ -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",
+12 -9
View File
@@ -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",
+12 -9
View File
@@ -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",
+12 -9
View File
@@ -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": "思考しました",
+12 -9
View File
@@ -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": "생각함",
+12 -9
View File
@@ -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": {
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff. Show more