Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix agent routing review edge cases (#612)

Call White03bc6907e9f9
diff --git a/config/v2_settings.py b/config/v2_settings.py
index 9c67c727a..0c1b0da92 100644
--- a/config/v2_settings.py
+++ b/config/v2_settings.py
@@ -132,6 +132,8 @@ def normalize_routing_settings(routing: Optional[RoutingSettings]) -> RoutingSet
def routing_model_for_backend(routing: Optional[RoutingSettings], backend: Optional[str]) -> Optional[str]:
normalized = normalize_routing_settings(routing)
+ if not _routing_backend_matches(normalized, backend):
+ return None
return normalized.model
@@ -140,9 +142,18 @@ def routing_reasoning_effort_for_backend(
backend: Optional[str],
) -> Optional[str]:
normalized = normalize_routing_settings(routing)
+ if not _routing_backend_matches(normalized, backend):
+ return None
return normalized.reasoning_effort
+def _routing_backend_matches(routing: RoutingSettings, backend: Optional[str]) -> bool:
+ agent_name = getattr(routing, "agent_name", None)
+ if agent_name in {"opencode", "claude", "codex"}:
+ return agent_name == backend
+ return True
+
+
@dataclass
class ChannelSettings:
enabled: bool = False
diff --git a/core/services/sessions.py b/core/services/sessions.py
index 6a81fa083..f53d6d55f 100644
--- a/core/services/sessions.py
+++ b/core/services/sessions.py
@@ -42,6 +42,7 @@ from storage.workbench_sessions_service import (
backfill_session_title,
count_bound_resources,
create_session,
+ derive_backend_for_agent_name,
get_active_session,
get_session,
is_session_archived,
@@ -59,6 +60,7 @@ __all__ = [
"backfill_session_title",
"count_bound_resources",
"create_session",
+ "derive_backend_for_agent_name",
"get_active_session",
"get_session",
"is_session_archived",
diff --git a/storage/settings_service.py b/storage/settings_service.py
index 997a16585..ab585f86d 100644
--- a/storage/settings_service.py
+++ b/storage/settings_service.py
@@ -368,7 +368,7 @@ def _routing_columns(routing: RoutingSettings) -> dict[str, str | None]:
routing = normalize_routing_settings(routing)
model = routing.model
effort = routing.reasoning_effort
- variant = routing.codex_agent or routing.claude_agent or routing.opencode_agent
+ variant = _active_routing_variant(routing)
return {
"agent_name": routing.agent_name,
"agent_variant": variant,
@@ -377,6 +377,17 @@ def _routing_columns(routing: RoutingSettings) -> dict[str, str | None]:
}
+def _active_routing_variant(routing: RoutingSettings) -> str | None:
+ agent_name = routing.agent_name
+ if agent_name == "codex":
+ return routing.codex_agent
+ if agent_name == "claude":
+ return routing.claude_agent
+ if agent_name == "opencode":
+ return routing.opencode_agent
+ return routing.codex_agent or routing.claude_agent or routing.opencode_agent
+
+
def _routing_from_row(row: dict[str, Any], payload: dict[str, Any]) -> RoutingSettings:
routing_payload = payload.get("routing") or {}
routing = RoutingSettings(
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index b3c0d0273..50c218185 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -474,6 +474,10 @@ def _backend_for_agent_name(conn: Connection, agent_name: str) -> str:
return str(backend or "")
+def derive_backend_for_agent_name(conn: Connection, agent_name: str) -> str:
+ return _backend_for_agent_name(conn, agent_name)
+
+
def backfill_session_title(
conn: Connection,
session_id: str,
diff --git a/tests/test_controller_vibe_agent_routing.py b/tests/test_controller_vibe_agent_routing.py
index f971dce68..c832e26f8 100644
--- a/tests/test_controller_vibe_agent_routing.py
+++ b/tests/test_controller_vibe_agent_routing.py
@@ -131,6 +131,42 @@ def test_codex_overrides_prefer_scope_level_model_and_reasoning() -> None:
assert controller.get_codex_overrides(_context()) == (None, "gpt-5.5", "xhigh")
+def test_builtin_agent_model_overrides_only_apply_to_matching_backend() -> None:
+ controller = _StubController()
+ controller.primary_platform = "slack"
+ controller._get_settings_key = lambda context: context.channel_id
+ routing = SimpleNamespace(
+ agent_name="claude",
+ codex_agent=None,
+ opencode_agent=None,
+ model="claude-opus-4-8",
+ reasoning_effort="max",
+ )
+ controller.get_settings_manager_for_context = lambda context: SimpleNamespace(
+ get_channel_routing=lambda settings_key: routing
+ )
+
+ assert controller.get_codex_overrides(_context()) == (None, None, None)
+ assert controller.get_opencode_overrides(_context()) == (None, None, None)
+
+
+def test_builtin_agent_model_overrides_still_apply_to_selected_backend() -> None:
+ controller = _StubController()
+ controller.primary_platform = "slack"
+ controller._get_settings_key = lambda context: context.channel_id
+ routing = SimpleNamespace(
+ agent_name="codex",
+ codex_agent=None,
+ model="gpt-5.5",
+ reasoning_effort="xhigh",
+ )
+ controller.get_settings_manager_for_context = lambda context: SimpleNamespace(
+ get_channel_routing=lambda settings_key: routing
+ )
+
+ assert controller.get_codex_overrides(_context()) == (None, "gpt-5.5", "xhigh")
+
+
def test_avibe_run_target_agent_does_not_read_im_routing() -> None:
controller = _StubController()
reviewer = SimpleNamespace(name="reviewer", backend="codex")
diff --git a/tests/test_core_services_sessions.py b/tests/test_core_services_sessions.py
index c5de049eb..5414abfab 100644
--- a/tests/test_core_services_sessions.py
+++ b/tests/test_core_services_sessions.py
@@ -70,6 +70,7 @@ def test_public_surface_is_stable():
"backfill_session_title",
"count_bound_resources",
"create_session",
+ "derive_backend_for_agent_name",
"get_active_session",
"get_session",
"is_session_archived",
diff --git a/tests/test_sqlite_settings_store.py b/tests/test_sqlite_settings_store.py
index a3d26d732..ba49da73b 100644
--- a/tests/test_sqlite_settings_store.py
+++ b/tests/test_sqlite_settings_store.py
@@ -405,6 +405,83 @@ def test_settings_save_lifts_backend_aliases_for_builtin_agent_name(tmp_path: Pa
assert routing.reasoning_effort == "max"
+def test_settings_save_stores_only_active_builtin_agent_variant(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path)
+ service = SQLiteSettingsService(db_path)
+ try:
+ service.save_state(
+ SettingsState(
+ channels={
+ "slack::C123": ChannelSettings(
+ enabled=True,
+ routing=RoutingSettings(
+ agent_name="opencode",
+ codex_agent="stale-codex-profile",
+ opencode_agent=None,
+ ),
+ ),
+ }
+ )
+ )
+ state = service.load_state()
+ finally:
+ service.close()
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.connect() as conn:
+ row = conn.execute(
+ select(scope_settings.c.agent_variant, scope_settings.c.settings_json)
+ .select_from(scope_settings)
+ .join(scopes, scopes.c.id == scope_settings.c.scope_id)
+ .where(scopes.c.platform == "slack", scopes.c.native_id == "C123")
+ ).one()
+ finally:
+ engine.dispose()
+
+ assert row.agent_variant is None
+ assert state.channels["slack::C123"].routing.codex_agent == "stale-codex-profile"
+ assert json.loads(row.settings_json)["routing"]["codex_agent"] == "stale-codex-profile"
+
+
+def test_settings_save_uses_matching_builtin_agent_variant(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path)
+ service = SQLiteSettingsService(db_path)
+ try:
+ service.save_state(
+ SettingsState(
+ channels={
+ "slack::C123": ChannelSettings(
+ enabled=True,
+ routing=RoutingSettings(
+ agent_name="codex",
+ codex_agent="active-codex-profile",
+ opencode_agent="stale-opencode-profile",
+ ),
+ ),
+ }
+ )
+ )
+ finally:
+ service.close()
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.connect() as conn:
+ row = conn.execute(
+ select(scope_settings.c.agent_variant)
+ .select_from(scope_settings)
+ .join(scopes, scopes.c.id == scope_settings.c.scope_id)
+ .where(scopes.c.platform == "slack", scopes.c.native_id == "C123")
+ ).one()
+ finally:
+ engine.dispose()
+
+ assert row.agent_variant == "active-codex-profile"
+
+
def test_settings_load_ignores_row_model_without_agent_name(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
run_migrations(db_path)
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.py
index 06ba02269..2cc30230b 100644
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@ -600,6 +600,78 @@ def test_patch_backend_switch_blocked_while_turn_in_flight(isolated_state, tmp_p
in_flight.assert_awaited_once()
+def test_patch_agent_name_only_backend_switch_blocked_while_turn_in_flight(isolated_state, tmp_path):
+ """A selected Vibe Agent implies its backend. The UI often sends only
+ ``agent_name`` when changing the picker, so the route must derive the
+ backend before deciding whether to consult the controller's in-flight gate.
+ """
+
+ from core.vibe_agents import VibeAgentStore
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+ store = VibeAgentStore()
+ try:
+ store.create(name="reviewer", backend="codex")
+ finally:
+ store.close()
+
+ in_flight = AsyncMock(return_value={"status_code": 200, "body": {"ok": True, "in_flight": True}})
+ with patch("vibe.internal_client.turn_state", in_flight):
+ client = app.test_client()
+ headers = csrf_headers(client)
+ response = client.patch(
+ f"/api/sessions/{session_id}",
+ json={"agent_name": "reviewer"},
+ headers=headers,
+ )
+ assert response.status_code == 409
+ body = response.get_json()
+ assert body["code"] == "backend_locked"
+ assert body["current_backend"] == "claude"
+ assert body["requested_backend"] == "codex"
+ in_flight.assert_awaited_once()
+
+
+def test_patch_agent_name_only_backend_switch_refreshes_variant_when_idle(isolated_state, tmp_path):
+ from core.vibe_agents import VibeAgentStore
+ from storage.db import create_sqlite_engine
+ from storage.models import agent_sessions
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == session_id)
+ .values(agent_variant="old-claude-profile")
+ )
+
+ store = VibeAgentStore()
+ try:
+ store.create(name="reviewer", backend="codex")
+ finally:
+ store.close()
+
+ idle = AsyncMock(return_value={"status_code": 200, "body": {"ok": True, "in_flight": False}})
+ with patch("vibe.internal_client.turn_state", idle):
+ client = app.test_client()
+ headers = csrf_headers(client)
+ response = client.patch(
+ f"/api/sessions/{session_id}",
+ json={"agent_name": "reviewer"},
+ headers=headers,
+ )
+
+ assert response.status_code == 200
+ body = response.get_json()
+ assert body["agent_name"] == "reviewer"
+ assert body["agent_backend"] == "codex"
+ assert body["agent_variant"] == "codex"
+ idle.assert_awaited_once()
+
+
def test_patch_same_backend_change_skips_in_flight_gate(isolated_state, tmp_path):
"""Same-backend agent/model changes stay allowed mid-turn and don't pay the
internal turn-state round-trip."""
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 733a7785c..8702eaf58 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -4428,6 +4428,18 @@ async def sessions_update(session_id: str):
return jsonify({"error": "no updatable fields supplied"}), 400
engine = _projects_engine()
+ should_check_backend_lock = "agent_backend" in updatable
+ requested_backend = updatable.get("agent_backend")
+ if "agent_name" in updatable and "agent_backend" not in updatable:
+ try:
+ with engine.connect() as conn:
+ requested_backend = workbench_sessions_service.derive_backend_for_agent_name(
+ conn,
+ str(updatable.get("agent_name") or ""),
+ )
+ should_check_backend_lock = True
+ except LookupError as err:
+ return jsonify({"error": str(err)}), 404
# The row's ``agent_status`` lags turn acceptance: ``SessionTurnManager.submit``
# registers the in-flight gate synchronously, but ``running`` is only written
# once dispatch starts — so a cross-backend switch landing in that startup
@@ -4435,13 +4447,13 @@ async def sessions_update(session_id: str):
# bind-time backend backfill. Consult the controller's authoritative in-flight
# registry first; an unreachable/slow controller falls through to the
# row-status guard inside ``update_session`` (best effort).
- if "agent_backend" in updatable:
+ if should_check_backend_lock:
try:
with engine.connect() as conn:
current = workbench_sessions_service.get_session(conn, session_id)
except LookupError as err:
return jsonify({"error": str(err)}), 404
- if str(updatable.get("agent_backend") or "") != str(current.get("agent_backend") or ""):
+ if str(requested_backend or "") != str(current.get("agent_backend") or ""):
try:
turn_result = await internal_client.turn_state(session_id)
in_flight = bool((turn_result.get("body") or {}).get("in_flight"))
@@ -4452,7 +4464,7 @@ async def sessions_update(session_id: str):
workbench_sessions_service.SessionBackendLockedError(
session_id=session_id,
current_backend=current.get("agent_backend"),
- requested_backend=updatable.get("agent_backend"),
+ requested_backend=requested_backend,
)
)