From cf91369d8cbef30794556487014b3b2f8fe7807c Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:57:07 +0800 Subject: [PATCH 1/4] fix(chat): steer the current private Steward turn from the App Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../native_chat/queued_admission.py | 35 ++++++++++ loopx/chat_server.py | 8 ++- tests/test_lark_private_conversations.py | 68 +++++++++++++++++++ 3 files changed, 110 insertions(+), 1 deletion(-) diff --git a/loopx/capabilities/native_chat/queued_admission.py b/loopx/capabilities/native_chat/queued_admission.py index 18dcd08c5f..92a3b20e46 100644 --- a/loopx/capabilities/native_chat/queued_admission.py +++ b/loopx/capabilities/native_chat/queued_admission.py @@ -67,6 +67,41 @@ def enqueue_turn(controller: Any, *, session_id: str, client_turn_id: str, messa return turn, created +def steer_web_turn(controller: Any, *, session_id: str, expected_turn_id: str, + client_ingress_id: str, message: str) -> tuple[dict[str, Any], bool]: + """Apply the loopback App's steering input to its existing private Session.""" + session = controller.store.load_session(session_id) + saved = (session or {}).get("steward_context") or {} + if saved.get("audience") != "bound_owner": + return controller.steer_active_turn(session_id=session_id, expected_turn_id=expected_turn_id, + client_ingress_id=client_ingress_id, message=message) + contexts = controller.project_contexts + bindings = contexts.conversation_bindings + if bindings is None or controller.registry_path is None: + raise ValueError("bound steward authority is unavailable") + + from ...chat_manager_context import manager_authorization_scope_id_for_registry + + # Reuse the local Web source grant. Keep its binding fence through the + # exact-Turn receipt and native delivery, including concurrent revocation. + with bindings.input_context(saved, origin="web", session=session, store=controller.store) as selected: + fresh = controller.store.load_session(session_id) + if fresh is None or fresh.get("status") == "closed": + raise KeyError("chat session was not found") + if any(fresh.get(key) != session.get(key) for key in + ("steward_context", "project_context", "channel_id", "goal_id", "agent_id", "executor_endpoint_id")): + raise ValueError("bound Session changed before input admission") + contexts.runtime_context(fresh, selected) + scope = manager_authorization_scope_id_for_registry(controller.registry_path, + selected["context"]["goal_ids"], runtime_root=controller.coordination_runtime_root, + channel_id=fresh["channel_id"]) + if scope is None or scope != fresh.get("manager_authorization_scope_id"): + raise ValueError("bound steward authorization changed before steering") + with controller.store.steering_delivery_lock(session_id, client_ingress_id): + return controller._steer_active_turn(session=fresh, session_id=session_id, expected_turn_id=expected_turn_id, + client_ingress_id=client_ingress_id, message=message, _queued_turn_id=None, origin="web") + + def deliver_native_mention( controller, *, session_id: str, ingress_id: str, target_turn_id: str | None, binding_matches: bool, text_only: bool, may_deliver_new: bool, diff --git a/loopx/chat_server.py b/loopx/chat_server.py index e2c38a1590..17ff027292 100644 --- a/loopx/chat_server.py +++ b/loopx/chat_server.py @@ -9,6 +9,7 @@ import uuid from collections.abc import Callable, Mapping import webbrowser +from functools import partial from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from typing import TYPE_CHECKING, Any, Literal, cast @@ -1086,7 +1087,12 @@ def _steer_turn(self, session_id: str, turn_id: str) -> None: raise ValueError("a message of 1–12000 characters is required") if not isinstance(ingress_id, str) or not ingress_id.strip(): raise ValueError("client_ingress_id is required") - turn, created = self.server.runtime_controller.steer_active_turn( + controller = self.server.runtime_controller + steer = controller.steer_active_turn + if is_loopback_host(str(self.server.server_address[0])): + from .capabilities.native_chat.queued_admission import steer_web_turn + steer = partial(steer_web_turn, controller) + turn, created = steer( session_id=session_id, expected_turn_id=turn_id, client_ingress_id=ingress_id, message=message, ) diff --git a/tests/test_lark_private_conversations.py b/tests/test_lark_private_conversations.py index d7279ddd8f..29bd31a790 100644 --- a/tests/test_lark_private_conversations.py +++ b/tests/test_lark_private_conversations.py @@ -6977,6 +6977,74 @@ def slow_source(*args, **kwargs): runtime.close() +def test_private_steward_app_steering_delivers_once_to_the_original_turn(tmp_path): + from loopx.chat_server import ChatHTTPServer, ChatRequestHandler + from test_native_steward_private import steward + + fixture = steward.__wrapped__(tmp_path) + store, runtime, provider, transport, binding, capture, _ = next(fixture) + server = ChatHTTPServer(("127.0.0.1", 0), ChatRequestHandler) + server.chat_store, server.runtime_controller = store, runtime + server.runtime_root, server.registry_path = store.root.parent, runtime.registry_path + server.selected_goal_id, server.verbose = None, False + worker = threading.Thread(target=server.serve_forever, daemon=True) + worker.start() + + def request(method, path, body=None): + connection = http.client.HTTPConnection(*server.server_address, timeout=15) + try: + connection.request(method, path, None if body is None else json.dumps(body), + headers={"Content-Type": "application/json"}) + response = connection.getresponse() + return response.status, json.loads(response.read()) + finally: + connection.close() + + try: + event = provider.event("steward-app", "original-private-input", "wait for steer") + assert transport.admit("steward-app", event)["status"] == "durably_accepted" + original, = transport.core.pending() + _wait_private_upstream(store, original) + sid, tid = original["session_id"], original["turn_id"] + session_path = f"/api/chat/sessions/{sid}" + endpoint = f"{session_path}/turns/{tid}/steer" + correction = {"message": "Correct the current inspection.", "client_ingress_id": "app-correction"} + + status, refused = request("POST", f"{session_path}/turns/old-turn/steer", + {**correction, "client_ingress_id": "wrong-turn"}) + assert status == 409 and refused["delivery_state"] == "not_delivered" + provider.owner_ready = False + assert request("POST", endpoint, correction)[0] == 400 + assert store.steering_receipt(sid, "app-correction") is None + provider.owner_ready = True + + status, delivered = request("POST", endpoint, correction) + assert status == 200 and delivered["created"] is True and delivered["turn_id"] == tid + completed = runtime.wait_for_turn(session_id=sid, turn_id=tid, timeout_sec=10) + assert completed["status"] == "completed" + status, duplicate = request("POST", endpoint, correction) + assert status == 200 and duplicate["created"] is False and duplicate["turn_id"] == tid + status, history = request("GET", session_path) + assert status == 200 + entry, = [row for row in history["messages"] if row["text"] == correction["message"]] + assert entry["turn_id"] == tid and entry["origin"] == "web" + + transport.bindings.disconnect(binding["binding_id"], expected_revision=transport.bindings.read()["revision"]) + assert request("POST", endpoint, {**correction, "client_ingress_id": "revoked-input"})[0] == 400 + assert store.steering_receipt(sid, "revoked-input") is None + calls = [json.loads(line) for line in capture.read_text().splitlines()] + steer, = [call["params"] for call in calls if call["method"] == "turn/steer"] + assert steer["expectedTurnId"] == completed["upstream_turn_id"] + assert steer["input"] == [{"type": "text", "text": correction["message"]}] + assert sum(call["method"] == "turn/start" for call in calls) == 1 + assert not store.queued_turns(sid) + finally: + server.shutdown() + server.server_close() + worker.join(timeout=2) + fixture.close() + + def test_private_steward_native_mention_uses_original_manager_turn(tmp_path, monkeypatch): from test_native_steward_private import steward From 97a7a390ff3a7a7380efc94aa19bf19ea2de072a Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:00:10 +0800 Subject: [PATCH 2/4] Type the private App steering admission Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/capabilities/native_chat/queued_admission.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/loopx/capabilities/native_chat/queued_admission.py b/loopx/capabilities/native_chat/queued_admission.py index 92a3b20e46..ac6fff33d3 100644 --- a/loopx/capabilities/native_chat/queued_admission.py +++ b/loopx/capabilities/native_chat/queued_admission.py @@ -2,7 +2,7 @@ import hashlib import json from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any from ...chat_attachments import require_text_document_route from ...attached_session import enqueue_attached_agent_turn @@ -10,6 +10,9 @@ from ...control_plane.collaboration import conversation_scope from . import project_context as project_context_policy +if TYPE_CHECKING: + from ...chat_runtime import ChatRuntimeController + def enqueue_turn(controller: Any, *, session_id: str, client_turn_id: str, message: str, attachments: list[dict[str, Any]] | None, work_dir: Path | None, objective: str, @@ -67,14 +70,14 @@ def enqueue_turn(controller: Any, *, session_id: str, client_turn_id: str, messa return turn, created -def steer_web_turn(controller: Any, *, session_id: str, expected_turn_id: str, +def steer_web_turn(controller: "ChatRuntimeController", *, session_id: str, expected_turn_id: str, client_ingress_id: str, message: str) -> tuple[dict[str, Any], bool]: """Apply the loopback App's steering input to its existing private Session.""" session = controller.store.load_session(session_id) - saved = (session or {}).get("steward_context") or {} - if saved.get("audience") != "bound_owner": + if session is None or (session.get("steward_context") or {}).get("audience") != "bound_owner": return controller.steer_active_turn(session_id=session_id, expected_turn_id=expected_turn_id, client_ingress_id=client_ingress_id, message=message) + saved = session["steward_context"] contexts = controller.project_contexts bindings = contexts.conversation_bindings if bindings is None or controller.registry_path is None: From 6c3764556327ec768ef0e85234f4ebc145bd45b6 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:17:00 +0800 Subject: [PATCH 3/4] Steer the original queued App input in private Steward sessions Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/capabilities/native_chat/queue_api.py | 9 ++- .../native_chat/queued_admission.py | 49 +++++++++++++---- loopx/chat_runtime.py | 47 ++++++++++------ loopx/control_plane/chat_turn_acceptance.py | 4 +- .../turn_driver/chat_queue_steering.ts | 1 + .../chat_queue_steering.test.ts | 12 ++++ tests/test_lark_private_conversations.py | 55 ++++++++++++++----- 7 files changed, 134 insertions(+), 43 deletions(-) diff --git a/loopx/capabilities/native_chat/queue_api.py b/loopx/capabilities/native_chat/queue_api.py index a06118a3ec..6f85374c60 100644 --- a/loopx/capabilities/native_chat/queue_api.py +++ b/loopx/capabilities/native_chat/queue_api.py @@ -1,9 +1,11 @@ """HTTP transport for original Session Tasks and the existing persisted queue.""" +from functools import partial from typing import Any from urllib.parse import parse_qs, urlparse from ...chat_store import CHAT_STORE_SCHEMA_VERSION +from ...status_server import is_loopback_host class ChatQueueRequestMixin: @@ -121,7 +123,12 @@ def _steer_queued_turn(self, session_id: str, queued_turn_id: str) -> None: for key in body: if not isinstance(body[key], str) or not body[key] or len(body[key]) > 160: raise ValueError("invalid queue steering identity") - result = self.server.runtime_controller.steer_queued_turn(session_id=session_id, + controller = self.server.runtime_controller + steer = controller.steer_queued_turn + if is_loopback_host(str(self.server.server_address[0])): + from .queued_admission import steer_queued_web_turn + steer = partial(steer_queued_web_turn, controller) + result = steer(session_id=session_id, queued_turn_id=queued_turn_id, expected_turn_id=body["target_turn_id"], client_ingress_id=body["client_ingress_id"]) self._send_json({"ok": True, **result}) diff --git a/loopx/capabilities/native_chat/queued_admission.py b/loopx/capabilities/native_chat/queued_admission.py index ac6fff33d3..6af99bb624 100644 --- a/loopx/capabilities/native_chat/queued_admission.py +++ b/loopx/capabilities/native_chat/queued_admission.py @@ -1,6 +1,8 @@ """IO admission to the existing same-Session queue; Core owns source authority.""" import hashlib import json +from collections.abc import Iterator +from contextlib import contextmanager from pathlib import Path from typing import TYPE_CHECKING, Any @@ -70,13 +72,14 @@ def enqueue_turn(controller: Any, *, session_id: str, client_turn_id: str, messa return turn, created -def steer_web_turn(controller: "ChatRuntimeController", *, session_id: str, expected_turn_id: str, - client_ingress_id: str, message: str) -> tuple[dict[str, Any], bool]: - """Apply the loopback App's steering input to its existing private Session.""" +@contextmanager +def bound_steward_web_steering_context(controller: "ChatRuntimeController", + session_id: str) -> Iterator[dict[str, Any] | None]: + """Authorize steering from the loopback App across the binding fence.""" session = controller.store.load_session(session_id) if session is None or (session.get("steward_context") or {}).get("audience") != "bound_owner": - return controller.steer_active_turn(session_id=session_id, expected_turn_id=expected_turn_id, - client_ingress_id=client_ingress_id, message=message) + yield None + return saved = session["steward_context"] contexts = controller.project_contexts bindings = contexts.conversation_bindings @@ -100,9 +103,36 @@ def steer_web_turn(controller: "ChatRuntimeController", *, session_id: str, expe channel_id=fresh["channel_id"]) if scope is None or scope != fresh.get("manager_authorization_scope_id"): raise ValueError("bound steward authorization changed before steering") - with controller.store.steering_delivery_lock(session_id, client_ingress_id): - return controller._steer_active_turn(session=fresh, session_id=session_id, expected_turn_id=expected_turn_id, - client_ingress_id=client_ingress_id, message=message, _queued_turn_id=None, origin="web") + yield fresh + + +def steer_admitted_web_turn(controller: "ChatRuntimeController", session: dict[str, Any], *, + expected_turn_id: str, client_ingress_id: str, message: str, + queued_turn_id: str | None = None) -> tuple[dict[str, Any], bool]: + session_id = session["session_id"] + with controller.store.steering_delivery_lock(session_id, client_ingress_id): + return controller._steer_active_turn(session=session, session_id=session_id, expected_turn_id=expected_turn_id, + client_ingress_id=client_ingress_id, message=message, _queued_turn_id=queued_turn_id, origin="web") + + +def steer_web_turn(controller: "ChatRuntimeController", *, session_id: str, expected_turn_id: str, + client_ingress_id: str, message: str) -> tuple[dict[str, Any], bool]: + with bound_steward_web_steering_context(controller, session_id) as session: + if session is None: + return controller.steer_active_turn(session_id=session_id, expected_turn_id=expected_turn_id, + client_ingress_id=client_ingress_id, message=message) + return steer_admitted_web_turn(controller, session, expected_turn_id=expected_turn_id, + client_ingress_id=client_ingress_id, message=message) + + +def steer_queued_web_turn(controller: "ChatRuntimeController", *, session_id: str, queued_turn_id: str, + expected_turn_id: str, client_ingress_id: str) -> dict[str, Any]: + with bound_steward_web_steering_context(controller, session_id) as session: + if session is None: + return controller.steer_queued_turn(session_id=session_id, queued_turn_id=queued_turn_id, + expected_turn_id=expected_turn_id, client_ingress_id=client_ingress_id) + return controller._steer_queued_turn(session_id=session_id, queued_turn_id=queued_turn_id, + expected_turn_id=expected_turn_id, client_ingress_id=client_ingress_id, admitted_steward=session) def deliver_native_mention( @@ -210,8 +240,7 @@ def reconcile_steering_delivery(controller, session, receipt) -> dict[str, Any] from .codex_adapter import CodexAppServerAdapter from ...control_plane.effect_runtime import effect_runtime_result - with controller.lock: - adapter = controller.adapters.get(session["session_id"]) + adapter = controller.adapters.get(session["session_id"]) if not isinstance(adapter, CodexAppServerAdapter) or not adapter.healthcheck(): return None capture = receipt.get("native_steering") diff --git a/loopx/chat_runtime.py b/loopx/chat_runtime.py index acfa28907a..40ff3efa21 100644 --- a/loopx/chat_runtime.py +++ b/loopx/chat_runtime.py @@ -527,8 +527,17 @@ def steer_queued_turn( Only a proven non-delivery restores FIFO eligibility. A lost native acknowledgement keeps the original input durably reserved. """ - from .control_plane.chat_turn_acceptance import plan_queued_chat_steering self._require_steering_session(session_id) + return self._steer_queued_turn(session_id=session_id, queued_turn_id=queued_turn_id, + expected_turn_id=expected_turn_id, client_ingress_id=client_ingress_id) + + def _steer_queued_turn( + self, *, session_id: str, queued_turn_id: str, expected_turn_id: str, + client_ingress_id: str, admitted_steward: dict[str, Any] | None = None, + ) -> dict[str, Any]: + from .capabilities.native_chat.queued_admission import steer_admitted_web_turn + from .control_plane.chat_turn_acceptance import plan_queued_chat_steering + ingress_id = "queue-steer-" + hashlib.sha256( json.dumps([session_id, queued_turn_id, client_ingress_id]).encode() ).hexdigest()[:40] @@ -537,28 +546,30 @@ def steer_queued_turn( turn = self.store.load_turn(session_id, queued_turn_id) if session is None or turn is None: raise KeyError("chat turn was not found") + if admitted_steward is not None and any(session.get(key) != admitted_steward.get(key) for key in ( + "steward_context", "project_context", "channel_id", "goal_id", "agent_id", + "executor_endpoint_id", "manager_authorization_scope_id", + )): + raise ValueError("bound Session changed before queue steering") active = self.store.load_turn(session_id, str(session.get("active_turn_id") or "")) if session.get("active_turn_id") else None def plan(phase): return plan_queued_chat_steering(session, turn, active, self.store.steering_receipt(session_id, ingress_id), - ingress_id=ingress_id, operation_id=client_ingress_id, target=expected_turn_id, phase=phase) + ingress_id=ingress_id, operation_id=client_ingress_id, target=expected_turn_id, phase=phase, + web_origin_only=admitted_steward is not None) decision = plan("prepare") - if decision["action"] == "unresolved": + if decision["action"] in {"dispatch", "unresolved"}: + if decision["action"] == "dispatch": + turn = self.store.write_queue_steering(session_id, turn, decision) try: - self.steer_active_turn(session_id=session_id, expected_turn_id=expected_turn_id, - client_ingress_id=ingress_id, message=turn["message"], - _queued_turn_id=queued_turn_id) - except Exception: - pass # Only the original receipt can complete the reservation. - decision = plan("settle") - if decision["action"] == "dispatch": - turn = self.store.write_queue_steering(session_id, turn, decision) - try: - self.steer_active_turn(session_id=session_id, expected_turn_id=expected_turn_id, - client_ingress_id=ingress_id, message=turn["message"], - _queued_turn_id=queued_turn_id) + if admitted_steward is not None: + steer_admitted_web_turn(self, session, expected_turn_id=expected_turn_id, + client_ingress_id=ingress_id, message=turn["message"], queued_turn_id=queued_turn_id) + else: + self.steer_active_turn(session_id=session_id, expected_turn_id=expected_turn_id, + client_ingress_id=ingress_id, message=turn["message"], _queued_turn_id=queued_turn_id) except Exception: # The durable ingress, including absence before any send, # owns the outcome. Exception wording cannot release work. @@ -625,8 +636,10 @@ def fail_ingress(error_code: str, *, record: bool = True) -> NoReturn: fail_ingress("live_steering_turn_mismatch") if not active_turn_id: fail_ingress("live_steering_requires_active_turn") - with self.lock: - adapter = self.adapters.get(session_id) + # Snapshot one adapter without taking the controller lock while a + # binding or queue fence is held. The native call still checks health + # and binds to the current upstream Turn. + adapter = self.adapters.get(session_id) if not isinstance(adapter, CodexAppServerAdapter) or not adapter.healthcheck(): fail_ingress("live_steering_session_not_attached") upstream_turn_id = "" diff --git a/loopx/control_plane/chat_turn_acceptance.py b/loopx/control_plane/chat_turn_acceptance.py index 000839ec4c..7b0b53e586 100644 --- a/loopx/control_plane/chat_turn_acceptance.py +++ b/loopx/control_plane/chat_turn_acceptance.py @@ -192,11 +192,13 @@ def plan_native_mention_ingress(**facts: object) -> dict[str, Any]: def plan_queued_chat_steering( session: dict[str, Any], turn: dict[str, Any], active: dict[str, Any] | None, receipt: dict[str, Any] | None, *, ingress_id: str, operation_id: str, target: str, phase: str, + web_origin_only: bool = False, ) -> dict[str, Any]: return effect_runtime_result("chat.queue.steer", { "phase": phase, "request": {"client_ingress_id": ingress_id, "operation_id": operation_id, "target_turn_id": target}, - "session": {"status": session.get("status"), "active_turn_id": session.get("active_turn_id")}, + "session": {"status": session.get("status"), "active_turn_id": session.get("active_turn_id"), + "web_origin_only": web_origin_only}, "active_status": (active or {}).get("status"), "turn": {"turn_id": turn["turn_id"], "status": turn["status"], "origin": turn.get("origin"), "loopx_execution": turn.get("loopx_execution", False), diff --git a/loopx/control_plane/turn_driver/chat_queue_steering.ts b/loopx/control_plane/turn_driver/chat_queue_steering.ts index e25199cd6f..21934fab8c 100644 --- a/loopx/control_plane/turn_driver/chat_queue_steering.ts +++ b/loopx/control_plane/turn_driver/chat_queue_steering.ts @@ -94,6 +94,7 @@ export function planQueuedChatSteering(input: JsonObject): QueueSteeringPlan { const held = reservation(turn.reservation); const reject = (code: string): QueueSteeringPlan => ({action: "reject", error_code: code}); if (session.status === "closed") return reject("session_closed"); + if (session.web_origin_only === true && turn.origin !== "web") return reject("queue_steering_source_unavailable"); if (turn.mutation != null) return reject("queue_mutation_in_progress"); if (held?.status === "pending" && (held.client_ingress_id !== id || held.target_turn_id !== target)) { diff --git a/tests/control_plane_ts/chat_queue_steering.test.ts b/tests/control_plane_ts/chat_queue_steering.test.ts index cb3da0855a..90fcf9199e 100644 --- a/tests/control_plane_ts/chat_queue_steering.test.ts +++ b/tests/control_plane_ts/chat_queue_steering.test.ts @@ -112,6 +112,18 @@ test("uncertain delivery never dispatches again or becomes eligible FIFO work", assert.deepEqual(selectQueuedChatTurns({turns: [{...expired, reservation: null}], include_reserved: true, capacity_at: "2026-01-01T00:00:00Z"}).turn_ids, []); }); +test("the private Steward App can steer only its own queued text", () => { + const f = facts(); + const session = {...f.session, web_origin_only: true}; + assert.equal(planQueuedChatSteering({...f, session}).action, "dispatch"); + for (const origin of ["external", "lark", "peer"]) { + const turn = {...f.turn, origin}; + assert.deepEqual(planQueuedChatSteering({...f, session, turn}), + {action: "reject", error_code: "queue_steering_source_unavailable"}); + } + assert.equal(planQueuedChatSteering({...f, turn: {...f.turn, origin: "external"}}).action, "dispatch"); +}); + test("acknowledgement recovers after target completion while proven rejection restores queue", () => { const f = facts(); f.turn.reservation = held; assert.equal(planQueuedChatSteering({...f, session: {status: "ready", active_turn_id: null}, receipt}).action, "complete"); diff --git a/tests/test_lark_private_conversations.py b/tests/test_lark_private_conversations.py index 29bd31a790..cdb603ebc3 100644 --- a/tests/test_lark_private_conversations.py +++ b/tests/test_lark_private_conversations.py @@ -6977,7 +6977,8 @@ def slow_source(*args, **kwargs): runtime.close() -def test_private_steward_app_steering_delivers_once_to_the_original_turn(tmp_path): +@pytest.mark.parametrize("queued", [False, True], ids=["composer", "queued-input"]) +def test_private_steward_app_steering_delivers_once_to_the_original_turn(tmp_path, queued): from loopx.chat_server import ChatHTTPServer, ChatRequestHandler from test_native_steward_private import steward @@ -7009,29 +7010,55 @@ def request(method, path, body=None): session_path = f"/api/chat/sessions/{sid}" endpoint = f"{session_path}/turns/{tid}/steer" correction = {"message": "Correct the current inspection.", "client_ingress_id": "app-correction"} - - status, refused = request("POST", f"{session_path}/turns/old-turn/steer", - {**correction, "client_ingress_id": "wrong-turn"}) - assert status == 409 and refused["delivery_state"] == "not_delivered" + body = correction + wrong_endpoint = f"{session_path}/turns/old-turn/steer" + wrong_body = {**correction, "client_ingress_id": "wrong-turn"} + original_queued = None + if queued: + status, pending = request("POST", f"{session_path}/turns", { + "message": correction["message"], "client_turn_id": "queue-original", "delivery": "queue", + }) + assert status == 202 and pending["status"] == "queued" + qid = pending["turn_id"] + original_queued = store.load_turn(sid, qid) + endpoint = wrong_endpoint = f"{session_path}/queue/{qid}/steer" + body = {"target_turn_id": tid, "client_ingress_id": "app-correction"} + wrong_body = {"target_turn_id": "old-turn", "client_ingress_id": "wrong-turn"} + + status, refused = request("POST", wrong_endpoint, wrong_body) + assert status == 409 and refused["error_code"] == "live_steering_turn_mismatch" provider.owner_ready = False - assert request("POST", endpoint, correction)[0] == 400 - assert store.steering_receipt(sid, "app-correction") is None + assert request("POST", endpoint, body)[0] == 400 + if queued: + assert store.load_turn(sid, qid) == original_queued + else: + assert store.steering_receipt(sid, "app-correction") is None provider.owner_ready = True - status, delivered = request("POST", endpoint, correction) - assert status == 200 and delivered["created"] is True and delivered["turn_id"] == tid + # Managed Steward admission takes the controller lock before its + # binding. Steering already fenced by the binding cannot wait on it. + with runtime.lock: + status, delivered = request("POST", endpoint, body) + assert status == 200 and delivered["turn_id"] == tid completed = runtime.wait_for_turn(session_id=sid, turn_id=tid, timeout_sec=10) assert completed["status"] == "completed" - status, duplicate = request("POST", endpoint, correction) - assert status == 200 and duplicate["created"] is False and duplicate["turn_id"] == tid + status, duplicate = request("POST", endpoint, body) + assert status == 200 and duplicate["turn_id"] == tid + if queued: + assert duplicate == delivered and delivered["queued_turn_id"] == qid + assert store.load_turn(sid, qid)["status"] == "completed" + adoption, = [row for row in store.events_after(sid, qid, None) + if row["kind"] == "turn.completed"] + assert adoption["payload"]["steered_into_turn_id"] == tid + else: + assert delivered["created"] is True and duplicate["created"] is False status, history = request("GET", session_path) assert status == 200 entry, = [row for row in history["messages"] if row["text"] == correction["message"]] - assert entry["turn_id"] == tid and entry["origin"] == "web" + assert entry["turn_id"] == (qid if queued else tid) and entry["origin"] == "web" transport.bindings.disconnect(binding["binding_id"], expected_revision=transport.bindings.read()["revision"]) - assert request("POST", endpoint, {**correction, "client_ingress_id": "revoked-input"})[0] == 400 - assert store.steering_receipt(sid, "revoked-input") is None + assert request("POST", endpoint, {**body, "client_ingress_id": "revoked-input"})[0] == 400 calls = [json.loads(line) for line in capture.read_text().splitlines()] steer, = [call["params"] for call in calls if call["method"] == "turn/steer"] assert steer["expectedTurnId"] == completed["upstream_turn_id"] From a49b198f46a611742012a8f6ad2171926d18d236 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:23:20 +0800 Subject: [PATCH 4/4] Keep queued steering under the native queue owner Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../native_chat/queued_admission.py | 52 +++++++++++++++++- loopx/chat_runtime.py | 55 +------------------ 2 files changed, 54 insertions(+), 53 deletions(-) diff --git a/loopx/capabilities/native_chat/queued_admission.py b/loopx/capabilities/native_chat/queued_admission.py index 6af99bb624..4426e509da 100644 --- a/loopx/capabilities/native_chat/queued_admission.py +++ b/loopx/capabilities/native_chat/queued_admission.py @@ -131,10 +131,60 @@ def steer_queued_web_turn(controller: "ChatRuntimeController", *, session_id: st if session is None: return controller.steer_queued_turn(session_id=session_id, queued_turn_id=queued_turn_id, expected_turn_id=expected_turn_id, client_ingress_id=client_ingress_id) - return controller._steer_queued_turn(session_id=session_id, queued_turn_id=queued_turn_id, + return steer_queued_turn(controller, session_id=session_id, queued_turn_id=queued_turn_id, expected_turn_id=expected_turn_id, client_ingress_id=client_ingress_id, admitted_steward=session) +def steer_queued_turn( + controller: "ChatRuntimeController", *, session_id: str, queued_turn_id: str, expected_turn_id: str, + client_ingress_id: str, admitted_steward: dict[str, Any] | None = None, +) -> dict[str, Any]: + from ...control_plane.chat_turn_acceptance import plan_queued_chat_steering + + ingress_id = "queue-steer-" + hashlib.sha256( + json.dumps([session_id, queued_turn_id, client_ingress_id]).encode() + ).hexdigest()[:40] + with controller.store.queue_steering_lock(session_id, queued_turn_id): + session = controller.store.load_session(session_id) + turn = controller.store.load_turn(session_id, queued_turn_id) + if session is None or turn is None: + raise KeyError("chat turn was not found") + if admitted_steward is not None and any(session.get(key) != admitted_steward.get(key) for key in ( + "steward_context", "project_context", "channel_id", "goal_id", "agent_id", + "executor_endpoint_id", "manager_authorization_scope_id", + )): + raise ValueError("bound Session changed before queue steering") + active = controller.store.load_turn(session_id, str(session.get("active_turn_id") or "")) if session.get("active_turn_id") else None + + def plan(phase): + return plan_queued_chat_steering(session, turn, active, + controller.store.steering_receipt(session_id, ingress_id), + ingress_id=ingress_id, operation_id=client_ingress_id, target=expected_turn_id, phase=phase, + web_origin_only=admitted_steward is not None) + + decision = plan("prepare") + if decision["action"] in {"dispatch", "unresolved"}: + if decision["action"] == "dispatch": + turn = controller.store.write_queue_steering(session_id, turn, decision) + try: + if admitted_steward is not None: + steer_admitted_web_turn(controller, session, expected_turn_id=expected_turn_id, + client_ingress_id=ingress_id, message=turn["message"], queued_turn_id=queued_turn_id) + else: + controller.steer_active_turn(session_id=session_id, expected_turn_id=expected_turn_id, + client_ingress_id=ingress_id, message=turn["message"], _queued_turn_id=queued_turn_id) + except Exception: + # The durable ingress, including absence before any send, + # owns the outcome. Exception wording cannot release work. + pass + decision = plan("settle") + controller.store.write_queue_steering(session_id, turn, decision) + if decision["action"] != "complete": + raise RuntimeError(decision["error_code"]) + return {"session_id": session_id, "queued_turn_id": queued_turn_id, + "turn_id": expected_turn_id, "client_ingress_id": client_ingress_id, + "status": "delivered"} + def deliver_native_mention( controller, *, session_id: str, ingress_id: str, target_turn_id: str | None, binding_matches: bool, text_only: bool, may_deliver_new: bool, diff --git a/loopx/chat_runtime.py b/loopx/chat_runtime.py index 40ff3efa21..38f79259ee 100644 --- a/loopx/chat_runtime.py +++ b/loopx/chat_runtime.py @@ -527,61 +527,12 @@ def steer_queued_turn( Only a proven non-delivery restores FIFO eligibility. A lost native acknowledgement keeps the original input durably reserved. """ + from .capabilities.native_chat.queued_admission import steer_queued_turn + self._require_steering_session(session_id) - return self._steer_queued_turn(session_id=session_id, queued_turn_id=queued_turn_id, + return steer_queued_turn(self, session_id=session_id, queued_turn_id=queued_turn_id, expected_turn_id=expected_turn_id, client_ingress_id=client_ingress_id) - def _steer_queued_turn( - self, *, session_id: str, queued_turn_id: str, expected_turn_id: str, - client_ingress_id: str, admitted_steward: dict[str, Any] | None = None, - ) -> dict[str, Any]: - from .capabilities.native_chat.queued_admission import steer_admitted_web_turn - from .control_plane.chat_turn_acceptance import plan_queued_chat_steering - - ingress_id = "queue-steer-" + hashlib.sha256( - json.dumps([session_id, queued_turn_id, client_ingress_id]).encode() - ).hexdigest()[:40] - with self.store.queue_steering_lock(session_id, queued_turn_id): - session = self.store.load_session(session_id) - turn = self.store.load_turn(session_id, queued_turn_id) - if session is None or turn is None: - raise KeyError("chat turn was not found") - if admitted_steward is not None and any(session.get(key) != admitted_steward.get(key) for key in ( - "steward_context", "project_context", "channel_id", "goal_id", "agent_id", - "executor_endpoint_id", "manager_authorization_scope_id", - )): - raise ValueError("bound Session changed before queue steering") - active = self.store.load_turn(session_id, str(session.get("active_turn_id") or "")) if session.get("active_turn_id") else None - - def plan(phase): - return plan_queued_chat_steering(session, turn, active, - self.store.steering_receipt(session_id, ingress_id), - ingress_id=ingress_id, operation_id=client_ingress_id, target=expected_turn_id, phase=phase, - web_origin_only=admitted_steward is not None) - - decision = plan("prepare") - if decision["action"] in {"dispatch", "unresolved"}: - if decision["action"] == "dispatch": - turn = self.store.write_queue_steering(session_id, turn, decision) - try: - if admitted_steward is not None: - steer_admitted_web_turn(self, session, expected_turn_id=expected_turn_id, - client_ingress_id=ingress_id, message=turn["message"], queued_turn_id=queued_turn_id) - else: - self.steer_active_turn(session_id=session_id, expected_turn_id=expected_turn_id, - client_ingress_id=ingress_id, message=turn["message"], _queued_turn_id=queued_turn_id) - except Exception: - # The durable ingress, including absence before any send, - # owns the outcome. Exception wording cannot release work. - pass - decision = plan("settle") - self.store.write_queue_steering(session_id, turn, decision) - if decision["action"] != "complete": - raise RuntimeError(decision["error_code"]) - return {"session_id": session_id, "queued_turn_id": queued_turn_id, - "turn_id": expected_turn_id, "client_ingress_id": client_ingress_id, - "status": "delivered"} - def steer_active_turn( self, *, session_id: str, client_ingress_id: str, message: str, expected_turn_id: str | None = None, _queued_turn_id: str | None = None,