fix(sessions): preserve cross-session input ownership and history (#6613)
* fix(webui): reconcile cross-session history by message ID * fix(sessions): preserve target authority and input ownership Resolve cross-session follow-ups through the target route, carry stable input IDs through admission and recovery, and associate live and replayed answers with the inputs actually consumed. Keep ordinary input scope isolation and omit historical anomaly repair. Resolves NAN-430. * fix(sessions): complete input identity integration across boundaries Carry input identity explicitly in projected input events, keep runner annotations out of public history, and reuse the canonical WebUI session parser during recovery. Type validated recovery metadata and align existing channel and subagent regressions with explicit response ownership. All nine failed compatibility cases and adjacent recovery coverage pass in a focused 58-test run. * fix(sessions): unify input recording and block remote commands * fix(webui): keep input ownership checks page-bounded Look up referenced inputs through the existing identity index before invoking transcript backfill. Complete pages no longer scan the full prompt history, including answers whose inputs live on earlier pages. Cover cold-cache pagination and cross-turn ownership in existing regressions. Focused pagination, replay and follow-up recovery checks: 88 passed. * fix(webui): preserve response ownership during history replay * fix: resolve strict typing in response replay * fix: preserve continuation ownership during recovery * test: diagnose stuck gateway asyncio shutdown * test: retain gateway thread stack diagnostics * test(webui): stabilize native autoscroll browser setup
This commit is contained in:
1 parent
0ce335bf12
commit
394a78e82d
51 files changed
+1412
-334
No files matched your search
@@ -819,6 +819,7 @@ class TestToolEventProgress:
|
||||
chat_id="chat-a",
|
||||
content="Can you include the key detail?",
|
||||
session_key_override=session_key,
|
||||
metadata={WEBUI_TURN_METADATA_KEY: "followup"},
|
||||
))
|
||||
release_first_request.set()
|
||||
# Events synchronize injection; the deadline only guards against a stuck worker.
|
||||
@@ -855,6 +856,11 @@ class TestToolEventProgress:
|
||||
for message in outbound
|
||||
if isinstance(message.event, StreamDeltaEvent)
|
||||
] == ["Checking", "The late result is ready"]
|
||||
assert [
|
||||
message.metadata["response_input_ids"]
|
||||
for message in outbound
|
||||
if isinstance(message.event, StreamDeltaEvent)
|
||||
] == [[], ["user:followup"]]
|
||||
assert any(isinstance(message.event, ProgressEvent) for message in outbound)
|
||||
assert len([
|
||||
message for message in outbound if isinstance(message.event, TurnEndEvent)
|
||||
@@ -902,6 +908,7 @@ class TestToolEventProgress:
|
||||
WEBUI_TURN_METADATA_KEY,
|
||||
"_history_generation",
|
||||
"latency_ms",
|
||||
"response_input_ids",
|
||||
}
|
||||
for message in visible_events
|
||||
)
|
||||
|
||||
@@ -13,6 +13,7 @@ from nanobot.agent.turn_delivery import TurnDeliveryFactory
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest
|
||||
from nanobot.providers.openai_compat_provider import OpenAICompatProvider
|
||||
from nanobot.runtime_context import public_history_message
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.recovery import (
|
||||
@@ -71,7 +72,7 @@ async def test_committed_model_failure_continues_with_tool_results_without_resen
|
||||
monkeypatch.setattr(read_tool, "execute", execute)
|
||||
request = InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="chat", content="Read the note and summarize it",
|
||||
metadata={"webui": True, "webui_turn_id": "request-1"},
|
||||
metadata={"webui": True, "webui_turn_id": "request-1", "message_id": "original-input"},
|
||||
)
|
||||
try:
|
||||
with coordinator.connected():
|
||||
@@ -83,9 +84,20 @@ async def test_committed_model_failure_continues_with_tool_results_without_resen
|
||||
await loop._dispatch_one(bus.inbound.get_nowait(), asyncio.Queue())
|
||||
final = await sessions.state.get(request.session_key)
|
||||
assert final.metadata[RECOVERY_METADATA_KEY]["status"] == "recovered"
|
||||
answer = next(row for row in final.messages if row.get("content") == "Finished from the saved result.")
|
||||
user = next(row for row in final.messages if row.get("role") == "user")
|
||||
assert user["input_id"]
|
||||
assert answer["response_input_ids"] == [user["input_id"]]
|
||||
assert execute.await_count == 1
|
||||
assert sum(message.get("role") == "user" for message in final.messages) == 1
|
||||
assert any(message.get("role") == "tool" and "saved evidence" in message["content"] for message in requests[-1]["messages"])
|
||||
continuation = requests[-1]["messages"][-1]
|
||||
assert continuation["_hidden_history"] == {"kind": "internal_continuation"}
|
||||
# The marker is runner bookkeeping, not part of an OpenAI-compatible wire request.
|
||||
wire_messages = OpenAICompatProvider._sanitize_messages(
|
||||
OpenAICompatProvider(api_key="test"), requests[-1]["messages"], model="test-model",
|
||||
)
|
||||
assert all("_hidden_history" not in row for row in wire_messages)
|
||||
assert requests[0]["messages"][0] == requests[-1]["messages"][0]
|
||||
assert requests[0]["tools"] == requests[-1]["tools"]
|
||||
assert requests[-1]["messages"][:len(requests[1]["messages"])] == requests[1]["messages"]
|
||||
@@ -542,3 +554,80 @@ async def test_new_input_waits_for_real_recovery_cancellation_before_reading_dra
|
||||
assert RUNTIME_CHECKPOINT_KEY not in saved.metadata
|
||||
finally:
|
||||
await reopened.state.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_length_recovery_retains_original_prompt_attribution(tmp_path: Path, history) -> None:
|
||||
bus = MessageBus()
|
||||
sessions = history.sessions
|
||||
session = sessions.get_or_create("websocket:chat")
|
||||
session.metadata["title"] = "Saved recovery"
|
||||
sessions.save(session)
|
||||
recovery = RecoveryCoordinator(sessions, bus)
|
||||
provider = MagicMock(aclose=AsyncMock())
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.generation = GenerationSettings()
|
||||
provider.can_resume_conversation_state.return_value = False
|
||||
requests = []
|
||||
responses = iter([
|
||||
LLMResponse(content=None, reasoning_content="thinking", finish_reason="length"),
|
||||
LLMResponse(content="network failure", finish_reason="error", error_kind="connection"),
|
||||
LLMResponse(content="Recovered answer"),
|
||||
])
|
||||
|
||||
async def respond(**kwargs):
|
||||
requests.append(deepcopy(kwargs["messages"]))
|
||||
return next(responses)
|
||||
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
|
||||
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path, model="test-model",
|
||||
session_manager=sessions, recovery_admission=recovery)
|
||||
loop.turn_delivery_factory = TurnDeliveryFactory(bus, WebuiTurnRoutePolicy(sessions))
|
||||
coordinator = WebuiTurnCoordinator(bus, sessions, loop.schedule_background, recovery=recovery)
|
||||
request = InboundMessage(channel="websocket", sender_id="user", chat_id="chat", content="Original question",
|
||||
metadata={"webui": True, "webui_turn_id": "original", "message_id": "original"})
|
||||
recorder = WebUITranscriptRecorder(sessions)
|
||||
try:
|
||||
await recorder.prepare_and_append("chat", {"event": "user", "chat_id": "chat", "text": request.content},
|
||||
metadata=await history.metadata("chat", request.metadata))
|
||||
with coordinator.connected():
|
||||
await loop._dispatch_one(request, asyncio.Queue())
|
||||
state = (await sessions.state.get(request.session_key)).metadata[RECOVERY_METADATA_KEY]
|
||||
assert state["status"] == "awaiting_user"
|
||||
persisted = SessionManager(tmp_path).get_or_create(request.session_key)
|
||||
assert any(row.get("_hidden_history") == {"kind": "internal_continuation"} for row in persisted.messages)
|
||||
await recovery.handle_action("continue", {"chat_id": "chat", "recovery_id": state["recovery_id"]})
|
||||
await loop._dispatch_one(bus.inbound.get_nowait(), asyncio.Queue())
|
||||
final = SessionManager(tmp_path).get_or_create(request.session_key)
|
||||
answer = next(row for row in final.messages if row.get("content") == "Recovered answer")
|
||||
assert answer["response_input_ids"] == ["user:original"]
|
||||
outbound = [bus.outbound.get_nowait() for _ in range(bus.outbound.qsize())]
|
||||
delivered = next(row for row in outbound if row.content == "Recovered answer")
|
||||
await recorder.prepare_and_append("chat", {"event": "message", "chat_id": "chat", "text": delivered.content},
|
||||
metadata=await history.metadata("chat", delivered.metadata), include_source=True)
|
||||
assert history.prompts(request.session_key)[0]["answerPreview"] == "Recovered answer"
|
||||
wire = OpenAICompatProvider._sanitize_messages(OpenAICompatProvider(api_key="test"), requests[-1], model="test-model")
|
||||
assert all("_hidden_history" not in row for row in wire)
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
def test_persisted_automation_input_blocks_prior_prompt_attribution(tmp_path: Path) -> None:
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
from nanobot.session.automation_turns import AUTOMATION_HISTORY_META
|
||||
|
||||
sessions = SessionManager(tmp_path)
|
||||
session = sessions.get_or_create("websocket:chat")
|
||||
session.add_message("user", "Original question", input_id="user:original")
|
||||
session.add_message("assistant", "Original answer")
|
||||
session.add_message("user", "Scheduled task", **{AUTOMATION_HISTORY_META: True})
|
||||
session.add_message("assistant", "Thinking", reasoning_content="thinking")
|
||||
session.add_message("user", "Continue", _hidden_history={"kind": "internal_continuation"})
|
||||
sessions.save(session)
|
||||
replay = SessionManager(tmp_path).get_or_create("websocket:chat").get_history()
|
||||
assert AgentRunner._response_input_ids(replay) == ()
|
||||
assert replay[-1]["_hidden_history"] == {"kind": "internal_continuation"}
|
||||
public = session.get_history(include_runtime_context=False)
|
||||
assert all("_hidden_history" not in row for row in public)
|
||||
wire = OpenAICompatProvider._sanitize_messages(OpenAICompatProvider(api_key="test"), replay, model="test-model")
|
||||
assert all("_hidden_history" not in row and AUTOMATION_HISTORY_META not in row for row in wire)
|
||||
@@ -654,6 +654,7 @@ async def test_runner_uses_no_tools_finalization_after_max_iterations():
|
||||
assert result.messages[-1] == {
|
||||
"role": "assistant",
|
||||
"content": "Read the directory twice. More investigation remains.",
|
||||
"_meta": {"response_input_ids": []},
|
||||
}
|
||||
assert len(calls) == 3
|
||||
assert calls[-1]["tools"] is None
|
||||
@@ -718,7 +719,7 @@ async def test_runner_accounts_for_malformed_retry_and_no_tools_recovery():
|
||||
assert result.stop_reason == "completed"
|
||||
assert result.messages == [
|
||||
{"role": "user", "content": "do task"},
|
||||
{"role": "assistant", "content": "recovered answer"},
|
||||
{"role": "assistant", "content": "recovered answer", "_meta": {"response_input_ids": []}},
|
||||
]
|
||||
assert [item["tools"] for item in calls] == [definitions, definitions, None]
|
||||
assert ["on_content_delta" in item for item in calls] == [True, True, False]
|
||||
@@ -986,7 +987,7 @@ async def test_runner_length_recovery_returns_all_segments():
|
||||
|
||||
runner = AgentRunner()
|
||||
result = await runner.run(make_run_spec(provider,
|
||||
initial_messages=[{"role": "user", "content": "give a long answer"}],
|
||||
initial_messages=[{"role": "user", "content": "give a long answer", "_meta": {"input_id": "long"}}],
|
||||
tools=tools,
|
||||
model="test-model",
|
||||
max_iterations=5,
|
||||
@@ -1000,6 +1001,7 @@ async def test_runner_length_recovery_returns_all_segments():
|
||||
if message.get("role") == "assistant"
|
||||
] == ["first", "second", "third"]
|
||||
assert provider.chat_stream_with_retry.await_count == 3
|
||||
assert [m["_meta"]["response_input_ids"] for m in result.messages if m.get("role") == "assistant"] == [["long"]] * 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1243,3 +1245,79 @@ async def test_runner_passes_generation_settings_to_provider():
|
||||
assert captured["temperature"] == 0.3
|
||||
assert captured["max_tokens"] == 8192
|
||||
assert captured["reasoning_effort"] == "high"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("automated", [False, True])
|
||||
async def test_runner_continuation_preserves_request_ownership(automated):
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
LLMResponse(content="first"), LLMResponse(content="continued"),
|
||||
])
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
inputs = [
|
||||
{"role": "user", "content": "old", "_meta": {"input_id": "old"}},
|
||||
{"role": "assistant", "content": "old answer"},
|
||||
({"role": "user", "content": "scheduled", "_automation_turn": True}
|
||||
if automated else {"role": "user", "content": "new", "_meta": {"input_id": "new"}}),
|
||||
]
|
||||
result = await AgentRunner().run(make_run_spec(
|
||||
provider, initial_messages=inputs, tools=tools, model="test-model",
|
||||
max_iterations=2, max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
continuation_callback=AsyncMock(side_effect=["Continue", None]),
|
||||
))
|
||||
answers = [m for m in result.messages if m.get("role") == "assistant"][-2:]
|
||||
assert [m["_meta"]["response_input_ids"] for m in answers] == (
|
||||
[[], []] if automated else [["new"], ["new"]]
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("automated", [False, True])
|
||||
async def test_interrupted_output_ownership_survives_persistence_and_later_checkpoint(tmp_path, automated):
|
||||
from nanobot.agent.hook import AgentHook
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
from nanobot.session.message_metadata import persisted_message
|
||||
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
calls = 0
|
||||
|
||||
async def chat_stream_with_retry(**kwargs):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
if calls == 1:
|
||||
await kwargs["on_content_delta"]("partial")
|
||||
return LLMResponse(content="failed", finish_reason="error")
|
||||
return LLMResponse(content="done")
|
||||
|
||||
provider.chat_stream_with_retry = chat_stream_with_retry
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
hook = AgentHook()
|
||||
hook.wants_streaming = MagicMock(return_value=True)
|
||||
checkpoints = []
|
||||
async def checkpoint(payload):
|
||||
checkpoints.append(payload)
|
||||
|
||||
initial = [{"role": "user", "content": "task", **(
|
||||
{"_automation_turn": True} if automated else {"_meta": {"input_id": "input-1"}}
|
||||
)}]
|
||||
# An injection after the failed request makes the next request and its checkpoint reachable.
|
||||
injection = {"role": "user", "content": "follow up", "_meta": {"input_id": "next"}}
|
||||
drain = AsyncMock(side_effect=[[], [], [injection], [], [], []])
|
||||
result = await AgentRunner().run(make_run_spec(
|
||||
provider, initial_messages=initial, tools=tools, model="test-model",
|
||||
max_iterations=3, max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
hook=hook, checkpoint_callback=checkpoint, injection_callback=drain,
|
||||
))
|
||||
interrupted = next(m for m in result.messages if m.get("_interrupted"))
|
||||
assert interrupted["_meta"]["response_input_ids"] == ([] if automated else ["input-1"])
|
||||
manager = SessionManager(tmp_path)
|
||||
manager.save(Session(key="cli:ownership", messages=[persisted_message(m) for m in result.messages]))
|
||||
loaded = manager.read_session_snapshot("cli:ownership")
|
||||
persisted_interrupted = next(m for m in loaded.messages if m.get("_interrupted"))
|
||||
assert persisted_interrupted == persisted_message(interrupted)
|
||||
assert persisted_interrupted["response_input_ids"] == ([] if automated else ["input-1"])
|
||||
assert any(interrupted in cp["preceding_messages"] for cp in checkpoints)
|
||||
@@ -611,16 +611,12 @@ async def test_checkpoint2_preserves_final_response_in_history_before_followup()
|
||||
assert call_count["n"] == 2
|
||||
assert captured_messages[-1] == [
|
||||
{"role": "user", "content": "hello"},
|
||||
{"role": "assistant", "content": "first answer"},
|
||||
{"role": "assistant", "content": "first answer", "_meta": {"response_input_ids": []}},
|
||||
{"role": "user", "content": "follow-up question"},
|
||||
]
|
||||
assert [
|
||||
{"role": message["role"], "content": message["content"]}
|
||||
for message in result.messages
|
||||
if message.get("role") == "assistant"
|
||||
] == [
|
||||
{"role": "assistant", "content": "first answer"},
|
||||
{"role": "assistant", "content": "second answer"},
|
||||
assert [message for message in result.messages if message.get("role") == "assistant"] == [
|
||||
{"role": "assistant", "content": "first answer", "_meta": {"response_input_ids": []}},
|
||||
{"role": "assistant", "content": "second answer", "_meta": {"response_input_ids": []}},
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -12,12 +12,19 @@ from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.outbound_events import UserInputEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import UserInputAccepted
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
|
||||
from nanobot.providers.base import LLMResponse
|
||||
from nanobot.runtime_context import public_history_message
|
||||
from nanobot.security.workspace_access import current_workspace_scope
|
||||
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
|
||||
from nanobot.session.recovery import PENDING_FOLLOWUPS_KEY
|
||||
from nanobot.session.session_handles import SessionHandleResolver
|
||||
from nanobot.session.session_messages import SESSION_MESSAGE_METADATA_KEY
|
||||
from nanobot.session.webui_turns import WebuiTurnCoordinator
|
||||
from nanobot.session.webui_turns import WebuiTurnCoordinator, WebuiTurnRoutePolicy
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
from nanobot.webui.history import record_from_fact
|
||||
from nanobot.webui.transcript import build_prompt_index, build_webui_thread_response
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -147,14 +154,19 @@ async def test_path_followup_reaches_running_turn(loop: AgentLoop) -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("message_count", [1, 2], ids=["idle", "active"])
|
||||
@pytest.mark.parametrize("message_count", [1, 3], ids=["idle", "batched-followups"])
|
||||
async def test_cross_session_input_preserves_source_in_live_events_and_history(
|
||||
loop: AgentLoop, message_count: int,
|
||||
loop: AgentLoop, message_count: int, tmp_path: Path,
|
||||
) -> None:
|
||||
source_key, target_key = "websocket:source", "websocket:target"
|
||||
project = tmp_path / "target-project"
|
||||
project.mkdir()
|
||||
target_scope = {"project_path": str(project), "access_mode": "restricted"}
|
||||
await loop.sessions.state.get(source_key)
|
||||
await loop.sessions.state.get(target_key)
|
||||
await loop.sessions.state.mutate_metadata(target_key, lambda metadata: metadata.update(webui=True))
|
||||
await loop.sessions.state.mutate_metadata(
|
||||
target_key, lambda metadata: metadata.update(webui=True, workspace_scope=target_scope),
|
||||
)
|
||||
handles = SessionHandleResolver(loop.sessions)
|
||||
source = await handles.ahandle_for_session(source_key)
|
||||
destination = await handles.ahandle_for_session(target_key)
|
||||
@@ -170,11 +182,15 @@ async def test_cross_session_input_preserves_source_in_live_events_and_history(
|
||||
loop.bus.publish_outbound = AsyncMock()
|
||||
started, release = asyncio.Event(), asyncio.Event()
|
||||
|
||||
observed_scopes = []
|
||||
|
||||
async def respond(**kwargs):
|
||||
observed_scopes.append(current_workspace_scope())
|
||||
started.set()
|
||||
await release.wait()
|
||||
return LLMResponse(content="Reviewed", tool_calls=[], usage=None)
|
||||
|
||||
loop.runner.run = AsyncMock(wraps=loop.runner.run)
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
|
||||
run = asyncio.create_task(loop.run())
|
||||
try:
|
||||
@@ -190,6 +206,10 @@ async def test_cross_session_input_preserves_source_in_live_events_and_history(
|
||||
while len(accepted) < index + 1:
|
||||
await asyncio.sleep(0)
|
||||
await asyncio.wait_for(started.wait(), 3)
|
||||
if index:
|
||||
async with asyncio.timeout(3):
|
||||
while loop._pending_queues[target_key].empty():
|
||||
await asyncio.sleep(0)
|
||||
release.set()
|
||||
await asyncio.wait_for(
|
||||
asyncio.gather(*loop._active_tasks[target_key]), 5,
|
||||
@@ -209,10 +229,151 @@ async def test_cross_session_input_preserves_source_in_live_events_and_history(
|
||||
inputs = [record for record in records if record.get("event") == "user"]
|
||||
assert [record["text"] for record in inputs] == [f"Review {i}" for i in range(message_count)]
|
||||
assert all(record["session_message"]["session"] == provenance for record in inputs)
|
||||
loop.provider.chat_stream_with_retry.assert_awaited()
|
||||
assert [record["created_at_ms"] for record in inputs] == [event.created_at_ms for event in events]
|
||||
session = await loop.sessions.state.get(target_key)
|
||||
stored_inputs = [row for row in session.messages if row.get("role") == "user"]
|
||||
assert [row["session_message"] for row in stored_inputs] == [
|
||||
event.provenance["session_message"] for event in events
|
||||
]
|
||||
assert [row["input_id"] for row in stored_inputs] == [row["input_id"] for row in inputs] == [event.input_id for event in events]
|
||||
assert [scope.metadata() for scope in observed_scopes] == [target_scope] * min(message_count, 2)
|
||||
assert all(scope.source_channel == "websocket" for scope in observed_scopes)
|
||||
response = next(call.args[0] for call in reversed(loop.bus.publish_outbound.await_args_list)
|
||||
if call.args[0].content == "Reviewed")
|
||||
assert response.metadata["response_input_ids"] == [row["input_id"] for row in stored_inputs[0 if message_count == 1 else 1:]]
|
||||
loop.runner.run.assert_awaited_once()
|
||||
assert PENDING_FOLLOWUPS_KEY not in session.metadata
|
||||
finally:
|
||||
release.set()
|
||||
disconnect()
|
||||
disconnect_accepted()
|
||||
run.cancel()
|
||||
await asyncio.gather(run, return_exceptions=True)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_busy_cross_session_input_uses_target_scope_and_keeps_its_answer(loop: AgentLoop, tmp_path: Path) -> None:
|
||||
source_key, target_key = "websocket:source", "websocket:target"
|
||||
await loop.sessions.state.get(source_key)
|
||||
await loop.sessions.state.get(target_key)
|
||||
await loop.sessions.state.mutate_metadata(target_key, lambda metadata: metadata.update(webui=True))
|
||||
handles = SessionHandleResolver(loop.sessions)
|
||||
destination = await handles.ahandle_for_session(target_key)
|
||||
assert destination is not None
|
||||
tool = SendSessionMessageTool(sessions=loop.sessions, bus=loop.bus)
|
||||
coordinator = WebuiTurnCoordinator(
|
||||
bus=loop.bus, sessions=loop.sessions,
|
||||
schedule_background=lambda coro: coro.close(),
|
||||
)
|
||||
disconnect = coordinator.subscribe()
|
||||
accepted = []
|
||||
disconnect_accepted = loop.bus.subscribe(accepted.append, UserInputAccepted)
|
||||
project = tmp_path / "target-project"
|
||||
project.mkdir()
|
||||
target_scope = {"project_path": str(project), "access_mode": "restricted"}
|
||||
await loop.sessions.state.mutate_metadata(
|
||||
target_key, lambda metadata: metadata.update(workspace_scope=target_scope),
|
||||
)
|
||||
config = WebSocketConfig()
|
||||
gateway = build_gateway_services(
|
||||
config=config, bus=loop.bus, session_manager=loop.sessions,
|
||||
static_dist_path=None, workspace_path=tmp_path, config_path=tmp_path / "config.json",
|
||||
default_restrict_to_workspace=False, runtime_model_name=None,
|
||||
runtime_surface="browser", runtime_capabilities_overrides=None,
|
||||
)
|
||||
channel = WebSocketChannel(config, loop.bus, gateway=gateway)
|
||||
async def deliver(msg):
|
||||
await ChannelManager._send_once(channel, msg)
|
||||
|
||||
loop.bus.publish_outbound = AsyncMock(side_effect=deliver)
|
||||
policy = WebuiTurnRoutePolicy(loop.sessions)
|
||||
loop.turn_delivery_factory.route_policy = policy
|
||||
loop.turn_delivery_factory.route_admission = policy.admit
|
||||
loop.runner.run = AsyncMock(wraps=loop.runner.run)
|
||||
metadata = {"webui": True, "webui_turn_id": "original", "_wants_stream": True,
|
||||
HISTORY_GENERATION_METADATA_KEY: (await loop.sessions.state.get(target_key)).generation}
|
||||
await gateway.transcripts.append_user_message("target", "Original question", metadata=metadata)
|
||||
started, release = asyncio.Event(), asyncio.Event()
|
||||
calls = []
|
||||
|
||||
async def respond(**kwargs):
|
||||
calls.append(current_workspace_scope())
|
||||
content = f"Answer {len(calls)}"
|
||||
await kwargs["on_content_delta"](content)
|
||||
if len(calls) == 1:
|
||||
started.set()
|
||||
await release.wait()
|
||||
return LLMResponse(content=content, tool_calls=[], usage=None)
|
||||
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
|
||||
run = asyncio.create_task(loop.run())
|
||||
try:
|
||||
await loop.bus.publish_inbound(InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="target", content="Original question",
|
||||
metadata=metadata,
|
||||
))
|
||||
await asyncio.wait_for(started.wait(), 3)
|
||||
with request_context(RequestContext(
|
||||
channel="websocket", chat_id="source", session_key=source_key,
|
||||
)):
|
||||
await tool.execute(to=destination.name, content="Review", expect_reply=False)
|
||||
async with asyncio.timeout(3):
|
||||
while len(accepted) < 2 or loop._pending_queues[target_key].empty():
|
||||
await asyncio.sleep(0)
|
||||
release.set()
|
||||
await asyncio.wait_for(asyncio.gather(*loop._active_tasks[target_key]), 5)
|
||||
|
||||
assert [scope.metadata() for scope in calls] == [target_scope, target_scope]
|
||||
assert all(scope.source_channel == "websocket" for scope in calls)
|
||||
loop.runner.run.assert_awaited_once()
|
||||
session = await loop.sessions.state.get(target_key)
|
||||
stored = [row for row in session.messages if row.get("role") == "user"]
|
||||
assert [public_history_message(row)["content"] for row in stored] == ["Original question", "Review"]
|
||||
records = await loop.sessions.state.project_history(
|
||||
target_key,
|
||||
lambda history: [record_from_fact(fact, target_key) for fact in history.all_facts()],
|
||||
)
|
||||
displayed = next(row for row in records if row.get("session_message"))
|
||||
assert stored[1]["session_message"] == displayed["session_message"]
|
||||
assert stored[1]["input_id"] == displayed["input_id"]
|
||||
answers = [row for row in records if row.get("event") == "stream_end"]
|
||||
assert [row["response_input_ids"] for row in answers] == [[row["input_id"]] for row in stored]
|
||||
prompts, page = await loop.sessions.state.project_history(target_key, lambda history: (
|
||||
build_prompt_index(target_key, history=history, session_messages_loader=lambda: session.messages),
|
||||
build_webui_thread_response(target_key, history=history, session_messages=session.messages),
|
||||
))
|
||||
assert [prompt["answerPreview"] for prompt in prompts] == ["Answer 1", "Answer 2"]
|
||||
users = [row for row in page["events"] if row["event"] == "user_message"]
|
||||
assert [row["text"] for row in users] == ["Original question", "Review"]
|
||||
assert [row["input_id"] for row in users] == [row["input_id"] for row in stored]
|
||||
assert PENDING_FOLLOWUPS_KEY not in session.metadata
|
||||
finally:
|
||||
release.set()
|
||||
disconnect()
|
||||
disconnect_accepted()
|
||||
run.cancel()
|
||||
await asyncio.gather(run, return_exceptions=True)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("expect_reply", [True, False])
|
||||
@pytest.mark.parametrize("disabled", [True, False])
|
||||
async def test_session_message_source_context_independent_of_tool_policy(
|
||||
loop: AgentLoop, expect_reply: bool, disabled: bool,
|
||||
) -> None:
|
||||
from nanobot.session.manager import SessionPolicy
|
||||
|
||||
session = loop.sessions.get_or_create("telegram:target")
|
||||
loop.sessions.save(session)
|
||||
await loop.sessions.state.set_policy(
|
||||
"telegram:target",
|
||||
SessionPolicy(disabled_tools=frozenset({"send_session_message"}) if disabled else frozenset()),
|
||||
)
|
||||
msg = _message("Please review this")
|
||||
msg.metadata[SESSION_MESSAGE_METADATA_KEY]["expect_reply"] = expect_reply
|
||||
await loop._process_message(msg)
|
||||
messages = loop.provider.chat_stream_with_retry.await_args.kwargs["messages"]
|
||||
content = next(row["content"] for row in reversed(messages) if row.get("role") == "user")
|
||||
assert content.startswith("Please review this")
|
||||
assert content.count("Message from @luma.") == 1
|
||||
assert ("Reply with send_session_message." in content) is expect_reply
|
||||
@@ -458,6 +458,7 @@ def test_get_history_does_not_duplicate_persisted_cli_app_runtime_context():
|
||||
"entry_point": "cli-anything-drawio",
|
||||
}],
|
||||
RUNTIME_CONTEXT_HISTORY_META: marker,
|
||||
"input_id": "user:cli-app",
|
||||
})
|
||||
|
||||
model_history = session.get_history(max_messages=500)
|
||||
@@ -466,7 +467,7 @@ def test_get_history_does_not_duplicate_persisted_cli_app_runtime_context():
|
||||
include_runtime_context=False,
|
||||
)
|
||||
|
||||
assert model_history == [{"role": "user", "content": content}]
|
||||
assert model_history == [{"role": "user", "content": content, "_meta": {"input_id": "user:cli-app"}}]
|
||||
assert model_history[0]["content"].count("CLI App Attachment: @drawio") == 1
|
||||
assert public_history == [{"role": "user", "content": "please use @drawio"}]
|
||||
|
||||
|
||||
@@ -263,7 +263,7 @@ async def test_default_loop_keeps_slack_thread_for_late_subagent_result(
|
||||
assert initial_reply.metadata["slack"] == slack_route
|
||||
assert saved_route == {"channel": "slack", "chat_id": "C1", "metadata": thread_metadata}
|
||||
assert (late_reply.channel, late_reply.chat_id) == ("slack", "C1")
|
||||
assert late_reply.metadata == thread_metadata
|
||||
assert late_reply.metadata == {**thread_metadata, "response_input_ids": []}
|
||||
finally:
|
||||
release_child.set()
|
||||
loop.stop()
|
||||
|
||||
@@ -18,6 +18,7 @@ from nanobot.session.recovery import (
|
||||
pending_followups,
|
||||
restore_runtime_checkpoint,
|
||||
)
|
||||
from nanobot.session.session_messages import SESSION_MESSAGE_METADATA_KEY
|
||||
from nanobot.webui.recovery import RecoveryCoordinator
|
||||
|
||||
|
||||
@@ -148,7 +149,8 @@ async def test_recovered_input_keeps_admission_identity_and_timestamp(tmp_path):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("interrupt", [False, True], ids=["completed", "checkpoint-recovery"])
|
||||
async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit(tmp_path, monkeypatch, interrupt):
|
||||
@pytest.mark.parametrize("cross_session", [False, True])
|
||||
async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit(tmp_path, monkeypatch, interrupt, cross_session):
|
||||
import asyncio
|
||||
|
||||
provider = MagicMock(aclose=AsyncMock())
|
||||
@@ -173,12 +175,19 @@ async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit
|
||||
draft = await loop.sessions.state.get("websocket:chat")
|
||||
draft.add_message(
|
||||
"user", "intentionally identical text", **{INBOUND_META_TURN_ID: "initial-input"},
|
||||
timestamp="2026-10-18T19:00:00",
|
||||
timestamp="2026-10-18T19:00:00", input_id="user:initial-input",
|
||||
)
|
||||
await loop.sessions.state.prepare_input(draft)
|
||||
queue = asyncio.Queue()
|
||||
for turn_id in ("first-input", "second-input"):
|
||||
message = _input("intentionally identical text", turn_id)
|
||||
if cross_session:
|
||||
message.channel, message.input_role = "system", "user"
|
||||
message.chat_id = message.session_key_override = draft.key
|
||||
message.metadata = {SESSION_MESSAGE_METADATA_KEY: {
|
||||
"message_id": turn_id, "created_at_ms": 1, "expect_reply": False,
|
||||
"source_handle": "luma", "source_session_key": "websocket:source", "target_session_key": draft.key,
|
||||
}}
|
||||
identifier = await loop.sessions.state.queue_followup(draft.key, message)
|
||||
message.metadata[PENDING_FOLLOWUP_ID_KEY] = identifier
|
||||
queue.put_nowait(message)
|
||||
@@ -218,7 +227,14 @@ async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit
|
||||
stored = await reopened.state.get(draft.key)
|
||||
inputs = [row for row in stored.messages if row.get("role") == "user"]
|
||||
assert [public_history_message(row)["content"] for row in inputs] == ["intentionally identical text"] * 3
|
||||
assert [row[INBOUND_META_TURN_ID] for row in inputs] == ["initial-input", "first-input", "second-input"]
|
||||
if cross_session:
|
||||
assert [row["session_message"]["message_id"] for row in inputs[1:]] == ["first-input", "second-input"]
|
||||
else:
|
||||
assert [row[INBOUND_META_TURN_ID] for row in inputs] == ["initial-input", "first-input", "second-input"]
|
||||
prefix = "session-message" if cross_session else "user"
|
||||
input_ids = ["user:initial-input", f"{prefix}:first-input", f"{prefix}:second-input"]
|
||||
assert [row["input_id"] for row in inputs] == input_ids
|
||||
assert stored.messages[-1]["response_input_ids"] == input_ids
|
||||
assert [row["timestamp"] for row in inputs] == ["2026-10-18T19:00:00"] * 3
|
||||
assert pending_followups(stored) == []
|
||||
assert bus.inbound.empty()
|
||||
|
||||
@@ -20,6 +20,7 @@ from nanobot.session.recovery import (
|
||||
pending_followups,
|
||||
record_pending_followup,
|
||||
)
|
||||
from nanobot.session.session_messages import SESSION_MESSAGE_METADATA_KEY
|
||||
from nanobot.webui import history as history_module
|
||||
from nanobot.webui.recovery import RecoveryActionError, RecoveryCoordinator
|
||||
|
||||
@@ -204,20 +205,21 @@ async def test_scan_loads_only_sessions_that_need_webui_recovery(
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_live_turn_followup_survives_restart_until_it_is_committed(tmp_path: Path) -> None:
|
||||
@pytest.mark.parametrize("cross_session", [False, True])
|
||||
async def test_live_turn_followup_survives_restart_until_it_is_committed(tmp_path: Path, cross_session: bool) -> None:
|
||||
sessions = SessionManager(tmp_path)
|
||||
session = sessions.get_or_create("websocket:chat")
|
||||
_persist(sessions, session)
|
||||
followup_id = record_pending_followup(
|
||||
session,
|
||||
InboundMessage(
|
||||
channel="websocket",
|
||||
sender_id="user",
|
||||
chat_id="chat",
|
||||
content="also check the logs",
|
||||
metadata={"webui": True},
|
||||
),
|
||||
metadata = {SESSION_MESSAGE_METADATA_KEY: {
|
||||
"message_id": "source-message", "created_at_ms": 1, "expect_reply": False,
|
||||
"source_handle": "luma", "source_session_key": "websocket:source", "target_session_key": session.key,
|
||||
}} if cross_session else {"webui": True}
|
||||
message = InboundMessage(
|
||||
channel="system" if cross_session else "websocket", sender_id="session" if cross_session else "user",
|
||||
chat_id=session.key if cross_session else "chat", content="/stop" if cross_session else "also check the logs", metadata=metadata,
|
||||
session_key_override=session.key, input_role="user" if cross_session else None,
|
||||
)
|
||||
followup_id = record_pending_followup(session, message)
|
||||
assert followup_id is not None
|
||||
sessions.save(session)
|
||||
|
||||
@@ -225,9 +227,16 @@ async def test_live_turn_followup_survives_restart_until_it_is_committed(tmp_pat
|
||||
await coordinator.scan()
|
||||
|
||||
queued = bus.inbound.get_nowait()
|
||||
assert queued.content == "also check the logs"
|
||||
assert (queued.channel, queued.content, queued.input_role, queued.timestamp) == (
|
||||
message.channel, message.content, message.input_role, message.timestamp,
|
||||
)
|
||||
assert queued.session_key == session.key
|
||||
assert queued.require_existing_session
|
||||
if cross_session:
|
||||
assert queued.metadata[SESSION_MESSAGE_METADATA_KEY] == metadata[SESSION_MESSAGE_METADATA_KEY]
|
||||
assert queued.metadata["_recovery_followup_id"] == followup_id
|
||||
restored = restarted.get_or_create("websocket:chat")
|
||||
assert record_pending_followup(restored, queued) == followup_id
|
||||
assert len(pending_followups(restored)) == 1
|
||||
|
||||
acknowledge_pending_followups(restored, [followup_id])
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.tools.session_messages import SendSessionMessageTool, SessionMessageError
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.session_handles import SessionHandleResolver
|
||||
|
||||
|
||||
async def test_session_send_rejects_commands_and_delivers_normal_input(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
bus = MessageBus()
|
||||
tool = SendSessionMessageTool(sessions=manager, bus=bus)
|
||||
try:
|
||||
await manager.state.get("websocket:source")
|
||||
await manager.state.get("websocket:target")
|
||||
handles = SessionHandleResolver(manager)
|
||||
target = await handles.ahandle_for_session("websocket:target")
|
||||
assert target is not None
|
||||
for content in ("/stop", " /stop", "\n\t/restart", "/restart"):
|
||||
with pytest.raises(SessionMessageError, match="slash commands"):
|
||||
await tool.enqueue(source_session_key="websocket:source", target_handle=target.name,
|
||||
content=content, expect_reply=False)
|
||||
assert bus.inbound_size == 0
|
||||
await tool.enqueue(source_session_key="websocket:source", target_handle=target.name,
|
||||
content="Please review /restart", expect_reply=False)
|
||||
message = await bus.consume_inbound()
|
||||
assert message.content == "Please review /restart"
|
||||
assert message.session_key == "websocket:target"
|
||||
assert bus.inbound_size == 0
|
||||
finally:
|
||||
await manager.state.aclose()
|
||||
@@ -251,7 +251,7 @@ def test_v4_archive_upgrade_removes_orphans_and_preserves_existing_membership(tm
|
||||
db.execute("INSERT INTO storage_meta (key, value) VALUES ('session_archives_imported', '1')")
|
||||
store.initialize(workspace)
|
||||
store.initialize(workspace)
|
||||
assert _database_snapshot(store.path)[0] == 4
|
||||
assert _database_snapshot(store.path)[0] == len(sqlite_store._SCHEMA_MIGRATIONS)
|
||||
assert store.archived_keys() == ["chat:empty-fork", "chat:extensions"]
|
||||
assert store.archives_imported()
|
||||
assert store.load("chat:extensions") == original
|
||||
|
||||
@@ -311,8 +311,8 @@ async def test_session_input_is_projected_by_the_webui_coordinator(
|
||||
"source_session_key": "websocket:source",
|
||||
"target_session_key": "websocket:target",
|
||||
}
|
||||
append_input = AsyncMock(side_effect=None if write_succeeds else OSError("write failed"))
|
||||
monkeypatch.setattr(wth, "append_session_message_input", append_input)
|
||||
append_input = AsyncMock(return_value=write_succeeds)
|
||||
monkeypatch.setattr(wth.WebUITranscriptRecorder, "append_user_message", append_input)
|
||||
coordinator = wth.WebuiTurnCoordinator(
|
||||
bus=bus,
|
||||
sessions=sessions,
|
||||
@@ -345,6 +345,36 @@ async def test_session_input_is_projected_by_the_webui_coordinator(
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_input_rejects_replaced_target_generation(tmp_path) -> None:
|
||||
bus = MessageBus()
|
||||
bus.publish_outbound = AsyncMock()
|
||||
sessions = SessionManager(tmp_path)
|
||||
target = sessions.get_or_create("websocket:target")
|
||||
target.metadata["webui"] = True
|
||||
sessions.save(target)
|
||||
source = session_handle_for_name("websocket:source", "luma")
|
||||
coordinator = wth.WebuiTurnCoordinator(
|
||||
bus=bus, sessions=sessions, schedule_background=lambda coro: coro.close(),
|
||||
)
|
||||
coordinator.subscribe()
|
||||
await bus.publish(UserInputAccepted(
|
||||
context=RuntimeEventContext(
|
||||
channel="system", chat_id="websocket:target", session_key="websocket:target",
|
||||
session_generation="replaced-generation",
|
||||
metadata={SESSION_MESSAGE_METADATA_KEY: {
|
||||
"message_id": "message-1", "created_at_ms": 123, "expect_reply": False,
|
||||
"source_handle": source.name, "source_session_key": "websocket:source",
|
||||
"target_session_key": "websocket:target",
|
||||
}},
|
||||
),
|
||||
content="Review this",
|
||||
))
|
||||
bus.publish_outbound.assert_not_awaited()
|
||||
records = await sessions.state.project_history("websocket:target", lambda h: list(h.all_facts()))
|
||||
assert records == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fallback_model_ignores_non_websocket_requests() -> None:
|
||||
bus = MessageBus()
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
from nanobot.webui.transcript import TranscriptReplayStats
|
||||
|
||||
|
||||
def test_grouped_backfill_keeps_response_input_order_in_page_and_index(history, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:backfill-order"
|
||||
ids = ["input:first", "input:second", "input:third"]
|
||||
messages = [
|
||||
{"role": "user", "content": name, "input_id": input_id}
|
||||
for name, input_id in zip(("first", "second", "third"), ids)
|
||||
] + [{"role": "assistant", "content": "answer"}]
|
||||
history.append(key, {"event": "user", "text": "second", "input_id": ids[1]})
|
||||
history.append(key, {"event": "message", "text": "answer", "response_input_ids": ids})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
def loader():
|
||||
return messages
|
||||
index = history.prompts(key, session_messages_loader=loader)
|
||||
stats = TranscriptReplayStats()
|
||||
page = history.build(key, limit=1, session_messages_loader=loader, stats=stats)
|
||||
users = [event for event in page["events"] if event["event"] == "user_message"]
|
||||
assert [event["text"] for event in users] == ["first", "second", "third"]
|
||||
assert [prompt["inputId"] for prompt in index] == ids
|
||||
assert [prompt["id"] for prompt in index] == [event["projection_id"] for event in users]
|
||||
assert stats.parsed_records < 10
|
||||
|
||||
|
||||
def test_identity_backfill_is_not_repeated_by_legacy_answer_matching(history, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:backfill-duplicate"
|
||||
messages = [
|
||||
{"role": "user", "content": "question", "input_id": "input:one"},
|
||||
{"role": "assistant", "content": "answer"},
|
||||
]
|
||||
history.append(key, {"event": "message", "text": "answer"})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
history.append(key, {"event": "message", "text": "answer", "response_input_ids": ["input:one"]})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
def loader():
|
||||
return messages
|
||||
index = history.prompts(key, session_messages_loader=loader)
|
||||
page = history.build(key, limit=10, session_messages_loader=loader)
|
||||
users = [event for event in page["events"] if event["event"] == "user_message"]
|
||||
assert [prompt["inputId"] for prompt in index] == ["input:one"]
|
||||
assert [event["text"] for event in users] == ["question"]
|
||||
assert index[0]["id"] == users[0]["projection_id"]
|
||||
latest = history.build(key, limit=1, session_messages_loader=loader)
|
||||
older = history.build(key, limit=1, before=latest["page"]["before_cursor"], session_messages_loader=loader)
|
||||
paged_users = [event for part in (older, latest) for event in part["events"] if event["event"] == "user_message"]
|
||||
assert [event["projection_id"] for event in paged_users] == [index[0]["id"]]
|
||||
|
||||
|
||||
def test_empty_response_inputs_do_not_use_legacy_answer_matching(history, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:empty-response-inputs"
|
||||
messages = [
|
||||
{"role": "user", "content": "question", "input_id": "input:one"},
|
||||
{"role": "assistant", "content": "answer"},
|
||||
]
|
||||
history.append(key, {"event": "message", "text": "answer", "response_input_ids": []})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
history.append(key, {"event": "message", "text": "answer"})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
|
||||
def loader():
|
||||
return messages
|
||||
|
||||
index = history.prompts(key, session_messages_loader=loader)
|
||||
page = history.build(key, limit=10, session_messages_loader=loader)
|
||||
users = [event for event in page["events"] if event["event"] == "user_message"]
|
||||
assert [prompt["inputId"] for prompt in index] == ["input:one"]
|
||||
assert [event["projection_id"] for event in users] == [index[0]["id"]]
|
||||
latest = history.build(key, limit=1, session_messages_loader=loader)
|
||||
older = history.build(key, limit=1, before=latest["page"]["before_cursor"], session_messages_loader=loader)
|
||||
assert not [event for event in older["events"] if event["event"] == "user_message"]
|
||||
assert [event["projection_id"] for event in latest["events"] if event["event"] == "user_message"] == [index[0]["id"]]
|
||||
|
||||
|
||||
def test_truncated_turn_applies_plan_when_reference_anchor_is_dropped(history, tmp_path, monkeypatch):
|
||||
from nanobot.webui import transcript
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 5)
|
||||
key = "websocket:truncated-backfill"
|
||||
ids = ["input:a", "input:b", "input:c"]
|
||||
messages = [{"role": "user", "content": text, "input_id": ident}
|
||||
for text, ident in zip(("A", "B", "C"), ids)]
|
||||
history.append(key, {"event": "user", "text": "B", "input_id": ids[1]})
|
||||
history.append(key, {"event": "message", "text": "first", "response_input_ids": ids[:2]})
|
||||
for i in range(12):
|
||||
history.append(key, {"event": "message", "kind": "tool_hint", "text": str(i)})
|
||||
history.append(key, {"event": "message", "text": "last", "response_input_ids": ids[2:]})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
index = history.prompts(key, session_messages_loader=lambda: messages)
|
||||
page = history.build(key, limit=10, session_messages_loader=lambda: messages)
|
||||
users = [event for event in page["events"] if event["event"] == "user_message"]
|
||||
assert page["page"]["truncated_oversized_turn"]
|
||||
assert not page["page"]["has_more_before"]
|
||||
assert [event["text"] for event in users] == ["A", "B", "C"]
|
||||
assert [event["projection_id"] for event in users] == [prompt["id"] for prompt in index]
|
||||
|
||||
|
||||
def test_truncated_turn_recovers_even_if_all_missing_references_were_dropped(history, tmp_path, monkeypatch):
|
||||
from nanobot.webui import transcript
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 4)
|
||||
key = "websocket:truncated-no-reference"
|
||||
messages = [{"role": "user", "content": "A", "input_id": "a"}]
|
||||
history.append(key, {"event": "user", "text": "B", "input_id": "b"})
|
||||
history.append(key, {"event": "message", "text": "old", "response_input_ids": ["a", "b"]})
|
||||
for i in range(10):
|
||||
history.append(key, {"event": "message", "kind": "tool_hint", "text": str(i)})
|
||||
history.append(key, {"event": "message", "text": "new"})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
index = history.prompts(key, session_messages_loader=lambda: messages)
|
||||
page = history.build(key, limit=10, session_messages_loader=lambda: messages)
|
||||
users = [event for event in page["events"] if event["event"] == "user_message"]
|
||||
assert page["page"]["truncated_oversized_turn"]
|
||||
assert [event["text"] for event in users] == ["A", "B"]
|
||||
assert [event["projection_id"] for event in users] == [prompt["id"] for prompt in index]
|
||||
|
||||
|
||||
def test_completed_stream_compaction_and_truncation_keep_shared_backfill_anchor(history, tmp_path, monkeypatch):
|
||||
from nanobot.webui import transcript
|
||||
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:stream-anchor"
|
||||
ids = ["input:a", "input:b", "input:c"]
|
||||
messages = [{"role": "user", "content": text, "input_id": ident}
|
||||
for text, ident in zip(("A", "B", "C"), ids)]
|
||||
history.append(key, {"event": "user", "text": "B", "input_id": ids[1]})
|
||||
history.append(key, {"event": "message", "text": "answer", "response_input_ids": ids})
|
||||
for i in range(10):
|
||||
history.append(key, {"event": "message", "kind": "tool_hint", "text": str(i)})
|
||||
for text in ("one", "two", "three"):
|
||||
history.append(key, {"event": "delta", "text": text})
|
||||
history.append(key, {"event": "stream_end", "text": "onetwothree"})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
|
||||
def loader():
|
||||
return messages
|
||||
index = history.prompts(key, session_messages_loader=loader)
|
||||
stats = TranscriptReplayStats()
|
||||
full = history.build(key, limit=10, session_messages_loader=loader, stats=stats)
|
||||
assert stats.compacted_delta_records == 3
|
||||
monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 8)
|
||||
truncated_stats = TranscriptReplayStats()
|
||||
truncated = history.build(key, limit=10, session_messages_loader=loader, stats=truncated_stats)
|
||||
assert truncated["page"]["truncated_oversized_turn"]
|
||||
assert truncated_stats.compacted_delta_records == 3
|
||||
expected_ids = [prompt["id"] for prompt in index]
|
||||
assert [prompt["inputId"] for prompt in index] == ids
|
||||
for page in (full, truncated):
|
||||
users = [event for event in page["events"] if event["event"] == "user_message"]
|
||||
assert [event["text"] for event in users] == ["A", "B", "C"]
|
||||
assert [event["projection_id"] for event in users] == expected_ids
|
||||
@@ -89,6 +89,64 @@ async def test_remote_proxy_with_real_gateway_chat_settings_and_renewal(
|
||||
_stop_gateway(process)
|
||||
|
||||
|
||||
# Test-only injection: report locations without task names, frame data or source.
|
||||
_TASK_DIAGNOSTICS = """
|
||||
import asyncio, os, signal, sys
|
||||
if sys.platform.startswith('linux') and os.name == 'posix':
|
||||
original_run = asyncio.run
|
||||
def diagnostic_run(coro, *args, **kwargs):
|
||||
async def wrapped():
|
||||
loop = asyncio.get_running_loop()
|
||||
def dump_tasks():
|
||||
with open(os.environ['SMOKE_TASK_DIAGNOSTICS'], 'w', encoding='utf-8') as output:
|
||||
print('Gateway async task locations:', file=output)
|
||||
for number, task in enumerate(asyncio.all_tasks(loop), 1):
|
||||
for frame in task.get_stack():
|
||||
code = frame.f_code
|
||||
print(f'{number} {os.path.basename(code.co_filename)} {code.co_name} {frame.f_lineno}', file=output)
|
||||
print('Gateway async task locations end', file=output)
|
||||
loop.add_signal_handler(signal.SIGUSR1, dump_tasks)
|
||||
return await coro
|
||||
return original_run(wrapped(), *args, **kwargs)
|
||||
asyncio.run = diagnostic_run
|
||||
"""
|
||||
|
||||
|
||||
async def _stop_inline_gateway(process: subprocess.Popen[bytes], *, diagnostics: Path, timeout: float = 30) -> None:
|
||||
if process.poll() is not None:
|
||||
return
|
||||
if sys.platform == "win32":
|
||||
subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"],
|
||||
capture_output=True, check=True, creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
else:
|
||||
process.terminate()
|
||||
try:
|
||||
await asyncio.to_thread(process.wait, timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
try:
|
||||
if sys.platform.startswith("linux") and os.name == "posix":
|
||||
try:
|
||||
process.send_signal(signal.SIGUSR1)
|
||||
await asyncio.to_thread(process.wait, timeout=1)
|
||||
except (ProcessLookupError, subprocess.TimeoutExpired):
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
process.kill()
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
finally:
|
||||
await asyncio.to_thread(process.wait, timeout=10)
|
||||
if diagnostics.exists():
|
||||
print(diagnostics.read_text(encoding="utf-8"))
|
||||
stacks = diagnostics.with_name("gateway-stacks.log")
|
||||
if stacks.exists():
|
||||
frames = re.findall(r'File "[^"\n]*[/\\]([^/\\"\n]+)", line (\d+) in (\w+)',
|
||||
stacks.read_text(encoding="utf-8"))
|
||||
print("Gateway shutdown stack locations:", frames[-80:])
|
||||
raise
|
||||
|
||||
|
||||
def _free_port() -> int:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
@@ -583,7 +641,7 @@ async def test_real_gateway_goal_single_run_and_stop(tmp_path: Path, stop_during
|
||||
config = json.loads(config_path.read_text(encoding="utf-8"))
|
||||
config["providers"]["custom"]["apiBase"] = f"http://127.0.0.1:{model_port}/v1"
|
||||
config_path.write_text(json.dumps(config), encoding="utf-8")
|
||||
launcher = """
|
||||
launcher = _TASK_DIAGNOSTICS + """
|
||||
import asyncio, faulthandler, httpx, sys
|
||||
from pathlib import Path
|
||||
from nanobot.session.state import SessionState
|
||||
@@ -615,6 +673,8 @@ with Path(config).with_name('gateway-stacks.log').open('w') as stacks:
|
||||
env.update({"HOME": str(home), "USERPROFILE": str(home), "APPDATA": str(home),
|
||||
"LOCALAPPDATA": str(home), "TMP": str(tmp_path), "TEMP": str(tmp_path),
|
||||
"NO_PROXY": "localhost,127.0.0.1", "no_proxy": "localhost,127.0.0.1"})
|
||||
diagnostics = tmp_path / "gateway-tasks.log"
|
||||
env["SMOKE_TASK_DIAGNOSTICS"] = str(diagnostics)
|
||||
creationflags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
|
||||
process = None
|
||||
try:
|
||||
@@ -717,23 +777,53 @@ with Path(config).with_name('gateway-stacks.log').open('w') as stacks:
|
||||
release_close.set()
|
||||
release_checkpoint.set()
|
||||
try:
|
||||
if process is not None and process.poll() is None:
|
||||
if sys.platform == "win32":
|
||||
subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"],
|
||||
capture_output=True, check=True, creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
else:
|
||||
process.terminate()
|
||||
try:
|
||||
# Keep the test model/barrier server live while its client exits.
|
||||
await asyncio.to_thread(process.wait, timeout=30)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
await asyncio.to_thread(process.wait, timeout=10)
|
||||
stacks = tmp_path / "gateway-stacks.log"
|
||||
if stacks.exists():
|
||||
frames = re.findall(r'File "[^"\n]*[/\\]([^/\\"\n]+)", line (\d+) in (\w+)',
|
||||
stacks.read_text(encoding="utf-8"))
|
||||
print("Gateway shutdown stack locations:", frames[-80:])
|
||||
raise
|
||||
if process is not None:
|
||||
# Keep the model/barrier server live while its client exits.
|
||||
await _stop_inline_gateway(process, diagnostics=diagnostics)
|
||||
finally:
|
||||
await server.cleanup()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not (sys.platform.startswith("linux") and os.name == "posix"), reason="Linux signals only")
|
||||
@pytest.mark.asyncio
|
||||
async def test_inline_gateway_timeout_dumps_tasks_and_reaps(tmp_path: Path, capsys: pytest.CaptureFixture) -> None:
|
||||
(tmp_path / "gateway-stacks.log").write_text(
|
||||
'Thread secret\n File "/private/path/gateway.py", line 42 in blocked\n secret source\n'
|
||||
)
|
||||
log_path = tmp_path / "diagnostic.log"
|
||||
diagnostics = tmp_path / "tasks.log"
|
||||
script = _TASK_DIAGNOSTICS + """
|
||||
async def blocked():
|
||||
secret_variable = 'must-not-appear-in-diagnostics'
|
||||
await asyncio.Event().wait()
|
||||
async def main():
|
||||
signal.signal(signal.SIGTERM, signal.SIG_IGN)
|
||||
asyncio.create_task(blocked(), name='private-task-name')
|
||||
print('ready', flush=True)
|
||||
await asyncio.Event().wait()
|
||||
asyncio.run(main())
|
||||
"""
|
||||
with log_path.open("wb") as log:
|
||||
process = subprocess.Popen([sys.executable, "-c", script], stdout=log, stderr=subprocess.STDOUT,
|
||||
env={**os.environ, "SMOKE_TASK_DIAGNOSTICS": str(diagnostics)})
|
||||
try:
|
||||
deadline = time.monotonic() + 5
|
||||
while "ready" not in log_path.read_text() and time.monotonic() < deadline:
|
||||
await asyncio.sleep(0.01)
|
||||
assert "ready" in log_path.read_text()
|
||||
with pytest.raises(subprocess.TimeoutExpired):
|
||||
await _stop_inline_gateway(process, diagnostics=diagnostics, timeout=0.1)
|
||||
assert process.returncode is not None
|
||||
captured = capsys.readouterr().out
|
||||
assert "('gateway.py', '42', 'blocked')" in captured
|
||||
assert "/private/path" not in captured
|
||||
assert "secret source" not in captured
|
||||
output = diagnostics.read_text()
|
||||
assert "Gateway async task locations end" in output
|
||||
assert "<string> blocked " in output
|
||||
assert "private-task-name" not in output
|
||||
assert "must-not-appear-in-diagnostics" not in output
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait(timeout=10)
|
||||
@@ -13,16 +13,21 @@ from nanobot.webui.client_contract import webui_contract
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
|
||||
def test_complete_index_and_bidirectional_pages_without_loading_model_messages(history, tmp_path, monkeypatch):
|
||||
@pytest.mark.parametrize("identified", [False, True])
|
||||
def test_complete_index_and_bidirectional_pages_without_loading_model_messages(history, tmp_path, monkeypatch, identified):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:navigation"
|
||||
for i in range(120):
|
||||
history.append(key, {"event": "user", "chat_id": "navigation", "text": f"question {i}", "turn_id": f"t{i}"})
|
||||
history.append(key, {"event": "message", "chat_id": "navigation", "text": "answer " + "x" * 200, "turn_id": f"t{i}"})
|
||||
input_identity = {"input_id": f"user:t{i}"} if identified else {}
|
||||
response_identity = {"response_input_ids": [f"user:t{i}"]} if identified else {}
|
||||
history.append(key, {"event": "user", "chat_id": "navigation", "text": f"question {i}", "turn_id": f"t{i}", **input_identity})
|
||||
history.append(key, {"event": "message", "chat_id": "navigation", "text": "answer " + "x" * 200, "turn_id": f"t{i}", **response_identity})
|
||||
history.append(key, {"event": "turn_end", "chat_id": "navigation", "turn_id": f"t{i}"})
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr("nanobot.session.display_history.HistoryReader.navigation", lambda _: (_ for _ in ()).throw(AssertionError("page scanned full history")))
|
||||
latest = history.build(key, limit=3)
|
||||
index = history.prompts(key)
|
||||
assert len(index) == 120
|
||||
latest = history.build(key, limit=3)
|
||||
assert len(latest["events"]) < len(index)
|
||||
target = index[42]
|
||||
stats = transcript.TranscriptReplayStats()
|
||||
@@ -148,6 +153,64 @@ def test_recovered_prompt_identity_time_and_cursor_survive_pages(history, tmp_pa
|
||||
assert history.prompts(key, session_messages_loader=loader) == index
|
||||
|
||||
|
||||
@pytest.mark.parametrize("second_recorded", [True, False])
|
||||
@pytest.mark.parametrize("grouped", [True, False])
|
||||
def test_cross_session_inputs_are_reconciled_by_identity_across_turns(
|
||||
history, tmp_path, monkeypatch, second_recorded, grouped,
|
||||
):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:cross-session-replay"
|
||||
provenance = [
|
||||
{"message_id": f"message-{i}", "session": {"id": "handle_" + "1" * 32, "name": "luma"}}
|
||||
for i in range(2)
|
||||
]
|
||||
input_ids = [f"session-message:{source['message_id']}" for source in provenance]
|
||||
messages = [
|
||||
{"role": "user", "content": "original question", "input_id": "user:original"},
|
||||
{"role": "assistant", "content": "original answer"},
|
||||
]
|
||||
history.append(key, {"event": "user", "text": "original question", "input_id": "user:original"})
|
||||
for i, source in enumerate(provenance):
|
||||
messages.append({"role": "user", "content": "same message", "session_message": source, "input_id": input_ids[i]})
|
||||
if not grouped or i == 1:
|
||||
messages.append({"role": "assistant", "content": f"answer {i}"})
|
||||
if i == 0 or second_recorded:
|
||||
history.append(key, {"event": "user", "text": "same message", "session_message": source, "input_id": input_ids[i]})
|
||||
history.append(key, {"event": "message", "text": "original answer", "response_input_ids": ["user:original"]})
|
||||
assert [prompt["answerPreview"] for prompt in history.prompts(key)] == ["original answer"] + [""] * (2 if second_recorded else 1)
|
||||
history.append(key, {"event": "turn_end"})
|
||||
for i in ([1] if grouped else range(2)):
|
||||
history.append(key, {"event": "message", "text": f"answer {i}", "response_input_ids": input_ids if grouped else [input_ids[i]]})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
|
||||
def loader():
|
||||
assert not second_recorded, "complete display history must not load model history"
|
||||
return messages
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
if second_recorded:
|
||||
patch.setattr("nanobot.session.display_history.HistoryReader.navigation", lambda _: (_ for _ in ()).throw(AssertionError("page scanned full history")))
|
||||
latest = history.build(key, limit=1, session_messages_loader=loader)
|
||||
assert [event["text"] for event in latest["events"] if event["event"] == "user_message"] == (
|
||||
[] if second_recorded else ["same message"]
|
||||
)
|
||||
page = history.build(key, limit=10, session_messages_loader=loader)
|
||||
users = [event for event in page["events"] if event["event"] == "user_message"]
|
||||
assert [user["text"] for user in users] == ["original question", "same message", "same message"]
|
||||
assert [user["provenance"]["session_message"]["message_id"] for user in users[1:]] == [
|
||||
"message-0", "message-1",
|
||||
]
|
||||
prompts = history.prompts(key, session_messages_loader=loader)
|
||||
assert [prompt["id"] for prompt in prompts] == [user["projection_id"] for user in users]
|
||||
assert [prompt["answerPreview"] for prompt in prompts] == ["original answer", "answer 1" if grouped else "answer 0", "answer 1"]
|
||||
assert [prompt["inputId"] for prompt in prompts] == ["user:original", *input_ids]
|
||||
revision = history.revision(key)
|
||||
history.append(key, {"event": "user", "text": "same message", "session_message": provenance[0], "input_id": input_ids[0]})
|
||||
assert history.revision(key) == revision
|
||||
assert history.build(key, limit=10, session_messages_loader=loader) == page
|
||||
assert history.build(key, limit=1, session_messages_loader=loader) == latest
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_recovered_public_index_and_page_validators_include_canonical_timestamp(history, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
@@ -331,3 +394,26 @@ def test_indexed_backfill_preserves_unique_in_suffix_matching(history, tmp_path,
|
||||
assert [user["text"] for user in users] == (["question 2"] if with_anchor else [])
|
||||
if with_anchor:
|
||||
assert users[0]["projection_id"] == prompts[-1]["id"]
|
||||
|
||||
|
||||
def test_recover_multiple_missing_inputs_for_one_answer_across_pages(history, tmp_path, monkeypatch):
|
||||
"""A grouped answer can stand for multiple inputs absent from display history."""
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:missing-grouped-inputs"
|
||||
ids = ["session-message:first", "session-message:second"]
|
||||
messages = [
|
||||
{"role": "user", "content": "first", "input_id": ids[0]},
|
||||
{"role": "user", "content": "second", "input_id": ids[1]},
|
||||
{"role": "assistant", "content": "shared answer"},
|
||||
]
|
||||
history.append(key, {"event": "message", "text": "shared answer", "response_input_ids": ids})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
def loader():
|
||||
return messages
|
||||
|
||||
page = history.build(key, limit=1, session_messages_loader=loader)
|
||||
users = [event for event in page["events"] if event["event"] == "user_message"]
|
||||
assert [event["text"] for event in users] == ["first", "second"]
|
||||
prompts = history.prompts(key, session_messages_loader=loader)
|
||||
assert [prompt["inputId"] for prompt in prompts] == ids
|
||||
assert [prompt["id"] for prompt in prompts] == [event["projection_id"] for event in users]
|
||||
Reference in new issue
Block a user