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()
|
||||
|
||||
Reference in new issue
Block a user