diff --git a/nanobot/agent/context_governance.py b/nanobot/agent/context_governance.py index 12c9d00f2..b94f3a491 100644 --- a/nanobot/agent/context_governance.py +++ b/nanobot/agent/context_governance.py @@ -260,6 +260,8 @@ class ModelRequestState: request_run_id: str = field(default_factory=lambda: uuid4().hex) request_sequence: int = 0 request_usage: LLMUsage | None = None + # Current response targets, shared by requests that recover the same answer. + response_input_ids: tuple[str, ...] = () # Reported usage per runner round; recovery requests update the same slot. recent_round_usages: list[LLMUsage | None] = field(default_factory=list) diff --git a/nanobot/agent/runner.py b/nanobot/agent/runner.py index 1880b63a7..5c2c3721b 100644 --- a/nanobot/agent/runner.py +++ b/nanobot/agent/runner.py @@ -500,6 +500,7 @@ class AgentRunner: had_injections = True await end_length_segment(interrupted=drained_before_request) response_input_ids = self._response_input_ids(messages) + request_state.response_input_ids = response_input_ids if spec.events.accepts(ResponseInputsEvent): await spec.events.emit(ResponseInputsEvent(response_input_ids)) context = AgentHookContext( @@ -993,6 +994,7 @@ class AgentRunner: round_usages=tuple(usage for usage in state.recent_round_usages if usage is not None), context_window_tokens=spec.runtime.context_window_tokens, request_usage=request_usage, + response_input_ids=state.response_input_ids if phase == "started" else (), )) try: diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.py index 4fa44febb..a37de0b1f 100644 --- a/nanobot/channels/websocket/tests/test_websocket_channel.py +++ b/nanobot/channels/websocket/tests/test_websocket_channel.py @@ -7034,13 +7034,21 @@ async def test_model_request_delivery_persists_started_and_terminal_offline(hist for sequence, phase in enumerate(("started", "completed"), 1): await channel.send(await history.message( channel="websocket", chat_id="model-requests", content="", - event=ModelRequestEvent("request", "run", sequence, phase), + event=ModelRequestEvent( + "request", "run", sequence, phase, + response_input_ids=("input-1", "input-2") if phase == "started" else (), + ), )) rows = history.read("websocket:model-requests") assert [r["event"] for r in rows] == ["model_request", "model_request"] assert [r["phase"] for r in rows] == ["started", "completed"] + assert rows[0]["response_input_ids"] == ["input-1", "input-2"] + assert "response_input_ids" not in rows[1] if connected: - assert [r["phase"] for r in _sent_ws_payloads(ws)] == ["started", "completed"] + frames = _sent_ws_payloads(ws) + assert [r["phase"] for r in frames] == ["started", "completed"] + assert frames[0]["response_input_ids"] == ["input-1", "input-2"] + assert "response_input_ids" not in frames[1] @pytest.mark.asyncio diff --git a/nanobot/events.py b/nanobot/events.py index bdd084167..195322be8 100644 --- a/nanobot/events.py +++ b/nanobot/events.py @@ -25,6 +25,8 @@ class ModelRequestEvent(AgentEvent): round_usages: tuple[LLMUsage, ...] = () context_window_tokens: int | None = None request_usage: LLMUsage | None = None + # Only set on started: inputs this request is answering, not its full history. + response_input_ids: tuple[str, ...] = () @dataclass(frozen=True) diff --git a/nanobot/webui/outbound_wire.py b/nanobot/webui/outbound_wire.py index d0b0a7ef8..0f07fe389 100644 --- a/nanobot/webui/outbound_wire.py +++ b/nanobot/webui/outbound_wire.py @@ -108,6 +108,7 @@ class ModelRequestWirePayload(_ChatWirePayload): usage: NotRequired[dict[str, int]] round_usages: NotRequired[list[dict[str, int]]] context_window_tokens: NotRequired[int] + response_input_ids: NotRequired[list[str]] class ContextCompactionWirePayload(_ChatWirePayload): @@ -272,6 +273,8 @@ def project_notification( } if context_graph is not None: payload["context_graph"] = context_graph + if event.phase == "started" and event.response_input_ids: + payload["response_input_ids"] = list(event.response_input_ids) if event.usage is not None: payload["usage"] = event.usage.to_turn_dict() payload["round_usages"] = [usage.to_turn_dict() for usage in event.round_usages[-8:]] diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py index afe35647b..5c967b496 100644 --- a/nanobot/webui/transcript.py +++ b/nanobot/webui/transcript.py @@ -1158,9 +1158,11 @@ def _recover_incomplete_turns( def _needs_user_event_backfill( lines: list[dict[str, Any]], history: HistoryReader, *, legacy: bool = True, ) -> bool: + # A request start identifies response targets, but is not persisted answer evidence. + display_lines = [record for record in lines if record.get("event") != "model_request"] referenced_inputs = { input_id - for record in lines + for record in display_lines if isinstance(references := record.get("response_input_ids"), list) for input_id in cast(list[object], references) if isinstance(input_id, str) and input_id @@ -1168,7 +1170,7 @@ def _needs_user_event_backfill( return any(not history.has_input(input_id) for input_id in referenced_inputs) or legacy and any( not any(record.get("event") == "user" or isinstance(record.get("response_input_ids"), list) for record in turn) and _transcript_turn_signature(turn) - for turn in _split_transcript_turns(lines) + for turn in _split_transcript_turns(display_lines) ) @@ -1625,6 +1627,10 @@ def _client_projection_event( ): return None projected.update(request_id=request_id, run_id=run_id, sequence=sequence, phase=phase) + if phase == "started" and isinstance(references := record.get("response_input_ids"), list): + input_ids = [value for value in cast(list[object], references) if isinstance(value, str) and value] + if input_ids: + projected["response_input_ids"] = input_ids if "request_usage" in record: projected["request_usage"] = _sanitize_turn_usage(record["request_usage"]) or None if (graph := decode_graph(record.get("context_graph"))) is not None: diff --git a/tests/agent/test_model_request_events.py b/tests/agent/test_model_request_events.py index 5dcac3792..895ca6d5b 100644 --- a/tests/agent/test_model_request_events.py +++ b/tests/agent/test_model_request_events.py @@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock import pytest from agent.runner_helpers import make_run_spec +from nanobot.agent.context_governance import ContextWindowExceededError from nanobot.agent.hook import AgentHookContext from nanobot.agent.progress_hook import AgentProgressHook from nanobot.agent.runner import AgentRunner @@ -55,6 +56,73 @@ async def test_requests_arrive_before_runner_finishes_and_cancel_is_terminal(): assert requests[1].usage is None +@pytest.mark.asyncio +async def test_started_identifies_the_inputs_in_the_request_being_answered(): + requests = [] + pending = [] + + async def publish(event): + if isinstance(event, ModelRequestEvent): + requests.append(event) + + def user(input_id, content): + return {"role": "user", "content": content, "_meta": {"input_id": input_id}} + + async def drain(): + batch = pending.copy() + pending.clear() + return batch + + async def provider_call(*, messages, **kwargs): + started = requests[-1] + assert started.phase == "started" + user_prompt = "\n".join(message["content"] for message in messages if message["role"] == "user") + if len(requests) == 1: + pending.extend([user("b", "second question"), user("c", "third question")]) + assert "second question" not in user_prompt + assert started.response_input_ids == ("a",) + return LLMResponse(content="first answer") + assert "first question" in user_prompt # Prior input is still context, not a response target. + assert "second question" in user_prompt and "third question" in user_prompt + assert started.response_input_ids == ("b", "c") + return LLMResponse(content="follow-up answer") + + provider = MagicMock() + provider.chat_stream_with_retry = provider_call + run_spec = spec(provider, EventSink(publish), injection_callback=drain) + run_spec.initial_messages = [user("a", "first question")] + result = await AgentRunner().run(run_spec) + + assert [(event.phase, event.response_input_ids) for event in requests] == [ + ("started", ("a",)), ("completed", ()), ("started", ("b", "c")), ("completed", ()), + ] + answers = [message for message in result.messages if message["role"] == "assistant"] + assert [message["_meta"]["response_input_ids"] for message in answers] == [["a"], ["b", "c"]] + + +@pytest.mark.asyncio +async def test_rejected_prompt_never_starts_a_model_request(monkeypatch): + events = [] + + async def publish(event): + events.append(event) + + monkeypatch.setattr( + "nanobot.agent.context_governance.estimate_prompt_tokens_chain", + lambda *_args, **_kwargs: (600, "test-counter"), + ) + provider = MagicMock() + provider.chat_stream_with_retry = AsyncMock() + run_spec = spec(provider, EventSink(publish), context_window_tokens=1_624, max_tokens=100) + run_spec.initial_messages = [{"role": "user", "content": "hi", "_meta": {"input_id": "a"}}] + + with pytest.raises(ContextWindowExceededError): + await AgentRunner().run(run_spec) + + provider.chat_stream_with_retry.assert_not_awaited() + assert not any(isinstance(event, ModelRequestEvent) for event in events) + + @pytest.mark.asyncio async def test_completed_request_usage_is_visible_while_tool_is_blocked(): events = [] diff --git a/tests/utils/test_webui_transcript.py b/tests/utils/test_webui_transcript.py index 8561cc833..39819cb84 100644 --- a/tests/utils/test_webui_transcript.py +++ b/tests/utils/test_webui_transcript.py @@ -1276,6 +1276,7 @@ def test_model_request_persists_through_reconnect_projection(history, tmp_path, request_id="request", run_id="run", sequence=2, phase=phase, usage=usage, round_usages=(usage,) * 10, context_window_tokens=32000, request_usage=usage if measured else None, + response_input_ids=("input-1", "input-2") if phase == "started" else (), )) assert projection is not None assert projection.persistence == "turn_activity" @@ -1289,5 +1290,9 @@ def test_model_request_persists_through_reconnect_projection(history, tmp_path, assert response is not None [event] = [e for e in response["events"] if e["event"] == "model_request"] assert {field: event[field] for field in record} == record + if phase == "started": + assert event["response_input_ids"] == ["input-1", "input-2"] + else: + assert "response_input_ids" not in event assert len(event["round_usages"]) == 8 assert event["usage"] == usage.to_turn_dict() diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts index 0260708a5..75e2369af 100644 --- a/webui/src/lib/types.ts +++ b/webui/src/lib/types.ts @@ -1682,6 +1682,8 @@ export type InboundEvent = run_id: string; sequence: number; phase: "started" | "completed" | "failed" | "cancelled"; + /** Inputs being answered by this request; present on started when identified. */ + response_input_ids?: string[]; usage?: TurnUsage; round_usages?: RoundUsage[]; context_window_tokens?: number;