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

+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),
])