Enterprise agent platform for building, deploying, and operating AI teammates.
feat(v1): report completion_outcome for tasks that set response_format.accept_partial (#3781)
Alex Liue30f246709e3
diff --git a/src/xagent/web/api/v1/_events_stream.py b/src/xagent/web/api/v1/_events_stream.pyindex 5096ef403..ca6fb86d7 100644--- a/src/xagent/web/api/v1/_events_stream.py+++ b/src/xagent/web/api/v1/_events_stream.py@@ -154,7 +154,7 @@ import jsonimport loggingfrom datetime import datetime, timezonefrom time import monotonic-from typing import TYPE_CHECKING, Any, AsyncIterator, Callable, cast+from typing import TYPE_CHECKING, Any, AsyncIterator, Callable, Mapping, castfrom fastapi import WebSocketfrom fastapi.responses import StreamingResponse@@ -166,6 +166,7 @@ from ...models.user import Userfrom ...models.user_api_key import UserApiKeyfrom ...schemas.v1 import PublicStepfrom ...services.db_runtime import run_db_io_cancellation_safe+from ...services.execution_result_projection import completion_outcome_fieldsfrom ...services.public_trace_events import (DELEGATED_AGENT_TRACE_SOURCE,is_audit_only_trace_data,@@ -320,7 +321,8 @@ def _stream_close_reason(status: TaskStatus, control_state: str | None) -> str |# A sync callable: (task_id, principal) -> ``_TaskInfoSnapshot``-shaped# object (duck-typed: ``.status`` / ``.control_state`` / ``.output`` /-# ``.error`` / ``.pending_question``), raising+# ``.error`` / ``.pending_question`` / ``.completion_outcome`` /+# ``.accept_partial``), raising# ``V1ApiError(TASK_NOT_FOUND, 404)`` when the task is missing or not# owned, or ``V1ApiError(TASK_EXPIRED, 410)`` when retention expired a# task the key could have seen (see ``_task_gone_error_frame``); the two@@ -417,6 +419,7 @@ def completed_frame(structured_output: dict[str, Any] | None = None,structured_output_status: str | None = None,structured_output_reason: dict[str, Any] | None = None,+ reported_outcome: Mapping[str, str | None] | None = None,snapshot_total_steps: int | None = None,) -> str:return _sse_frame(@@ -429,6 +432,7 @@ def completed_frame("structured_output": structured_output,"structured_output_status": structured_output_status,"structured_output_reason": structured_output_reason,+ **(reported_outcome or {}),**_snapshot_marker_fields(snapshot_total_steps),},)@@ -446,6 +450,17 @@ def _structured_output_fields(snapshot: "_TaskInfoSnapshot") -> dict[str, Any]:).as_dict()+def _completion_outcome_fields(snapshot: "_TaskInfoSnapshot") -> dict[str, str | None]:+ """The ``completion_outcome`` key of a conclusion frame, from the same+ effective snapshot that supplies its status: empty unless the task's format+ sets accept_partial, as on ``GET /v1/chat/tasks/{task_id}``."""+ return completion_outcome_fields(+ snapshot.status,+ snapshot.completion_outcome,+ accept_partial=snapshot.accept_partial,+ )++def input_required_frame(task_id: int, prompt: str | None, *, snapshot_total_steps: int | None = None) -> str:@@ -1506,6 +1521,7 @@ async def watchdog_check_once(error=snapshot.error,error_code=snapshot.error_code,**_structured_output_fields(snapshot),+ reported_outcome=_completion_outcome_fields(snapshot),))if close_reason == "input_required":@@ -2149,6 +2165,7 @@ def _terminal_snapshot_stream(error=snapshot.error,error_code=snapshot.error_code,**_structured_output_fields(snapshot),+ reported_outcome=_completion_outcome_fields(snapshot),snapshot_total_steps=snapshot_total_steps,)diff --git a/src/xagent/web/api/v1/tasks.py b/src/xagent/web/api/v1/tasks.pyindex d2eb7af85..eba3e23c3 100644--- a/src/xagent/web/api/v1/tasks.py+++ b/src/xagent/web/api/v1/tasks.py@@ -65,6 +65,7 @@ from ...services.api_idempotency import IdempotencyClaimfrom ...services.db_runtime import (run_db_io_cancellation_safe,)+from ...services.execution_result_projection import completion_outcome_fieldsfrom ...services.hot_path_cache import (cache_get,cache_set,@@ -86,6 +87,7 @@ from ...services.response_format import (from ...services.sdk_task_cancel import sdk_cancel_error_codefrom ...services.structured_output_projection import (project_structured_output,+ response_format_accepts_partial,response_format_configured,)from ...services.task_auto_resume import TerminalView, status_only_terminal_view@@ -596,6 +598,11 @@ class _TaskInfoSnapshot:# request, ``None`` for every other row. Cleared like ``error`` wherever# the status shown is not the stored one.error_code: str | None = None+ # Read from the same row: the stored completion rating and whether the+ # task's stored format sets accept_partial, which decides if the response+ # carries a completion_outcome key at all.+ completion_outcome: Any = None+ accept_partial: bool = False# Terminal statuses an append is accepted from. With shared execution the row@@ -875,6 +882,8 @@ def _load_task_info_snapshot(error_code=sdk_cancel_error_code(task.status, cast(str | None, task.error_message)),+ completion_outcome=task.completion_outcome,+ accept_partial=response_format_accepts_partial(task.agent_config),)@@ -1021,7 +1030,8 @@ def _get_chat_task_sync(current. The cached body holds the stored values; the view is appliedto the response after every cache read or write. A queued START isapplied the same way, for the same reason. So are the structured output- fields: the cached body holds them as null.+ fields and the completion_outcome key: the cached body holds the fields+ as null and has no such key."""task = _load_task_info_snapshot(task_id, principal)@@ -1065,6 +1075,15 @@ def _get_chat_task_sync(format_configured=task.format_configured,).as_dict())+ # The key is absent unless the stored format sets accept_partial, so it is+ # only ever added here, never passed to the cached response.+ overlay.update(+ completion_outcome_fields(+ effective_task_snapshot(task).status,+ task.completion_outcome,+ accept_partial=task.accept_partial,+ )+ )cache_key = task_snapshot_key(task_id)task_updated_at = cache_version_token(task.updated_at)cached = cache_get(cache_key)@@ -1730,7 +1749,11 @@ async def stream_chat_task_events(- ``task.completed``: ``{status, output, error, structured_output,structured_output_status, structured_output_reason}``. The threestructured fields carry the same values as the fields of the- same name on ``GET /v1/chat/tasks/{task_id}``. A failed task+ same name on ``GET /v1/chat/tasks/{task_id}``. A+ ``completion_outcome`` key follows them only when the task's+ response format sets accept_partial; its value is completed,+ partial or blocked, or null (null unless the task is completed+ and the run recorded a rating). A failed taskalso ends the stream with this event rather than a separateone -- ``status`` is ``"failed"`` and ``error`` is set.- ``task.input_required``: ``{task_id, prompt}``. ``prompt`` is thediff --git a/src/xagent/web/schemas/v1.py b/src/xagent/web/schemas/v1.pyindex fb7d0f902..b814c0147 100644--- a/src/xagent/web/schemas/v1.py+++ b/src/xagent/web/schemas/v1.py@@ -31,9 +31,11 @@ from pydantic import (BaseModel,ConfigDict,Field,+ SerializerFunctionWrapHandler,StrictBool,StrictInt,StringConstraints,+ model_serializer,)from ..api.skill_hub import _MAX_SKILL_MD_CHARS, _NAME_RE@@ -1356,7 +1358,8 @@ class TaskInfoResponse(BaseModel):Returns a snapshot of the task's current state from the ``tasks``row. ``input`` / ``output`` / ``error`` reflect the **latest** turnonly -- full transcript history is queryable via the ``/steps``- endpoint's ``message`` type steps.+ endpoint's ``message`` type steps. The ``completion_outcome`` key is+ present only when the task's response format sets accept_partial."""task_id: int@@ -1504,6 +1507,31 @@ class TaskInfoResponse(BaseModel):"otherwise."),)+ completion_outcome: Optional[str] = Field(+ None,+ description=(+ "How the agent rated the run shown in this response: completed, "+ "partial or blocked. Present only when the task's response format "+ "sets accept_partial; the key is absent otherwise. When present, "+ "null unless the task is completed and the run recorded a rating. "+ "Whether a structured result is complete is told by "+ "structured_output_status, not by this field."+ ),+ )++ # Responses for a task without accept_partial must stay byte-identical to+ # those of servers that predate this field, so the key is dropped unless+ # the response was built or updated with it. No return annotation: any+ # annotation, Any included, replaces this model's serialization schema in+ # the OpenAPI document.+ @model_serializer(mode="wrap")+ def _omit_unreported_completion_outcome( # type: ignore[no-untyped-def]+ self, handler: SerializerFunctionWrapHandler+ ):+ data = handler(self)+ if "completion_outcome" not in self.model_fields_set:+ data.pop("completion_outcome", None)+ return data# ``PublicStep.type`` is the public surface for what was internally onediff --git a/src/xagent/web/services/execution_result_projection.py b/src/xagent/web/services/execution_result_projection.pyindex 52507457b..59b664d69 100644--- a/src/xagent/web/services/execution_result_projection.py+++ b/src/xagent/web/services/execution_result_projection.py@@ -6,7 +6,7 @@ from dataclasses import dataclassfrom typing import Any, Mappingfrom ...core.agent.execution_adapter import INTERRUPTED_USER_MESSAGE-from ...core.agent.result import normalize_tool_failure_code+from ...core.agent.result import COMPLETION_OUTCOMES, normalize_tool_failure_codefrom ..models.task import TaskStatusfrom .assistant_history_safety import (ASSISTANT_RESPONSE_MESSAGE_TYPE,@@ -60,12 +60,30 @@ def completion_outcome_for_status(return Noneoutcome = result.get("completion_outcome")return (- outcome- if isinstance(outcome, str) and outcome in {"completed", "partial", "blocked"}- else None+ outcome if isinstance(outcome, str) and outcome in COMPLETION_OUTCOMES else None)+def reported_completion_outcome(status: TaskStatus, stored: Any) -> str | None:+ """The completion outcome a task response reports: the stored value when+ the effective status is COMPLETED and the value is a known outcome, else None."""+ if status is not TaskStatus.COMPLETED:+ return None+ return stored if type(stored) is str and stored in COMPLETION_OUTCOMES else None+++def completion_outcome_fields(+ status: TaskStatus, stored: Any, *, accept_partial: bool+) -> dict[str, str | None]:+ """The ``completion_outcome`` key of a task response, as a dict to merge in:+ empty unless the task's format sets accept_partial, so a response for any+ other task carries no such key; otherwise the reported outcome, which may+ be None."""+ if not accept_partial:+ return {}+ return {"completion_outcome": reported_completion_outcome(status, stored)}++def execution_result_diagnostic_error(result: Mapping[str, Any]) -> str:"""Owner-facing diagnostic text for a failed result: the dedicated key first, then ``error``.diff --git a/src/xagent/web/services/structured_output_projection.py b/src/xagent/web/services/structured_output_projection.pyindex 3c1d4311c..ce4f96669 100644--- a/src/xagent/web/services/structured_output_projection.py+++ b/src/xagent/web/services/structured_output_projection.py@@ -196,6 +196,15 @@ def response_format_configured(agent_config: Any) -> bool:)+def response_format_accepts_partial(agent_config: Any) -> bool:+ """Whether the stored format of ``agent_config`` sets accept_partial: the+ format is a dict whose accept_partial is exactly True."""+ if type(agent_config) is not dict:+ return False+ stored = agent_config.get(RESPONSE_FORMAT_CONFIG_KEY)+ return type(stored) is dict and stored.get("accept_partial") is True++def _reason_fields(code: str,lists: dict[str, list[str]] | None = None,diff --git a/tests/web/api/v1/structured_output_shared.py b/tests/web/api/v1/structured_output_shared.pyindex ef22620a4..a1a73e424 100644--- a/tests/web/api/v1/structured_output_shared.py+++ b/tests/web/api/v1/structured_output_shared.py@@ -7,14 +7,17 @@ from __future__ import annotationsimport refrom collections.abc import Iteratorfrom contextlib import contextmanager+from dataclasses import replacefrom datetime import datetime, timezonefrom typing import Anyfrom sqlalchemy import event+from xagent.web.api.v1 import tasks as v1_tasksfrom xagent.web.models.agent import Agentfrom xagent.web.models.database import get_enginefrom xagent.web.models.task import Task, TaskStatus+from xagent.web.services.task_auto_resume import TerminalViewfrom ..conftest import _admin_headers, _direct_db_session, client@@ -56,6 +59,7 @@ def insert_task(error: str | None = None,title: str = "structured output task",moment: datetime | None = None,+ completion_outcome: str | None = None,) -> int:"""One SDK task row, with its structured output record and agent_config."""db = _direct_db_session()@@ -74,6 +78,7 @@ def insert_task(run_id=run_id,agent_config=agent_config,error_message=error,+ completion_outcome=completion_outcome,)if moment is not None:task.created_at = moment@@ -115,6 +120,22 @@ def task_selects(statements: list[str]) -> list[str]:FORMAT_CONFIG = {"response_format": {"type": "json_schema", "name": "answer"}}+++def stored_format_config(**switch: bool) -> dict[str, Any]:+ """The agent_config of a task whose stored format is complete, with the+ accept_partial switch stored as given (not stored when not given)."""+ return {+ "response_format": {+ "type": "json_schema",+ "name": "answer",+ "schema": {"type": "object", "properties": {}},+ "description": None,+ **switch,+ }+ }++MOMENT = datetime(2026, 11, 1, 8, 30, tzinfo=timezone.utc)RECORD = {"run_id": "run-1",@@ -140,3 +161,55 @@ BASELINE_TASKS: list[dict[str, Any]] = [{"status": TaskStatus.COMPLETED, "output": "\u00e9 \u4e2d\u6587 \U0001f600"},]NEW_KEYS = ("structured_output", "structured_output_status", "structured_output_reason")++# The keys of a GET task response and of a task.completed frame for a task+# without accept_partial, in order.+TODAY_TASK_INFO_KEYS = (+ "task_id",+ "agent_id",+ "workforce_id",+ "status",+ "run_id",+ "state_version",+ "control_state",+ "input",+ "output",+ "error",+ "error_code",+ "created_at",+ "completed_at",+ "pending_interaction",+ *NEW_KEYS,+)+TODAY_COMPLETED_FRAME_KEYS = ("status", "output", "error", "error_code", *NEW_KEYS)++SWITCH_OFF_CONFIGS = {+ "no-format": None,+ "no-switch": stored_format_config(),+ "switch-false": stored_format_config(accept_partial=False),+}+SWITCH_ON_CONFIG = stored_format_config(accept_partial=True)+TERMINAL_VIEW = TerminalView(+ state="stopped", error="stopped", stopped_at=MOMENT, reason="x"+)++# (id, rating stored on the row, snapshot changes that make the effective state)+EFFECTIVE_STATES = [+ ("completed-completed", "completed", {}),+ ("completed-partial", "partial", {}),+ ("completed-blocked", "blocked", {}),+ ("completed-unrated", None, {}),+ ("pending", "partial", {"start_queued": True}),+ ("failed-view", "partial", {"view": TERMINAL_VIEW}),+]+++def with_snapshot(monkeypatch, **changes) -> None:+ """Make the v1 task snapshot reader return the row's snapshot with+ ``changes`` applied."""+ real = v1_tasks._load_task_info_snapshot+ monkeypatch.setattr(+ v1_tasks,+ "_load_task_info_snapshot",+ lambda task_id, principal: replace(real(task_id, principal), **changes),+ )diff --git a/tests/web/api/v1/test_events_stream.py b/tests/web/api/v1/test_events_stream.pyindex 03afa5e1d..dc5f4e01c 100644--- a/tests/web/api/v1/test_events_stream.py+++ b/tests/web/api/v1/test_events_stream.py@@ -106,6 +106,8 @@ NO_STRUCTURED_OUTPUT = {"structured_output_record": None,"format_configured": False,"error_code": None,+ "completion_outcome": None,+ "accept_partial": False,}NULL_STRUCTURED_OUTPUT_FIELDS = {"error_code": None,diff --git a/tests/web/api/v1/test_structured_output_events.py b/tests/web/api/v1/test_structured_output_events.pyindex 590b4fa43..dd64cd01d 100644--- a/tests/web/api/v1/test_structured_output_events.py+++ b/tests/web/api/v1/test_structured_output_events.py@@ -8,22 +8,33 @@ from typing import Anyimport pytest+from xagent.core.agent.result import COMPLETION_OUTCOMESfrom xagent.web.api.v1 import _events_stream as esfrom xagent.web.api.v1 import tasks as v1_tasksfrom xagent.web.models.task import TaskStatusfrom xagent.web.services import structured_output_projection+from xagent.web.services.hot_path_cache import (+ InMemoryTTLCache,+ set_cache_backend_for_testing,+)from ..conftest import clientfrom .structured_output_shared import (COLUMN,+ EFFECTIVE_STATES,FORMAT_CONFIG,NEW_KEYS,RECORD,+ SWITCH_OFF_CONFIGS,+ SWITCH_ON_CONFIG,+ TODAY_COMPLETED_FRAME_KEYS,+ TODAY_TASK_INFO_KEYS,bearer,create_agent_with_key,insert_task,recorded_statements,task_selects,+ with_snapshot,)from .test_events_stream import _principal_for@@ -247,3 +258,132 @@ def test_the_response_and_the_frame_return_the_same_result_and_reason(name):assert response["structured_output_status"] == record["status"]if record["reason"] is not None:assert response["structured_output_reason"]["code"] == record["reason"]["code"]+++# --- the completion_outcome key -------------------------------------------------++SURFACES = ["get-miss", "get-hit", "sse-attach", "sse-watchdog"]+# A queued start has no conclusion frame, so only GET shows that state.+CASES = [+ pytest.param(surface, rating, changes, id=f"{surface}-{name}")+ for surface in SURFACES+ for name, rating, changes in EFFECTIVE_STATES+ if surface.startswith("get") or "start_queued" not in changes+]+++async def _watchdog_frame(key: str, task_id: int) -> dict[str, Any]:+ principal = _principal_for(key)+ sink = es.V1EventStreamSink(+ task_id=task_id,+ principal_key_prefix=principal.key.key_prefix,+ initial_status="running",+ )+ closed = await es.watchdog_check_once(+ sink,+ task_id,+ principal,+ read_task_snapshot=lambda tid, p: v1_tasks.effective_task_snapshot(+ v1_tasks._load_task_info_snapshot(tid, p)+ ),+ )+ assert closed is True+ frame, _is_close = sink.queue.get_nowait()+ return json.loads(frame.split("data: ", 1)[1])+++async def _read(surface: str, key: str, task_id: int, request) -> dict[str, Any]:+ """The parsed body of a GET response or of a conclusion frame."""+ if surface == "sse-attach":+ return completed_data(key, task_id)[0]+ if surface == "sse-watchdog":+ return await _watchdog_frame(key, task_id)+ if surface == "get-hit":+ set_cache_backend_for_testing(InMemoryTTLCache())+ request.addfinalizer(lambda: set_cache_backend_for_testing(None))+ client.get(f"/v1/chat/tasks/{task_id}", headers=bearer(key))+ return client.get(f"/v1/chat/tasks/{task_id}", headers=bearer(key)).json()+++def _today_keys(surface: str) -> tuple[str, ...]:+ return (+ TODAY_TASK_INFO_KEYS+ if surface.startswith("get")+ else TODAY_COMPLETED_FRAME_KEYS+ )++[email protected](("surface", "rating", "changes"), CASES)[email protected]("config", SWITCH_OFF_CONFIGS.values(), ids=SWITCH_OFF_CONFIGS)+async def test_switch_off_responses_have_no_completion_outcome(+ config, surface, rating, changes, monkeypatch, request+):+ agent_id, key = create_agent_with_key()+ task_id = insert_task(agent_id, agent_config=config, completion_outcome=rating)+ with_snapshot(monkeypatch, **changes)++ body = await _read(surface, key, task_id, request)++ assert tuple(body) == _today_keys(surface)++[email protected](("surface", "rating", "changes"), CASES)+async def test_switch_on_responses_end_with_the_reported_outcome(+ surface, rating, changes, monkeypatch, request+):+ agent_id, key = create_agent_with_key()+ task_id = insert_task(+ agent_id, agent_config=SWITCH_ON_CONFIG, completion_outcome=rating+ )+ with_snapshot(monkeypatch, **changes)++ body = await _read(surface, key, task_id, request)++ assert tuple(body) == (*_today_keys(surface), "completion_outcome")+ assert body["completion_outcome"] == (rating if not changes else None)++[email protected]("rating", [*sorted(COMPLETION_OUTCOMES), None])+def test_the_response_and_the_frame_return_the_same_completion_outcome(rating):+ agent_id, key = create_agent_with_key()+ task_id = insert_task(+ agent_id,+ record=RECORD,+ agent_config=SWITCH_ON_CONFIG,+ completion_outcome=rating,+ )++ data, _raw = completed_data(key, task_id)+ response = client.get(f"/v1/chat/tasks/{task_id}", headers=bearer(key)).json()++ assert data["completion_outcome"] == response["completion_outcome"] == rating+++ ("reported", "snapshot_total_steps", "expected_tail"),+ [+ (None, None, ()),+ (+ {"completion_outcome": "partial"},+ 3,+ ("completion_outcome", "snapshot_truncated", "snapshot_total_steps"),+ ),+ ],+ ids=["not-given", "before-the-truncation-marker"],+)+def test_the_completion_outcome_key_of_a_built_frame(+ reported, snapshot_total_steps, expected_tail+):+ frame = es.completed_frame(+ status=TaskStatus.COMPLETED.value,+ output="x",+ error=None,+ error_code=None,+ reported_outcome=reported,+ snapshot_total_steps=snapshot_total_steps,+ )++ data = json.loads(frame.split("data: ", 1)[1])+ assert tuple(data) == (*TODAY_COMPLETED_FRAME_KEYS, *expected_tail)diff --git a/tests/web/api/v1/test_structured_output_get.py b/tests/web/api/v1/test_structured_output_get.pyindex 7de5b4d0b..e1d87f0c3 100644--- a/tests/web/api/v1/test_structured_output_get.py+++ b/tests/web/api/v1/test_structured_output_get.py@@ -4,12 +4,10 @@ projected from it."""from __future__ import annotationsimport json-from dataclasses import replaceimport pytestfrom tests.web.services.test_structured_output_projection import MESSAGES-from xagent.web.api.v1 import tasks as v1_tasksfrom xagent.web.models.task import Taskfrom xagent.web.schemas.v1 import TaskInfoResponsefrom xagent.web.services.hot_path_cache import (@@ -30,11 +28,14 @@ from .structured_output_shared import (MOMENT,NEW_KEYS,RECORD,+ SWITCH_ON_CONFIG,+ TERMINAL_VIEW,bearer,create_agent_with_key,insert_task,recorded_statements,task_selects,+ with_snapshot,)pytestmark = pytest.mark.usefixtures("_test_db")@@ -99,6 +100,7 @@ def test_the_response_models_new_fields_all_default_to_none():assert response.structured_output is Noneassert response.structured_output_status is Noneassert response.structured_output_reason is None+ assert response.completion_outcome is Nonedef test_a_ready_record_of_the_current_run_is_returned_in_stored_key_order():@@ -148,17 +150,6 @@ def test_the_existing_fields_are_byte_identical_to_the_recorded_baseline():assert json.dumps(body, ensure_ascii=False, separators=(",", ":")) == expected-# A record of the run the task shows, with a format configured: what a reader-# would report if nothing hid it.-def _with_snapshot(monkeypatch, **changes):- real = v1_tasks._load_task_info_snapshot- monkeypatch.setattr(- v1_tasks,- "_load_task_info_snapshot",- lambda task_id, principal: replace(real(task_id, principal), **changes),- )--def test_a_record_of_an_earlier_run_is_not_shown_for_the_current_run():agent_id, key = create_agent_with_key()stale = insert_task(@@ -178,7 +169,7 @@ def test_a_record_of_an_earlier_run_is_not_shown_for_the_current_run():def test_a_queued_start_hides_the_record_of_the_previous_run(monkeypatch):agent_id, key = create_agent_with_key()task_id = insert_task(agent_id, record=RECORD, agent_config=FORMAT_CONFIG)- _with_snapshot(monkeypatch, start_queued=True)+ with_snapshot(monkeypatch, start_queued=True)body = get(key, task_id).json()@@ -190,7 +181,7 @@ def test_a_terminal_view_hides_the_record(monkeypatch):agent_id, key = create_agent_with_key()task_id = insert_task(agent_id, record=RECORD, agent_config=FORMAT_CONFIG)view = TerminalView(state="stopped", error="stopped", stopped_at=MOMENT, reason="x")- _with_snapshot(monkeypatch, view=view)+ with_snapshot(monkeypatch, view=view)body = get(key, task_id).json()@@ -253,3 +244,27 @@ def test_the_message_of_a_reason_is_the_fixed_text_of_its_code(code):assert "missing_fields" not in resp.textif code not in ("information_missing", "value_not_expressible"):assert "unexpressible_fields" not in resp.text+++# --- the completion_outcome key -------------------------------------------------+++ "changes",+ [{}, {"start_queued": True}, {"view": TERMINAL_VIEW}],+ ids=["none", "start-queued", "view"],+)+def test_the_cache_body_never_holds_completion_outcome(+ changes, monkeypatch, task_cache+):+ agent_id, key = create_agent_with_key()+ task_id = insert_task(+ agent_id, agent_config=SWITCH_ON_CONFIG, completion_outcome="partial"+ )+ with_snapshot(monkeypatch, **changes)++ first = get(key, task_id)+ second = get(key, task_id)++ assert "completion_outcome" not in cache_get(task_snapshot_key(task_id))["response"]+ assert second.text == first.textdiff --git a/tests/web/services/test_completion_outcome_fields.py b/tests/web/services/test_completion_outcome_fields.pynew file mode 100644index 000000000..c9f0c0216--- /dev/null+++ b/tests/web/services/test_completion_outcome_fields.py@@ -0,0 +1,82 @@+"""The ``completion_outcome`` key of a task response: when it is present and+what it holds."""++from __future__ import annotations++from typing import Any++import pytest++from xagent.core.agent.result import COMPLETION_OUTCOMES+from xagent.web.models.task import TaskStatus+from xagent.web.services import execution_result_projection as projection+from xagent.web.services import structured_output_projection as format_projection++STORED_VALUES: list[Any] = [*sorted(COMPLETION_OUTCOMES), None, "other", ["list"]]+++def _is_rating(value: Any) -> bool:+ return type(value) is str and value in COMPLETION_OUTCOMES++[email protected]("accept_partial", [True, False])[email protected]("stored", STORED_VALUES, ids=repr)[email protected]("status", list(TaskStatus))+def test_completion_outcome_fields(status, stored, accept_partial):+ fields = projection.completion_outcome_fields(+ status, stored, accept_partial=accept_partial+ )++ if not accept_partial:+ assert fields == {}+ return+ known = status is TaskStatus.COMPLETED and _is_rating(stored)+ assert fields == {"completion_outcome": stored if known else None}+++ ("agent_config", "expected"),+ [+ (None, False),+ ("response_format", False),+ ({}, False),+ ({"response_format": None}, False),+ ({"response_format": {"type": "json_schema"}}, False),+ ({"response_format": {"accept_partial": True}}, True),+ ({"response_format": {"accept_partial": False}}, False),+ ({"response_format": {"accept_partial": 1}}, False),+ ({"response_format": {"accept_partial": "true"}}, False),+ ({"response_format": "accept_partial"}, False),+ ],+)+def test_the_switch_is_on_only_when_stored_as_exactly_true(agent_config, expected):+ assert format_projection.response_format_accepts_partial(agent_config) is expected++[email protected]("status", list(TaskStatus))[email protected]("outcome", STORED_VALUES, ids=repr)+def test_completion_outcomes_single_source(status, outcome):+ result = {"completion_outcome": outcome}++ expected = (+ outcome if status is TaskStatus.COMPLETED and _is_rating(outcome) else None+ )+ assert projection.completion_outcome_for_status(result, status) == expected+++ "read",+ [+ lambda: projection.completion_outcome_for_status(+ {"completion_outcome": "extra"}, TaskStatus.COMPLETED+ ),+ lambda: projection.reported_completion_outcome(TaskStatus.COMPLETED, "extra"),+ ],+ ids=["for_status", "reported"],+)+def test_the_ratings_follow_the_shared_set(monkeypatch, read):+ monkeypatch.setattr(+ projection, "COMPLETION_OUTCOMES", COMPLETION_OUTCOMES | {"extra"}+ )++ assert read() == "extra"diff --git a/tests/web/services/test_standby_startup.py b/tests/web/services/test_standby_startup.pyindex 3a890fa7b..fff77d4a4 100644--- a/tests/web/services/test_standby_startup.py+++ b/tests/web/services/test_standby_startup.py@@ -28,6 +28,7 @@ from tests.integration.test_auto_migration_startup import ( # noqa: F401)from xagent.config import STANDBY as STANDBY_ENVfrom xagent.web.models import database as database_module+from xagent.web.services import task_executionfrom xagent.web.services.release_hold import release_holdfrom xagent.web.services.standby import StandbyPhase, standby@@ -336,6 +337,14 @@ async def test_shutdown_cleans_sandboxes_only_when_it_owned_them("stop_app_process_diagnostics",):monkeypatch.setattr(app_module, name, AsyncMock())+ # shutdown_event() leaves the process-wide background task manager refusing+ # work, and nothing in this process reopens it, so give it a fresh one:+ # later tests in this process still need the shared manager to accept work.+ monkeypatch.setattr(+ task_execution,+ "background_task_manager",+ task_execution.BackgroundTaskManager(),+ )if started_as_standby:standby.begin()diff --git a/tests/web/test_openapi_document.py b/tests/web/test_openapi_document.pyindex 13f624616..237f621b7 100644--- a/tests/web/test_openapi_document.py+++ b/tests/web/test_openapi_document.py@@ -13,6 +13,7 @@ from typing import Any, Iteratorimport pytest+from tests.web.api.v1.structured_output_shared import TODAY_TASK_INFO_KEYSfrom xagent.web.app import appfrom xagent.web.services.global_memory_embedding_authority import (AuthorityConfiguration,@@ -81,3 +82,15 @@ def test_the_document_carries_no_root_defs(document):"""``$defs`` is a schema-local keyword; nothing may reference it as a root."""assert "$defs" not in documentassert not [ref for ref in _refs(document) if ref.startswith("#/$defs/")]+++def test_task_info_openapi_keeps_properties(document):+ schemas = document["components"]["schemas"]+ task_info = schemas["TaskInfoResponse"]++ assert list(task_info["properties"]) == [+ *TODAY_TASK_INFO_KEYS,+ "completion_outcome",+ ]+ assert task_info["required"] == ["task_id", "agent_id", "status", "created_at"]+ assert not [name for name in schemas if name.startswith("TaskInfoResponse-")]