Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions loopx/chat_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -1006,7 +1006,7 @@ def manager_session_model_allocation(

This is a proposal for the adapter's next idle boundary, not an update or
an endpoint switch. Absent defaults and unchanged profiles preserve the
persisted binding, including a restart's original service environment.
persisted binding unless a legacy snapshot still reports another model.
"""
previous = session.get("manager_executor_allocation")
defaults = steward_machine_defaults(controller)
Expand Down Expand Up @@ -1037,15 +1037,26 @@ def manager_session_model_allocation(
return proposed
if not isinstance(previous, Mapping):
return None
if (defaults is None or defaults.get("status") != "ready"
or defaults.get("configuration_revision") == previous.get("configuration_revision")):
if defaults is None or defaults.get("status") != "ready":
return None
endpoint = str(previous["executor_endpoint"])
configured_endpoint = _machine_default_text(defaults, "executor_endpoint")
if configured_endpoint and configured_endpoint != endpoint:
# Editing another endpoint's defaults cannot move an existing binding
# or reinterpret its model as belonging to that other provider.
return None
# Older Codex Sessions could persist a new allocation while reopening
# with the last observed model. Reconcile only a concrete machine choice
# for the same executor and a Session with no recorded model request.
legacy_model_not_adopted = (
endpoint == session.get("agent_id") == "codex"
and "requested_agent_model_id" not in session
and previous.get("model_source") == MANAGER_MODEL_SOURCE_MACHINE_CONFIGURATION
and _machine_default_text(defaults, "executor_model") == previous["model"]
and session.get("agent_model_id") not in (None, previous["model"])
)
if defaults.get("configuration_revision") == previous.get("configuration_revision"):
return previous if legacy_model_not_adopted else None
requested = endpoint if previous.get("allocation_reason") == MANAGER_ALLOCATION_REASON_USER_EXPLICIT else None
proposed = manager_executor_allocation(
controller, requested, machine_defaults=defaults,
Expand All @@ -1070,7 +1081,7 @@ def manager_session_model_allocation(
model_edited = proposed["configured_model"] != previous_model
effort_edited = proposed["configured_reasoning_effort"] != previous_effort
if not model_edited and not effort_edited:
return None
return previous if legacy_model_not_adopted else None
if not model_edited:
proposed["model"] = previous["model"]
proposed["model_source"] = previous["model_source"]
Expand Down
33 changes: 24 additions & 9 deletions loopx/chat_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -881,6 +881,21 @@ def check_route_configuration():
if active and active.get("status") == "queued" and active_id == accepted_turn_id:
check_route_configuration()
selected_agent = model_allocation["executor_endpoint"] if quota_route else session["agent_id"]
executor_model = (alloc.manager_executor_model(model_allocation)
if model_allocation is not None else alloc.restored_executor_model(session))
last_model = session.get("agent_model_id")
requested_model = last_model
if session["agent_id"] == "codex":
# In a Steward binding the allocation supplies the default. Old
# observed settings are only a fallback for unallocated Sessions.
requested_model = session.get("requested_agent_model_id",
None if manager_runtime is not None and executor_model is not None else last_model)
agent_config = executor_model if quota_route else {
**(session.get("codex_chat_configuration") or {}),
**({"model": requested_model} if requested_model else {}),
**({"reasoning_effort": session["requested_agent_reasoning_effort"]}
if session.get("requested_agent_reasoning_effort") else {}),
}
native_account_epoch = None
if (selected_agent == "codex" and (
active and active_id == accepted_turn_id and active.get("status") == "queued"
Expand All @@ -889,7 +904,8 @@ def check_route_configuration():
)):
from .capabilities.native_chat.codex_auth import conversation_account_epoch
native_account_epoch = conversation_account_epoch(self.coordination_runtime_root, selected_codex_home,
**({"consumer": "steward", "model": (model_allocation or {}).get("model") or session.get("agent_model_id")}
**({"consumer": "steward", "model": (agent_config or {}).get("model")
or (executor_model or {}).get("model") or last_model}
if manager_runtime is not None else {}))
native_quota_refresh = bool(active and active_id == accepted_turn_id
and active.get("status") == "queued" and active.get("origin") == "native_loopx"
Expand Down Expand Up @@ -1046,15 +1062,10 @@ def check_route_configuration():
project_coordination=conversation_scope(session)["kind"] == "owner_goal",
loopx_tools=session.get("loopx_tools") is True,
managed_read_default=session.get("managed_agent_id") is not None,
executor_model=(alloc.manager_executor_model(model_allocation)
if model_allocation is not None else alloc.restored_executor_model(session)),
executor_model=executor_model,
manager_runtime=manager_runtime,
project_context=session.get("project_context"),
agent_config=(alloc.manager_executor_model(model_allocation) if quota_route else {**(session.get("codex_chat_configuration") or {}), **({"model": requested_model} if (requested_model := (
session.get("requested_agent_model_id", session.get("agent_model_id"))
if session.get("agent_id") == "codex" else session.get("agent_model_id")
)) else {}), **({"reasoning_effort": session["requested_agent_reasoning_effort"]}
if session.get("requested_agent_reasoning_effort") else {})} or None),
agent_config=agent_config or None,
codex_home_override=selected_codex_home,
read_only_review=bool(recovery.get("read_only_review")),
metadata_review_context=session.get("steward_context") if metadata_fallback else None,
Expand All @@ -1064,9 +1075,13 @@ def check_route_configuration():
)
try:
# Recovery reads back the provider-restored configuration.
expected_model = session.get("requested_agent_model_id") if settings_changed else None
if (selected_agent == "codex" and not quota_route and model_allocation is not None
and model_allocation.get("configured_model")):
expected_model = (agent_config or {}).get("model") or model_allocation["model"]
observed_settings = self._observed_model_settings(adapter,
session.get("requested_agent_reasoning_effort") if settings_changed else None,
session.get("requested_agent_model_id") if settings_changed else None)
expected_model)
if session.get("upstream_mode") == CODEX_GOAL_CHAT_MODE:
if not isinstance(adapter, CodexAppServerAdapter):
raise CodexChatAgentError("Native Goal continuation requires a Codex adapter.", error_code="native_goal_adapter_mismatch", gate=None)
Expand Down
92 changes: 85 additions & 7 deletions tests/test_chat_manager_model_adoption.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
actual answer quality, separately from this lifecycle regression.
"""

import json
from types import SimpleNamespace

import pytest

from loopx.capabilities.machine_configuration.builtins import (
Expand All @@ -16,6 +19,7 @@
MANAGER_CONTEXT_VERSION,
manager_channel_binding,
manager_executor_allocation,
manager_session_model_allocation,
open_manager_session,
)
from loopx.chat_runtime import ChatRuntimeController, CodexAppServerAdapter
Expand Down Expand Up @@ -140,7 +144,6 @@ def test_idle_conversation_adopts_model_preserving_context_and_authority(convers
def test_legacy_bound_steward_adopts_explicit_machine_model_once(conversation):
root, store, runtime, session, starts = conversation
sid = session["session_id"]
import json
legacy = {**store.load_session(sid), "agent_model_id": "gpt-6-sol", "agent_reasoning_effort": "xhigh"}
legacy.pop("manager_executor_allocation", None)
store._session_path(sid).write_text(json.dumps(legacy)) # retained pre-allocation disk format
Expand All @@ -158,7 +161,6 @@ def test_legacy_bound_steward_adopts_explicit_machine_model_once(conversation):


def test_legacy_model_adoption_preserves_unset_fields_and_endpoint(conversation):
from loopx.chat_manager import manager_session_model_allocation
root, store, runtime, session, _ = conversation
legacy = {**session, "manager_executor_allocation": None,
"agent_model_id": "gpt-6-sol", "agent_reasoning_effort": "xhigh"}
Expand Down Expand Up @@ -277,9 +279,15 @@ def upstream_boundary(monkeypatch, tmp_path):
starts = []

def start(**kwargs):
adapter = Adapter(len(starts))
if kwargs.get("resume_thread_id"):
adapter.upstream_thread_id = kwargs["resume_thread_id"]
transport = Adapter(len(starts))
adapter = CodexAppServerAdapter(SimpleNamespace(
thread_id=kwargs.get("resume_thread_id") or transport.upstream_thread_id,
resolved_model=kwargs["model"],
resolved_reasoning_effort=kwargs["reasoning_effort"],
read_only_review=kwargs["read_only_review"],
process=SimpleNamespace(poll=lambda: None if transport.healthcheck() else 0),
close=transport.close_session,
))
starts.append((kwargs, adapter))
return adapter

Expand All @@ -292,15 +300,85 @@ def controller():
])
return runtime

