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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(workbench): lock backend while a turn is running, not only after native bind
cyh1164a293c277
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.pyindex 050070e53..90d26208a 100644--- a/storage/workbench_sessions_service.py+++ b/storage/workbench_sessions_service.py@@ -19,7 +19,7 @@ import osfrom datetime import datetime, timezonefrom typing import Any, Optional-from sqlalchemy import func, or_, select, update+from sqlalchemy import and_, func, or_, select, updatefrom sqlalchemy.engine import Connectionfrom storage.agent_session_rows import create_agent_session_row@@ -313,9 +313,10 @@ def create_session(class SessionBackendLockedError(Exception):"""Raised when a caller tries to switch the backend of a session that already- has a native conversation. A session is pinned to its backend for life: the- native can only be resumed by the backend that created it, so switching would- strand it and silently lose context. Changing the agent WITHIN the same+ has a native conversation (pinned for life: the native can only be resumed by+ the backend that created it, so switching would strand it and silently lose+ context) or whose turn is currently running (the in-flight turn will bind its+ native on the current route any moment). Changing the agent WITHIN the samebackend stays allowed."""def __init__(self, *, session_id: str, current_backend: Optional[str], requested_backend: Optional[str]):@@ -346,6 +347,7 @@ def update_session(agent_sessions.c.id,agent_sessions.c.agent_backend,agent_sessions.c.native_session_id,+ agent_sessions.c.agent_status,agent_sessions.c.metadata_json,).where(agent_sessions.c.id == session_id)).first()@@ -354,19 +356,25 @@ def update_session(# Backend is pinned once a NATIVE conversation exists: the native can only# be resumed by the backend that created it, so switching (or clearing) the- # backend would strand it. Before the first turn nothing is strandable — a- # fresh session may carry a project-default backend (see ``create_session``)- # and the user can still re-route it to ANY backend or clear back to the- # default. Within the same backend, agent/model/effort changes stay allowed- # for the session's whole life. Legacy agent-less rows whose native predates- # the bind-time backend backfill keep the old empty -> concrete "initial- # pin" escape — the row doesn't know which backend owns its native, and- # locking them would leave their picker permanently stuck.- if (- agent_backend is not _UNSET- and str(existing.native_session_id or "")- and str(existing.agent_backend or "")- and str(agent_backend or "") != str(existing.agent_backend or "")+ # backend would strand it. A RUNNING turn locks it too — the first turn is+ # already executing on the current route and will bind its native shortly,+ # so a mid-turn switch would either be silently overwritten by the bind-time+ # backfill or route queued follow-ups inconsistently (a stale ``running``+ # after a crash is reset to ``idle`` on startup). Before the first turn+ # nothing is strandable — a fresh session may carry a project-default+ # backend (see ``create_session``) and the user can still re-route it to ANY+ # backend or clear back to the default. Within the same backend,+ # agent/model/effort changes stay allowed for the session's whole life.+ # Legacy agent-less rows whose native predates the bind-time backend+ # backfill keep the old empty -> concrete "initial pin" escape (while idle)+ # — the row doesn't know which backend owns its native, and locking them+ # would leave their picker permanently stuck.+ backend_changes = agent_backend is not _UNSET and str(agent_backend or "") != str(+ existing.agent_backend or ""+ )+ if backend_changes and (+ (str(existing.native_session_id or "") and str(existing.agent_backend or ""))+ or str(existing.agent_status or "") == "running"):raise SessionBackendLockedError(session_id=session_id,@@ -401,21 +409,23 @@ def update_session(values["reasoning_effort"] = reasoning_effort or Nonestmt = update(agent_sessions).where(agent_sessions.c.id == session_id)- backend_changes = agent_backend is not _UNSET and str(agent_backend or "") != str(- existing.agent_backend or ""- )if backend_changes:# Re-assert the lock INSIDE the UPDATE: the guard above is read-then-- # write, and the first turn's native bind can commit in between (the+ # write, and a turn start / native bind can commit in between (the# SELECT runs before this statement takes the write lock). The predicate# makes the change atomic — it only lands while the session is still- # unlocked (no native, or the legacy blank-backend escape) or the row- # already converged to the requested backend.+ # unlocked (idle AND (no native or the legacy blank-backend escape)) or+ # the row already converged to the requested backend.stmt = stmt.where(or_(- func.coalesce(agent_sessions.c.native_session_id, "") == "",- func.coalesce(agent_sessions.c.agent_backend, "") == "",agent_sessions.c.agent_backend == str(agent_backend or ""),+ and_(+ func.coalesce(agent_sessions.c.agent_status, "idle") != "running",+ or_(+ func.coalesce(agent_sessions.c.native_session_id, "") == "",+ func.coalesce(agent_sessions.c.agent_backend, "") == "",+ ),+ ),))result = conn.execute(stmt.values(**values))diff --git a/tests/test_core_services_sessions.py b/tests/test_core_services_sessions.pyindex c083204ae..0349f218b 100644--- a/tests/test_core_services_sessions.py+++ b/tests/test_core_services_sessions.py@@ -475,6 +475,50 @@ def test_update_session_locks_backend_once_native_exists(isolated_state):sessions_service.update_session(conn, sid, agent_backend=None, agent_name=None)+def test_update_session_running_turn_locks_backend(isolated_state):+ """A RUNNING turn locks the backend even before the native is bound: the+ in-flight first turn is already executing on the current route and will bind+ its native shortly, so a mid-turn switch would be silently overwritten by+ the bind-time backfill or route queued follow-ups inconsistently. Same-+ backend changes stay allowed; a settled turn without a native (failed first+ turn) unlocks again so the user can re-route to recover."""++ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_avibe_scope(conn)+ sid = sessions_service.create_session(+ conn, scope_id=scope_id, agent_backend="claude", agent_name="claude"+ )["id"]+ sessions_service.set_agent_status(conn, sid, "running")+ with pytest.raises(sessions_service.SessionBackendLockedError):+ sessions_service.update_session(conn, sid, agent_backend="codex", agent_name="codex")+ with pytest.raises(sessions_service.SessionBackendLockedError):+ sessions_service.update_session(conn, sid, agent_backend=None, agent_name=None)+ # Same-backend agent/model change stays allowed mid-turn.+ sessions_service.update_session(conn, sid, agent_backend="claude", model="opus")+ # First turn failed before binding a native → switchable again to recover.+ sessions_service.set_agent_status(conn, sid, "failed")+ sessions_service.update_session(conn, sid, agent_backend="codex", agent_name="codex")+ assert sessions_service.get_session(conn, sid)["agent_backend"] == "codex"+++def test_update_session_running_turn_locks_agent_less_session_too(isolated_state):+ """An agent-less session's first (global-default) turn also locks while+ running: a concrete pick would race the bind-time backend backfill the same+ way. Once settled without a native, the pick is allowed again."""++ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_avibe_scope(conn)+ sid = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="")["id"]+ sessions_service.set_agent_status(conn, sid, "running")+ with pytest.raises(sessions_service.SessionBackendLockedError):+ sessions_service.update_session(conn, sid, agent_backend="codex", agent_name="codex")+ sessions_service.set_agent_status(conn, sid, "idle")+ sessions_service.update_session(conn, sid, agent_backend="codex", agent_name="codex")+ assert sessions_service.get_session(conn, sid)["agent_backend"] == "codex"++def test_update_session_backend_switch_loses_race_with_native_bind(isolated_state):"""The lock guard is read-then-write and the first turn's native bind cancommit in between (the SELECT runs before the UPDATE takes the write lock).diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 6db164ca2..7c7dde1f4 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -944,6 +944,7 @@ export const ChatPage: React.FC = () => {defaultAgentName={defaultAgentName}onPatch={patch}onBack={goBack}+ working={working}/>{error && (@@ -1069,18 +1070,21 @@ interface ChatHeaderBarProps {defaultAgentName: string | null;onPatch: (changes: Partial<WorkbenchSession>) => Promise<void>;onBack: () => void;+ working: boolean;}-const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack }) => {+const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working }) => {const { t } = useTranslation();const defaultAgent = defaultAgentName ? agents.find((agent) => agent.name === defaultAgentName) : null;- // Backend locks only once a NATIVE conversation exists — a native can only be- // resumed by the backend that created it (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.- const hasNative = Boolean(session.native_session_id);- const pinnedBackend = hasNative ? session.agent_backend?.trim() || null : null;- const canClearToDefault = !hasNative;+ // Backend locks once a NATIVE conversation exists — a native can only be+ // resumed by the backend that created it — or while a turn is RUNNING (the+ // 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.+ const backendLocked = Boolean(session.native_session_id) || working;+ const pinnedBackend = backendLocked ? session.agent_backend?.trim() || null : null;+ const canClearToDefault = !backendLocked;const defaultRoute = defaultAgent? {agent_name: defaultAgent.name,