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(workbench): gate backend switch on the controller's in-flight registry + disable picker for backend-less running turns

cyhd4863f2afaf7
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.py
index 66499e110..e961459dc 100644
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@ -470,3 +470,95 @@ def test_turn_state_idle_preserves_response_for_missing_session(isolated_state):
body = response.get_json()
assert body["in_flight"] is False
assert body["recovered_agent_status"] is False
+
+
+def test_patch_backend_switch_blocked_while_turn_in_flight(isolated_state, tmp_path):
+ """The row's ``agent_status`` lags turn acceptance (``submit`` registers the
+ in-flight gate before dispatch writes ``running``), so a cross-backend PATCH
+ in that startup window must consult the controller's gate and 409 — otherwise
+ the bind-time backend backfill would silently undo the switch."""
+
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+
+ 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_backend": "codex", "agent_name": "codex"},
+ headers=headers,
+ )
+ assert response.status_code == 409
+ assert response.get_json()["code"] == "backend_locked"
+ in_flight.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."""
+
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+
+ gate = AsyncMock(return_value={"status_code": 200, "body": {"ok": True, "in_flight": True}})
+ with patch("vibe.internal_client.turn_state", gate):
+ client = app.test_client()
+ headers = csrf_headers(client)
+ response = client.patch(
+ f"/api/sessions/{session_id}",
+ json={"agent_backend": "claude", "agent_name": "claude-pro", "model": "opus"},
+ headers=headers,
+ )
+ assert response.status_code == 200
+ assert response.get_json()["agent_name"] == "claude-pro"
+ gate.assert_not_awaited()
+
+
+def test_patch_backend_switch_allowed_when_idle(isolated_state, tmp_path):
+ """No native + no in-flight turn → the (project-default) backend is a soft
+ pin and the cross-backend switch lands."""
+
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+
+ 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_backend": "codex", "agent_name": "codex"},
+ headers=headers,
+ )
+ assert response.status_code == 200
+ assert response.get_json()["agent_backend"] == "codex"
+
+
+def test_patch_backend_switch_falls_back_to_row_guard_when_controller_down(isolated_state, tmp_path):
+ """An unreachable controller must not brick the picker: the gate check is
+ best-effort and the row-status guard inside ``update_session`` still
+ applies."""
+
+ from vibe import internal_client
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+
+ async def unavailable(session_id_inner):
+ raise internal_client.InternalServerUnavailable("socket missing")
+
+ with patch("vibe.internal_client.turn_state", unavailable):
+ client = app.test_client()
+ headers = csrf_headers(client)
+ response = client.patch(
+ f"/api/sessions/{session_id}",
+ json={"agent_backend": "codex", "agent_name": "codex"},
+ headers=headers,
+ )
+ assert response.status_code == 200
+ assert response.get_json()["agent_backend"] == "codex"
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 7c7dde1f4..9a05c53ae 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -1081,10 +1081,17 @@ const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultA
// in-flight turn binds its native on the current route any moment); mirrors
// update_session's guard. Until then a session may carry a project-default
// backend, but the user can still re-route it to any backend or clear back
- // to the default.
+ // to the default. A locked session with a KNOWN backend keeps the picker
+ // open for same-backend agent/model changes; locked with a BLANK backend
+ // (the global-default route mid-turn) has no valid choice at all — every
+ // concrete pick would 409 — so the picker disables until the turn settles.
+ // Idle blank-backend rows with a native (legacy, pre-backfill) stay enabled:
+ // the server allows their one-time "initial pin".
+ const concreteBackend = session.agent_backend?.trim() || null;
const backendLocked = Boolean(session.native_session_id) || working;
- const pinnedBackend = backendLocked ? session.agent_backend?.trim() || null : null;
+ const pinnedBackend = backendLocked ? concreteBackend : null;
const canClearToDefault = !backendLocked;
+ const pickerDisabled = working && !concreteBackend;
const defaultRoute = defaultAgent
? {
agent_name: defaultAgent.name,
@@ -1120,6 +1127,7 @@ const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultA
value={session}
agents={agents}
onChange={onPatch}
+ disabled={pickerDisabled}
allowedBackends={pinnedBackend ? [pinnedBackend] : undefined}
defaultLabel={
canClearToDefault
diff --git a/vibe/ui_compat.py b/vibe/ui_compat.py
index a9b4f3387..bdcd45a69 100644
--- a/vibe/ui_compat.py
+++ b/vibe/ui_compat.py
@@ -276,6 +276,9 @@ class CompatTestClient:
def post(self, url: str, **kwargs: Any) -> CompatTestResponse:
return self.request("POST", url, **kwargs)
+ def patch(self, url: str, **kwargs: Any) -> CompatTestResponse:
+ return self.request("PATCH", url, **kwargs)
+
def delete(self, url: str, **kwargs: Any) -> CompatTestResponse:
return self.request("DELETE", url, **kwargs)
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 71fda8202..595640a34 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3721,9 +3721,25 @@ async def sessions_bootstrap(session_id: str):
)
+def _backend_locked_response(err):
+ """Shared 409 payload for a rejected cross-backend session change."""
+ return (
+ jsonify(
+ {
+ "error": str(err),
+ "code": "backend_locked",
+ "current_backend": err.current_backend,
+ "requested_backend": err.requested_backend,
+ }
+ ),
+ 409,
+ )
+
+
@app.route("/api/sessions/<session_id>", methods=["PATCH"])
-def sessions_update(session_id: str):
+async def sessions_update(session_id: str):
from core.services import sessions as workbench_sessions_service
+ from vibe import internal_client
from vibe.sse_broker import broker
payload = request.json or {}
@@ -3744,25 +3760,44 @@ def sessions_update(session_id: str):
return jsonify({"error": "no updatable fields supplied"}), 400
engine = _projects_engine()
+ # 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
+ # window would pass the row-status guard and then be silently undone by the
+ # 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:
+ 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 ""):
+ try:
+ turn_result = await internal_client.turn_state(session_id)
+ in_flight = bool((turn_result.get("body") or {}).get("in_flight"))
+ except (internal_client.InternalServerUnavailable, internal_client.InternalServerTimeout):
+ in_flight = False
+ if in_flight:
+ return _backend_locked_response(
+ workbench_sessions_service.SessionBackendLockedError(
+ session_id=session_id,
+ current_backend=current.get("agent_backend"),
+ requested_backend=updatable.get("agent_backend"),
+ )
+ )
+
try:
with engine.begin() as conn:
session = workbench_sessions_service.update_session(conn, session_id, **updatable)
except LookupError as err:
return jsonify({"error": str(err)}), 404
except workbench_sessions_service.SessionBackendLockedError as err:
- # A session is pinned to its backend once it has a conversation; the UI
- # may switch the agent within the same backend, but not across backends.
- return (
- jsonify(
- {
- "error": str(err),
- "code": "backend_locked",
- "current_backend": err.current_backend,
- "requested_backend": err.requested_backend,
- }
- ),
- 409,
- )
+ # A session is pinned to its backend once it has a conversation (or a
+ # running turn); the UI may switch the agent within the same backend,
+ # but not across backends.
+ return _backend_locked_response(err)
# Broadcast so other surfaces (e.g. the sidebar session list) reflect the
# edit live — renaming a session in the chat header should rename its
# sidebar row without a manual refresh.