def open_conversation(runtime):
def open_conversation(runtime, **settings):
return open_manager_session(
controller=runtime, goal_id="loopx-manager", work_dir=tmp_path,
provider="fixture", audience="owner",
provider="fixture", audience="owner", **settings,
)[0]

return root, store, controller, open_conversation, starts


@pytest.mark.parametrize("allocation_already_recorded", [False, True])
def test_legacy_observed_model_does_not_override_machine_model(upstream_boundary, allocation_already_recorded):
root, store, controller, open_conversation, starts = upstream_boundary
configure(root, model="gpt-6.1-sol", effort="xhigh")
runtime = controller()
session = open_conversation(runtime)
sid = session["session_id"]
store.append_message(sid, role="user", text="Keep the original scope.")
messages = store.messages(sid)
configure(root, model="gpt-6.2-sol", effort="xhigh")

# A historical session has an observed model without a user selection.
# A previous runtime may also have committed the new allocation even
# though it reopened the provider with the model from that old observation.
legacy = store.load_session(sid)
legacy.pop("requested_agent_model_id")
if allocation_already_recorded:
allocation = manager_session_model_allocation(runtime, legacy)
assert allocation["model"] == "gpt-6.2-sol"
legacy["manager_executor_allocation"] = allocation
store._session_path(sid).write_text(json.dumps(legacy))

