fix(agent): preserve goal continuation lifecycle

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-24 19:25:34 +08:00
1 parent 3c022ada6a
commit ce885fa31e
5 files changed
+75 -22

No files matched your search

+6 -8
View File
@@ -1703,7 +1703,7 @@ class AgentLoop:
pending_queue=pending,
delivery=delivery,
)
continuing = turn_continuation.internal_continuation_pending(msg.metadata)
continuing = delivery.continuation_pending
await delivery.complete(
response,
publish_completion=not continuing,
@@ -1713,6 +1713,8 @@ class AgentLoop:
coordinator.complete(msg, response=response)
except asyncio.CancelledError:
logger.info("Task cancelled for session {}", session_key)
# The queued continuation is cancelled with this session worker.
delivery.continuation_pending = False
try:
await delivery.abort_stream()
except Exception:
@@ -1745,15 +1747,11 @@ class AgentLoop:
logger.opt(exception=log_content).error(
"Error processing message for session {}", session_key,
)
await delivery.fail(
publish_completion=not turn_continuation.internal_continuation_pending(
msg.metadata
)
)
await delivery.fail(publish_completion=not delivery.continuation_pending)
for coordinator in self._automation_turn_coordinators:
coordinator.complete(msg, error=exc)
finally:
if not turn_continuation.internal_continuation_pending(msg.metadata):
if not delivery.continuation_pending:
await delivery.idle()
except asyncio.CancelledError:
if not completion_published and self.commands.requires_session_queue(command_text(msg)):
@@ -2353,7 +2351,7 @@ class AgentLoop:
ctx.delivery.record_usage(result.round_usages)
if ctx.kind is TurnKind.USER:
current = await self.sessions.state.read_metadata(ctx.session_key)
await turn_continuation.maybe_continue_turn(
ctx.delivery.continuation_pending = await turn_continuation.maybe_continue_turn(
ctx, session_metadata=current["metadata"] if current else {},
)
+1
View File
@@ -207,6 +207,7 @@ class TurnDelivery:
route: TurnRoute
route_admission: TurnRouteAdmission | None = None
enable_stream: bool = False
continuation_pending: bool = field(init=False, default=False)
delivery_message: InboundMessage = field(init=False)
lifecycle_message: InboundMessage = field(init=False)
_stream_base_id: str | None = field(init=False, default=None)
-8
View File
@@ -24,7 +24,6 @@ if TYPE_CHECKING:
INTERNAL_CONTINUATION_META = "_internal_continuation"
INTERNAL_CONTINUATION_KIND_META = "_internal_continuation_kind"
INTERNAL_CONTINUATION_PENDING_META = "_internal_continuation_pending"
INTERNAL_CONTINUATION_RUN_STARTED_AT_META = "_internal_continuation_run_started_at"
SKIP_USER_PERSIST_META = "_skip_user_persist"
@@ -33,7 +32,6 @@ _GOAL_CONTINUATION_SENDER = "system:continuation"
_GOAL_CONTINUATION_ROUNDS_KEY = "_sustained_goal_continuation_rounds"
_MAX_GOAL_CONTINUATION_ROUNDS = 12
_STRIPPED_INBOUND_META_KEYS = {
INTERNAL_CONTINUATION_PENDING_META,
"goal_requested",
"original_command",
}
@@ -53,11 +51,6 @@ def sustained_goal_continuation_inbound(metadata: Mapping[str, Any] | None) -> b
)
def internal_continuation_pending(metadata: Mapping[str, Any] | None) -> bool:
"""True when the current turn scheduled an invisible continuation slice."""
return bool(metadata and metadata.get(INTERNAL_CONTINUATION_PENDING_META) is True)
def internal_continuation_run_started_at(metadata: Mapping[str, Any] | None) -> float | None:
"""Return the user-visible run start propagated across continuation slices."""
if not metadata:
@@ -143,7 +136,6 @@ async def maybe_continue_turn(
_increment_goal_continuation_round(ctx.session.metadata)
logger.info("Turn budget reached; scheduling internal continuation")
ctx.msg.metadata[INTERNAL_CONTINUATION_PENDING_META] = True
ctx.final_content = ""
ctx.all_messages = messages
ctx.suppress_response = True
+68 -2
View File
@@ -1514,8 +1514,9 @@ async def test_internal_continuation_preserves_streaming_route_metadata(
@pytest.mark.asyncio
@pytest.mark.parametrize("content", ["start the goal", "/goal start the goal"])
async def test_websocket_internal_continuation_keeps_single_visible_run(
tmp_path: Path,
tmp_path: Path, content: str,
) -> None:
loop = _make_full_loop(tmp_path)
session = loop.sessions.get_or_create("websocket:c-auto")
@@ -1548,7 +1549,7 @@ async def test_websocket_internal_continuation_keeps_single_visible_run(
channel="websocket",
sender_id="u1",
chat_id="c-auto",
content="start the goal",
content=content,
metadata={"webui": True},
))
@@ -1567,6 +1568,71 @@ async def test_websocket_internal_continuation_keeps_single_visible_run(
assert calls == 2
@pytest.mark.asyncio
@pytest.mark.parametrize("content", ["start the goal", "/goal start the goal"])
async def test_stop_after_continuation_queued_ends_visible_run(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, content: str,
) -> None:
from nanobot.command.builtin import cmd_stop
from nanobot.command.router import CommandContext
loop = _make_full_loop(tmp_path)
session = loop.sessions.get_or_create("websocket:c-stop-continuation")
session.metadata[GOAL_STATE_KEY] = {
"status": "active",
"objective": "Finish the long goal.",
}
loop.sessions.save(session)
calls = 0
async def fake_run_agent_loop(transcript_input, **_kwargs):
nonlocal calls
calls += 1
initial_messages = _assembled_messages(loop.context, transcript_input)
return _agent_run_result(
"paused",
[*initial_messages, {"role": "assistant", "content": "paused"}],
stop_reason="max_iterations",
)
loop._run_agent_loop = fake_run_agent_loop # type: ignore[method-assign]
saving = asyncio.Event()
finish_turn = loop.sessions.state.finish_turn
async def hold_first_save(session):
if not saving.is_set():
saving.set()
await asyncio.Event().wait()
await finish_turn(session)
monkeypatch.setattr(loop.sessions.state, "finish_turn", hold_first_save)
msg = InboundMessage(
channel="websocket", sender_id="u1", chat_id="c-stop-continuation",
content=content, metadata={"webui": True},
)
await loop._enqueue_session_message(msg)
try:
await asyncio.wait_for(saving.wait(), timeout=5)
assert loop._pending_queues[msg.session_key].qsize() == 1
stop_msg = InboundMessage(
channel="websocket", sender_id="u1", chat_id=msg.chat_id, content="/stop",
)
result = await cmd_stop(CommandContext(
msg=stop_msg, session=None, key=msg.session_key, raw="/stop", loop=loop,
))
assert "Stopped 1 task(s)" in result.content
finally:
await loop._cancel_active_tasks(msg.session_key)
outbound = []
while loop.bus.outbound_size:
outbound.append(await loop.bus.consume_outbound())
statuses = [m.event.status for m in outbound if isinstance(m.event, GoalStatusEvent)]
assert statuses == ["running", "idle"]
assert calls == 1
assert msg.session_key not in loop._pending_queues
@pytest.mark.asyncio
async def test_process_message_keeps_delivery_chat_for_thread_session(tmp_path: Path) -> None:
loop = _make_full_loop(tmp_path)
-4
View File
@@ -18,10 +18,8 @@ from nanobot.session.recovery import REQUEST_ORIGIN_METADATA_KEY
from nanobot.session.turn_continuation import (
INTERNAL_CONTINUATION_KIND_META,
INTERNAL_CONTINUATION_META,
INTERNAL_CONTINUATION_PENDING_META,
INTERNAL_CONTINUATION_RUN_STARTED_AT_META,
_save_skip_for_turn,
internal_continuation_pending,
internal_continuation_run_started_at,
maybe_continue_turn,
should_finalize_on_max_iterations,
@@ -82,7 +80,6 @@ async def test_maybe_continue_turn_queues_internal_message():
assert sustained_goal_continuation_inbound(queued.metadata) is True
assert queued.metadata[INTERNAL_CONTINUATION_RUN_STARTED_AT_META] == 1234.5
assert internal_continuation_run_started_at(queued.metadata) == 1234.5
assert internal_continuation_pending(ctx.msg.metadata)
assert queued.metadata["webui"] is True
assert queued.metadata["message_id"] == "msg-1"
assert queued.metadata[REQUEST_ORIGIN_METADATA_KEY] == {
@@ -97,7 +94,6 @@ async def test_maybe_continue_turn_queues_internal_message():
assert ctx.all_messages == messages[:-1]
assert ctx.final_content == ""
assert ctx.suppress_response is True
assert ctx.msg.metadata[INTERNAL_CONTINUATION_PENDING_META] is True
assert meta["_sustained_goal_continuation_rounds"] == 1