updated = open_conversation(runtime)

assert updated["session_id"] == sid and updated["channel_id"] == session["channel_id"]
assert (starts[-1][0]["model"], starts[-1][0]["reasoning_effort"]) == ("gpt-6.2-sol", "xhigh")
assert updated["agent_model_id"] == updated["manager_executor_allocation"]["model"] == "gpt-6.2-sol"
assert store.messages(sid) == messages
assert starts[-1][0]["history"] == [{"role": "user", "content": "Keep the original scope."}]
assert updated["upstream_context_history"][-1]["thread_id"] == session["upstream_thread_id"]

open_conversation(runtime)
assert len(starts) == 2


def test_explicit_session_model_survives_machine_default_edit(upstream_boundary):
root, _, controller, open_conversation, starts = upstream_boundary
configure(root, model="gpt-6-sol", effort="high")
runtime = controller()
session = open_conversation(runtime, agent_model_id="gpt-6.1-sol")
configure(root, model="gpt-6.2-sol", effort="high")

updated = open_conversation(runtime)
assert updated["session_id"] == session["session_id"]
assert starts[-1][0]["model"] == updated["agent_model_id"] == updated["requested_agent_model_id"] == "gpt-6.1-sol"


def test_unconfirmed_machine_model_does_not_replace_binding(upstream_boundary, monkeypatch):
root, store, controller, open_conversation, starts = upstream_boundary
configure(root, model="gpt-6.1-sol", effort="high")
runtime = controller()
session = open_conversation(runtime)
configure(root, model="gpt-6.2-sol", effort="high")
start = CodexAppServerAdapter.start

def start_without_model_readback(**kwargs):
adapter = start(**kwargs)
adapter.session.resolved_model = None
return adapter

monkeypatch.setattr(CodexAppServerAdapter, "start", start_without_model_readback)
with pytest.raises(CodexChatAgentError, match="could not be restored"):
open_conversation(runtime)

held = store.load_session(session["session_id"])
assert held["upstream_thread_id"] == session["upstream_thread_id"]
assert held["manager_executor_allocation"] == session["manager_executor_allocation"]
assert held["agent_model_id"] == "gpt-6.1-sol" and not starts[-1][1].healthcheck()


@pytest.mark.parametrize("refresh_context", [False, True])
def test_model_edit_keeps_early_context_through_public_resume(upstream_boundary, refresh_context):
root, store, controller, open_conversation, starts = upstream_boundary
Expand Down
Loading