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.

feat(sessions): offer to continue on Vibey when the session's Agent cannot run (#2934)

Call Whiteca2d3b3a3455
diff --git a/core/backend_failure.py b/core/backend_failure.py
index 1c9c81317..2ea6989d4 100644
--- a/core/backend_failure.py
+++ b/core/backend_failure.py
@@ -19,6 +19,17 @@ from vibe.i18n import t as i18n_t
from vibe.message_types import spec_for
BACKEND_FAILURE_EVENT = "backend_failure"
+#: ``failure_next_step`` of a notice whose Agent cannot run (disabled, deleted, or its
+#: backend unavailable): the Workbench offers to move the session to Vibey and run the
+#: failed input there (``continue_on_backend`` on the notice's Retry).
+CONTINUE_ON_VIBEY_NEXT_STEP = "continue_on_vibey"
+
+
+def output_with_next_step(request: Any, next_step: str) -> MessageOutput:
+ """The terminal output of a failure notice that names ``next_step`` as data."""
+
+ terminal = terminal_output_for(request) if request is not None else terminal_turn_output()
+ return replace(terminal, metadata={**terminal.metadata, "failure_next_step": next_step})
def is_backend_failure_notification(message_type: str | None, metadata: Any) -> bool:
diff --git a/core/backend_failure_retry.py b/core/backend_failure_retry.py
index c9759757b..d1c4921af 100644
--- a/core/backend_failure_retry.py
+++ b/core/backend_failure_retry.py
@@ -92,7 +92,11 @@ def _validate_boundary(
or session["visibility"] == "system"
or turn is None
or turn["session_id"] != session_id
- or turn["backend"] != session["agent_backend"]
+ # A continuation belongs to the backend that ran the Turn. An input that
+ # never reached it (``not_written``) belongs to no backend yet, so it may
+ # run wherever the session routes now: that is how "continue on Vibey"
+ # retries a message whose Agent was disabled.
+ or (turn["backend"] != session["agent_backend"] and turn["terminal_outcome"] != "not_written")
):
raise RetryUnavailable("retry_not_available")
latest = conn.execute(
@@ -126,6 +130,34 @@ def _validate_boundary(
return turn
+def existing_retry(
+ conn: Connection,
+ session_id: str,
+ notice_id: str,
+ *,
+ notice: dict[str, Any] | None = None,
+) -> dict[str, Any] | None:
+ """The retry this notice already owns, when a repeated click must resolve to it.
+
+ An admitted or reserved retry is returned as it is: a duplicate click wakes the
+ same owner (even after a lost response) instead of creating, or re-deciding, a
+ second one. A link to a Delivery this notice does not own is refused.
+ """
+ notice = notice if notice is not None else _notice(conn, session_id, notice_id)
+ link = notice["content"].get("failure_retry") or {}
+ existing = deliveries.get_delivery(conn, str(link.get("delivery_id") or ""))
+ if existing is None or existing["session_id"] != session_id:
+ return None
+ binding = retry_binding(existing)
+ if binding is None or binding.get("notice_id") != notice_id:
+ raise RetryUnavailable("retry_not_available")
+ if policy_for(existing["state"]).submission == "admitted" or existing["state"] == "reserved":
+ # Admission retires a reservation if the boundary changed; leaving a stale
+ # one here would strand an ordering fence in front of later normal input.
+ return existing
+ return None
+
+
def reserve_retry(
conn: Connection,
*,
@@ -139,19 +171,9 @@ def reserve_retry(
is admitted through the input admission entry with its binding as the event.
"""
notice = _notice(conn, session_id, notice_id)
- link = notice["content"].get("failure_retry") or {}
- existing = deliveries.get_delivery(conn, str(link.get("delivery_id") or ""))
- if existing is not None and existing["session_id"] == session_id:
- binding = retry_binding(existing)
- if binding is None or binding.get("notice_id") != notice_id:
- raise RetryUnavailable("retry_not_available")
- if policy_for(existing["state"]).submission == "admitted":
- return existing
- if existing["state"] == "reserved":
- # Wake the same owner even after a lost response. Admission retires
- # it if the boundary changed; leaving a stale reservation here would
- # strand an ordering fence in front of subsequent normal input.
- return existing
+ existing = existing_retry(conn, session_id, notice_id, notice=notice)
+ if existing is not None:
+ return existing
source_turn = deliveries.get_turn(conn, str(notice["metadata"]["turn_id"]))
original = (
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index bd56f76e4..0e1214283 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -12,7 +12,7 @@ from core.audio_asr import (
format_audio_transcript_echo,
)
from core.agent_input import AgentInputMetadata, harness_label
-from core.backend_failure import emit_backend_failure
+from core.backend_failure import CONTINUE_ON_VIBEY_NEXT_STEP, emit_backend_failure, output_with_next_step
from core.delivery_target import routed_delivery_context
from core.message_output import HARNESS_PROMPT_ECHO_SPEC_KEY
from core.session_handoff import BACKEND_HANDOFF_TURN_KEY
@@ -914,8 +914,27 @@ class MessageHandler(BaseHandler):
A Model Hub supply refusal is already the user's copy and names its own cause.
"""
+ from core.vibe_agents import AgentUnavailableError
from modules.agents.model_hub import ModelSupplyRefusal
+ if isinstance(error, AgentUnavailableError) and error.reason in {"disabled", "missing"}:
+ agent = error.agent_name
+ if error.reason == "missing":
+ # A deleted Agent resolved by id names only that id; the session's
+ # projection still carries the name the user knows.
+ from core.agent_session_context import resolve_context_agent_session_target
+
+ target = resolve_context_agent_session_target(context) or {}
+ agent = str(target.get("agent_name") or "").strip() or agent
+ label = display_name_for_backend(agent) if is_agent_backend(agent) else agent
+ await self._emit_agent_cannot_run(
+ context,
+ request,
+ self._t(f"error.agentUnavailable.{error.reason}", agent=label),
+ failing_backend=None,
+ cause=error,
+ )
+ return
if isinstance(error, ModelSupplyRefusal):
error_text = f"❌ {error}"
else:
@@ -934,6 +953,61 @@ class MessageHandler(BaseHandler):
cause=error,
)
+ async def _emit_agent_cannot_run(
+ self,
+ context: MessageContext,
+ request: AgentRequest | None,
+ reason: str,
+ *,
+ failing_backend: Optional[str],
+ cause: BaseException | None = None,
+ escape_reason: bool = True,
+ ) -> None:
+ """Notify that the session's Agent cannot run, and offer to continue on Vibey.
+
+ The Workbench draws the offer as a button from ``failure_next_step``: it moves
+ the session to the built-in Vibey Agent and runs the failed input there. A
+ chat app cannot change the session's Agent, so its notice says where to.
+ Nothing is offered when Vibey is what cannot run, or is not available.
+ """
+ target = routed_delivery_context(context)
+ workbench = resolve_context_platform(target) == "avibe"
+ if not workbench and escape_reason:
+ reason = self._get_formatter(target).escape_special_chars(reason)
+ # Catalog and Model Hub reads: off the controller loop.
+ offer = failing_backend != "vibey" and await asyncio.to_thread(self._builtin_vibey_available)
+ output = output_with_next_step(request, CONTINUE_ON_VIBEY_NEXT_STEP) if offer and workbench else None
+ text = f"❌ {reason}"
+ if offer:
+ text = f"{text}\n{self._t('error.continueOnVibey.workbench' if workbench else 'error.continueOnVibey.im')}"
+ await emit_backend_failure(
+ self.controller,
+ context,
+ str(failing_backend or getattr(request, "vibe_agent_backend", None) or "agent"),
+ text,
+ display_text=text,
+ request=request,
+ output=output,
+ cause=cause,
+ )
+
+ def _builtin_vibey_available(self) -> bool:
+ """Whether a continuation on Vibey could run now: its built-in Agent exists and
+ the Model Hub supplies it a model (the same answer a Vibey turn starts from).
+ Blocking. A problem with Vibey's own selected model is not predicted here: the
+ continuation then ends with Vibey's own notice, which says what to fix."""
+ from modules.agents.model_hub import hub_supply_refusal
+
+ store = getattr(self.controller, "vibe_agent_store", None)
+ getter = getattr(store, "get_builtin_default_agent_for_backend", None)
+ if not callable(getter):
+ return False
+ try:
+ return getter("vibey") is not None and hub_supply_refusal(self.controller, "vibey", self._get_lang()) is None
+ except Exception:
+ logger.debug("Could not resolve whether Vibey can run", exc_info=True)
+ return False
+
async def _admit_human_delivery(
self,
*,
@@ -1741,15 +1815,11 @@ class MessageHandler(BaseHandler):
display_backend = display_name_for_backend(backend) if backend else str(target)
hint_key = f"error.agentNotConfiguredHint.{backend}" if backend else "error.agentNotConfiguredHint.generic"
hint = self._t(hint_key)
- msg = f"❌ {self._t('error.agentNotConfigured', agent=target, backend=display_backend, hint=hint)}"
+ reason = self._t('error.agentNotConfigured', agent=target, backend=display_backend, hint=hint)
+ msg = f"❌ {reason}"
if request is not None:
- await emit_backend_failure(
- self.controller,
- context,
- backend or str(target),
- msg,
- display_text=msg,
- request=request,
+ await self._emit_agent_cannot_run(
+ context, request, reason, failing_backend=backend or str(target), escape_reason=False
)
return
await self._get_im_client(context).send_message(context, msg)
diff --git a/docs/plans/2026-10-22-session-backend-switch.md b/docs/plans/2026-10-22-session-backend-switch.md
index bf10d68da..4903cdae5 100644
--- a/docs/plans/2026-10-22-session-backend-switch.md
+++ b/docs/plans/2026-10-22-session-backend-switch.md
@@ -124,6 +124,24 @@ One bounded block, rendered in English for the model:
then shown in order. Each message is clipped.
4. A runnable `vibe data query` for the full history.
+## Continue on Vibey when the Agent cannot run
+
+When the session's Agent is disabled or deleted, or its backend is unavailable,
+the turn ends before anything reaches a backend. The failure notice names the
+cause in plain words and carries `failure_next_step: continue_on_vibey`. In the
+Workbench it replaces Retry with **Continue with Vibey**; a chat app's notice
+says to switch in the Workbench instead, since an IM thread cannot change its
+session's Agent.
+
+The button posts the notice's Retry with `continue_on_backend: "vibey"`. In one
+transaction the route switches the session to the built-in Vibey Agent (the
+same `update_session` switch and controller preflight as the Chat header, so a
+bound session gets the handoff) and reserves the retry. The retry re-queues the
+exact message that failed. A not-yet-written input belongs to no backend, so the
+retry boundary admits it on the backend the session now routes to; a turn that
+reached its backend still retries only there, and then the switch rolls back
+with the refused retry.
+
## Known by design
- The handoff is lossy: tool calls, file reads, and reasoning of the old backend
diff --git a/tests/test_backend_failure_retry.py b/tests/test_backend_failure_retry.py
index 75354cee1..8cf6d3f63 100644
--- a/tests/test_backend_failure_retry.py
+++ b/tests/test_backend_failure_retry.py
@@ -1333,3 +1333,117 @@ def test_stale_retry_releases_a_newer_input_waiting_behind_its_reservation(manag
asyncio.run(admit())
assert len(starts) == 1
assert starts[0][1] == "new task"
+
+
[email protected]("bound", [False, True])
+def test_continue_on_vibey_moves_the_session_and_runs_the_unwritten_message(isolated_state, tmp_path, monkeypatch, bound):
+ """A message that never reached its disabled Agent continues on the built-in Vibey
+ Agent: one request moves the session (the same switch, with its handoff when the
+ session had a conversation) and runs that exact message there. The move and the
+ retry commit together, so a notice whose input did reach the old backend refuses
+ both and leaves the session where it was."""
+ from core.vibe_agents import VibeAgentStore
+ from vibe.ui_server import app
+
+ # The Model Hub supplies Vibey a model unless a step below says otherwise.
+ monkeypatch.setattr("vibe.ui_server._backend_supply_blocked", lambda _backend: False)
+ store = VibeAgentStore()
+ try:
+ vibey = store.ensure_builtin_default_agent(backend="vibey")
+ finally:
+ store.close()
+ session_id, notice, _turn, _inputs = _retry_notice(tmp_path, backend="codex", not_written=True)
+ if bound:
+ with create_sqlite_engine().begin() as conn:
+ conn.execute(
+ update(agent_sessions).where(agent_sessions.c.id == session_id).values(native_session_id="codex-thread")
+ )
+ client = app.test_client()
+ headers = csrf_headers(client)
+ url = f"/api/sessions/{session_id}/messages"
+ idle = AsyncMock(return_value={"status_code": 200, "body": {"ok": True, "in_flight": False}})
+
+ assert client.post(url, headers=headers, json={"continue_on_backend": "vibey", "text": "x"}).status_code == 400
+ continue_body = {"retry_for": notice["id"], "continue_on_backend": "vibey"}
+ from core.vibe_agents import VibeAgentAccessError
+
+ with patch("core.vibe_agents.ensure_agent_selection_access", side_effect=VibeAgentAccessError("denied")):
+ assert client.post(url, headers=headers, json=continue_body).status_code == 403
+ # A notice offered while Vibey could run may be clicked after it no longer can.
+ with patch("vibe.ui_server._backend_supply_blocked", return_value=True):
+ stale = client.post(url, headers=headers, json=continue_body)
+ assert (stale.status_code, stale.get_json()["code"]) == (409, "continue_agent_unavailable")
+ # Without the controller there is nothing to run the input: nothing moves.
+ from vibe import internal_client
+
+ with patch("vibe.internal_client.turn_state", AsyncMock(side_effect=internal_client.InternalServerUnavailable("down"))):
+ offline = client.post(url, headers=headers, json=continue_body)
+ assert (offline.status_code, offline.get_json()["code"]) == (503, "controller_unavailable")
+ with create_sqlite_engine().connect() as conn:
+ assert conn.execute(
+ select(agent_sessions.c.agent_backend).where(agent_sessions.c.id == session_id)
+ ).scalar_one() == "codex"
+ dispatch = AsyncMock(return_value={"status_code": 202, "body": {"delivery_state": "queued", "queued": True}})
+ with (
+ patch("vibe.internal_client.turn_state", idle),
+ patch("vibe.internal_client.dispatch_async", dispatch),
+ # The session's own Agent may be deleted and unusable by this caller: the
+ # continuation never runs it, so only the target Agent's access counts.
+ patch("core.vibe_agents.ensure_session_agent_access", side_effect=PermissionError("deleted Agent")),
+ ):
+ response = client.post(url, headers=headers, json=continue_body)
+ assert response.status_code == 202
+ assert dispatch.await_args.args[0]["message_id"] == _inputs[0]["id"]
+ assert dispatch.await_args.args[0]["text"] == "检查这张图"
+ with create_sqlite_engine().connect() as conn:
+ session = conn.execute(select(agent_sessions).where(agent_sessions.c.id == session_id)).mappings().one()
+ assert (session["agent_backend"], session["agent_name"]) == ("vibey", vibey.name)
+ assert ("backend_handoff" in json.loads(session["metadata_json"])) is bound
+
+ # A repeated click resolves to that retry and does not move the session again,
+ # even after the user picked another Vibey Agent.
+ with create_sqlite_engine().begin() as conn:
+ conn.execute(update(agent_sessions).where(agent_sessions.c.id == session_id).values(agent_name="vibey-helper"))
+ with patch("vibe.internal_client.turn_state", idle), patch("vibe.internal_client.dispatch_async", dispatch):
+ again = client.post(url, headers=headers, json=continue_body)
+ assert again.status_code in {201, 202}
+ with create_sqlite_engine().connect() as conn:
+ assert conn.execute(
+ select(agent_sessions.c.agent_name).where(agent_sessions.c.id == session_id)
+ ).scalar_one() == "vibey-helper"
+ # Already on the target backend, the action still needs the controller.
+ with patch("vibe.internal_client.turn_state", AsyncMock(side_effect=internal_client.InternalServerUnavailable("down"))):
+ same_backend = client.post(url, headers=headers, json=continue_body)
+ assert (same_backend.status_code, same_backend.get_json()["code"]) == (503, "controller_unavailable")
+
+
+def test_continue_on_vibey_refuses_a_message_the_old_backend_already_ran(isolated_state, tmp_path, monkeypatch):
+ """The move and the retry commit together: a continuation of a turn that reached
+ the old backend belongs to it, so both are refused and the session stays put."""
+ from core.vibe_agents import VibeAgentStore
+ from vibe.ui_server import app
+
+ monkeypatch.setattr("vibe.ui_server._backend_supply_blocked", lambda _backend: False)
+ store = VibeAgentStore()
+ try:
+ store.ensure_builtin_default_agent(backend="vibey")
+ finally:
+ store.close()
+ failed_session, failed_notice, _turn, _inputs = _retry_notice(tmp_path, backend="codex")
+ client = app.test_client()
+ headers = csrf_headers(client)
+ idle = AsyncMock(return_value={"status_code": 200, "body": {"ok": True, "in_flight": False}})
+ with patch("vibe.internal_client.turn_state", idle), patch("vibe.internal_client.dispatch_async", AsyncMock()) as never:
+ refused = client.post(
+ f"/api/sessions/{failed_session}/messages",
+ headers=headers,
+ json={"retry_for": failed_notice["id"], "continue_on_backend": "vibey"},
+ )
+ assert refused.status_code == 409
+ assert refused.get_json()["code"] == "retry_not_available"
+ never.assert_not_awaited()
+ with create_sqlite_engine().connect() as conn:
+ unchanged = conn.execute(
+ select(agent_sessions.c.agent_backend).where(agent_sessions.c.id == failed_session)
+ ).scalar_one()
+ assert unchanged == "codex"
diff --git a/tests/test_message_handler_missing_agent.py b/tests/test_message_handler_missing_agent.py
index 426ee2b6f..2b9f13142 100644
--- a/tests/test_message_handler_missing_agent.py
+++ b/tests/test_message_handler_missing_agent.py
@@ -107,3 +107,102 @@ def test_dispatched_missing_agent_preserves_primary_delivery_in_terminal_contrac
"delivered": True,
}
assert controller.im_client.sent == []
+
+
+def test_an_agent_that_cannot_run_offers_to_continue_on_vibey(monkeypatch):
+ """A disabled or deleted Agent ends the turn with a notice that names it and
+ offers Vibey: the Workbench draws the offer as a button from data, a chat app
+ is told where to switch. Without a built-in Vibey there is nothing to offer,
+ and a backend that is missing is offered Vibey unless Vibey is what is missing."""
+ from unittest.mock import AsyncMock, patch
+
+ from core.backend_failure import CONTINUE_ON_VIBEY_NEXT_STEP
+ from core.vibe_agents import AgentUnavailableError
+
+ from modules.agents.model_hub import ModelSupplyRefusal
+
+ # The Model Hub supplies Vibey a model unless a case below says otherwise.
+ monkeypatch.setattr("modules.agents.model_hub.hub_supply_refusal", lambda _controller, _backend, _lang: None)
+ controller = _StubController()
+ controller.im_client.formatter = SimpleNamespace(escape_special_chars=lambda text: text)
+ vibey = SimpleNamespace(name="vibey")
+ controller.vibe_agent_store = SimpleNamespace(
+ get=lambda _name: None, get_builtin_default_agent_for_backend=lambda backend: vibey
+ )
+ handler = MessageHandler(controller)
+ workbench = MessageContext(user_id="U1", channel_id="ses-1", platform="avibe")
+ telegram = MessageContext(user_id="U1", channel_id="C1", platform="telegram")
+ disabled = AgentUnavailableError("agent 'codex' is disabled", agent_name="codex", reason="disabled")
+ deleted = AgentUnavailableError("agent 'reviewer' not found", agent_name="reviewer", reason="missing")
+
+ def emitted_for(*calls):
+ emitted = AsyncMock()
+ with patch.dict(MessageHandler._emit_agent_cannot_run.__globals__, emit_backend_failure=emitted):
+ for call in calls:
+ anyio.run(*call)
+ return emitted.await_args_list
+
+ workbench_call, im_call, deleted_call = emitted_for(
+ (handler._emit_agent_dispatch_failure, workbench, None, disabled),
+ (handler._emit_agent_dispatch_failure, telegram, None, disabled),
+ (handler._emit_agent_dispatch_failure, workbench, None, deleted),
+ )
+ disabled_text = handler._t("error.agentUnavailable.disabled", agent="Codex")
+ assert workbench_call.kwargs["display_text"] == (
+ f"❌ {disabled_text}\n{handler._t('error.continueOnVibey.workbench')}"
+ )
+ assert workbench_call.kwargs["output"].metadata["failure_next_step"] == CONTINUE_ON_VIBEY_NEXT_STEP
+ assert workbench_call.kwargs["cause"] is disabled
+ assert im_call.kwargs["display_text"] == f"❌ {disabled_text}\n{handler._t('error.continueOnVibey.im')}"
+ assert im_call.kwargs["output"] is None
+ assert handler._t("error.agentUnavailable.missing", agent="reviewer") in deleted_call.kwargs["display_text"]
+ # Resolved by id, a deleted Agent names only its id; the session still knows its name.
+ by_id = AgentUnavailableError("agent id 'a1b2' not found", agent_name="a1b2", reason="missing")
+ targeted = MessageContext(
+ user_id="U1",
+ channel_id="ses-1",
+ platform="avibe",
+ platform_specific={"agent_session_target": {"id": "ses-1", "agent_id": "a1b2", "agent_name": "reviewer"}},
+ )
+ (by_id_call,) = emitted_for((handler._emit_agent_dispatch_failure, targeted, None, by_id))
+ assert handler._t("error.agentUnavailable.missing", agent="reviewer") in by_id_call.kwargs["display_text"]
+ assert "a1b2" not in by_id_call.kwargs["display_text"]
+ assert "agent 'codex' is disabled" not in workbench_call.kwargs["display_text"]
+
+ controller.vibe_agent_store = SimpleNamespace(
+ get=lambda _name: None, get_builtin_default_agent_for_backend=lambda backend: None
+ )
+ (no_vibey,) = emitted_for((handler._emit_agent_dispatch_failure, workbench, None, disabled))
+ assert no_vibey.kwargs["display_text"] == f"❌ {disabled_text}"
+ assert no_vibey.kwargs["output"] is None
+
+ # Vibey exists but the Model Hub supplies it no model: the continuation would only
+ # fail again, so it is not offered either.
+ controller.vibe_agent_store = SimpleNamespace(
+ get=lambda _name: None, get_builtin_default_agent_for_backend=lambda backend: vibey
+ )
+ monkeypatch.setattr(
+ "modules.agents.model_hub.hub_supply_refusal",
+ lambda _controller, backend, _lang: ModelSupplyRefusal("no source", fixed_in_models=True),
+ )
+ (no_supply,) = emitted_for((handler._emit_agent_dispatch_failure, workbench, None, disabled))
+ assert no_supply.kwargs["display_text"] == f"❌ {disabled_text}"
+ assert no_supply.kwargs["output"] is None
+ monkeypatch.setattr("modules.agents.model_hub.hub_supply_refusal", lambda _controller, _backend, _lang: None)
+
+ controller.vibe_agent_store = SimpleNamespace(
+ get=lambda _name: None, get_builtin_default_agent_for_backend=lambda backend: vibey
+ )
+ request = AgentRequest(
+ context=workbench,
+ message="hello",
+ user_message="hello",
+ working_path="/tmp",
+ base_session_id="base",
+ composite_session_id="base:/tmp",
+ session_key="avibe::ses-1",
+ )
+ for target, offered in (("codex", True), ("vibey", False)):
+ (call,) = emitted_for((lambda t=target: handler._handle_missing_agent(workbench, t, request=request),))
+ assert (call.kwargs["output"] is not None) is offered
+ assert (handler._t("error.continueOnVibey.workbench") in call.kwargs["display_text"]) is offered
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index cbb0d7236..e355bcc19 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -1358,15 +1358,15 @@ def test_sessions_patch_bound_backend_switch_waits_for_the_old_runtime(monkeypat
return AsyncMock(return_value={"status_code": 200, "body": {"ok": True, "in_flight": False, **body}})
refusals = (
- turn_state(background_activities=[{"item_kind": "backend_activity", "id": "act-1"}]),
- turn_state(pending_activity_output_count=1),
- AsyncMock(side_effect=internal_client.InternalServerUnavailable("down")),
+ (turn_state(background_activities=[{"item_kind": "backend_activity", "id": "act-1"}]), 409, "backend_busy"),
+ (turn_state(pending_activity_output_count=1), 409, "backend_busy"),
+ (AsyncMock(side_effect=internal_client.InternalServerUnavailable("down")), 503, "controller_unavailable"),
)
- for probe in refusals:
+ for probe, status, code in refusals:
with patch("vibe.internal_client.turn_state", probe):
refused = client.patch(f"/api/sessions/{sid}", json={"agent_name": "reviewer"}, headers=headers)
- assert refused.status_code == 409
- assert refused.get_json()["code"] == "backend_busy"
+ assert refused.status_code == status
+ assert refused.get_json()["code"] == code
settled = turn_state(background_activities=[{"item_kind": "watch", "id": "watch-1"}])
with patch("vibe.internal_client.turn_state", settled):
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index e7944d6ba..eeb4a8ff7 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -21,7 +21,7 @@ import { readChatViewMode, writeChatViewMode } from '../../lib/chatViewMemory';
import { normalizeChatMessageFontSize } from '../../lib/chatDisplay';
import { setConfigField } from '../../lib/configMutations';
import { annotationStandIn, annotationTitleKey, readAnnotationView } from '../../lib/annotationView';
-import { isAgentActivityBoundaryMessage, isRetriedFailureNotice, isRetryableFailureNotice, isTerminalAgentMessage, isTranscriptMessage, shouldRefreshAgentActivityForMessage } from '../../lib/chatMessageTypes';
+import { isAgentActivityBoundaryMessage, isRetriedFailureNotice, isRetryableFailureNotice, isTerminalAgentMessage, offersContinueOnVibey, isTranscriptMessage, shouldRefreshAgentActivityForMessage } from '../../lib/chatMessageTypes';
import { chatRowKind, drawsEmptyBodyPlaceholder, isAgentAuthored } from '../../lib/chatRowKind';
import { useIosKeyboardInset } from '../../lib/useIosKeyboardInset';
import { isProxyMediaUrl } from '../../lib/mediaProxy';
@@ -64,7 +64,7 @@ import {
} from '../../lib/chatTrigger';
import { AnnotationMessage } from './AnnotationMessage';
import { FailureDetails } from './FailureDetails';
-import { FailureRetry } from './FailureRetry';
+import { FailureRetry, type FailureRetryOptions } from './FailureRetry';
import { FailureNextStep } from './FailureNextStep';
import { AGENT_BUBBLE, SYSTEM_BUBBLE, USER_BUBBLE } from './chatBubble';
import { RoleAvatar } from './RoleAvatar';
@@ -2248,16 +2248,21 @@ export const ChatPage: React.FC = () => {
[sendMessage],
);
- const handleFailureRetry = useCallback(async (messageId: string): Promise<boolean> => {
+ const handleFailureRetry = useCallback(async (messageId: string, options?: FailureRetryOptions): Promise<boolean> => {
const sid = sessionId;
if (!sid || !writable) return false;
setError(null);
try {
// A notice-bound action does not read, clear, or restore the composer.
+ // ``continueOnBackend`` moves the session to that backend's built-in Agent
+ // first, in the same server transaction as the retry.
const response = await apiFetch(`/api/sessions/${encodeURIComponent(sid)}/messages`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ retry_for: messageId }),
+ body: JSON.stringify({
+ retry_for: messageId,
+ ...(options?.continueOnBackend ? { continue_on_backend: options.continueOnBackend } : {}),
+ }),
});
const body = await response.json().catch(() => null);
if (sid !== sessionIdRef.current) return false;
@@ -2286,6 +2291,8 @@ export const ChatPage: React.FC = () => {
else appendMessage(body as WorkbenchMessage);
}
void refreshQueue();
+ // The header shows the Agent the session moved to.
+ if (options?.continueOnBackend) void refreshSessionRow();
return ['queued', 'claimed', 'accepted'].includes(body?.delivery_state ?? body?.state ?? '');
} catch (err) {
if (sid === sessionIdRef.current) setError(errorMessage(err) ?? t('chat.retryFailed'));
@@ -2293,7 +2300,7 @@ export const ChatPage: React.FC = () => {
} finally {
if (sid === sessionIdRef.current) void syncTurnStateRef.current?.();
}
- }, [sessionId, writable, api, appendMessage, reloadLatestMessages, refreshQueue, t]);
+ }, [sessionId, writable, api, appendMessage, reloadLatestMessages, refreshQueue, refreshSessionRow, t]);
const stopMessage = useCallback(async () => {
if (!sessionId || !working) return;
@@ -3962,7 +3969,7 @@ interface TranscriptProps {
highlightedId: string | null;
messageFontSize: number;
onQuickReply: (messageId: string, choice: string) => boolean | void | Promise<boolean | void>;
- onFailureRetry?: (messageId: string) => Promise<boolean>;
+ onFailureRetry?: (messageId: string, options?: FailureRetryOptions) => Promise<boolean>;
provisionRequestsByMessage: Map<string, VaultRequest[]>;
onVaultRequestResolved: () => void;
// Chat-selection toolbar: quote the selection into the composer, or fork +
@@ -4699,7 +4706,7 @@ type MessageRowProps = {
agentBackend?: string | null;
messageFontSize: number;
onQuickReply?: (messageId: string, choice: string) => boolean | void | Promise<boolean | void>;
- onFailureRetry?: (messageId: string) => Promise<boolean>;
+ onFailureRetry?: (messageId: string, options?: FailureRetryOptions) => Promise<boolean>;
retryDisabled?: boolean;
vaultRequests?: VaultRequest[];
onVaultRequestResolved?: () => void;
@@ -4943,8 +4950,13 @@ export const MessageRow = memo(function MessageRow({
</span>
</div>
<div className="flex flex-wrap items-center gap-1.5 empty:hidden">
- <FailureNextStep message={message} />
- {onFailureRetry && (
+ <FailureNextStep
+ message={message}
+ readOnly={readOnly}
+ disabled={retryDisabled}
+ onRetry={onFailureRetry}
+ />
+ {onFailureRetry && !offersContinueOnVibey(message) && (
<FailureRetry
message={message}
readOnly={readOnly}
diff --git a/ui/src/components/workbench/FailureNextStep.test.tsx b/ui/src/components/workbench/FailureNextStep.test.tsx
index cd758998c..c7d466282 100644
--- a/ui/src/components/workbench/FailureNextStep.test.tsx
+++ b/ui/src/components/workbench/FailureNextStep.test.tsx
@@ -1,6 +1,6 @@
/** @vitest-environment jsdom */
-import { cleanup, fireEvent, render, screen } from '@testing-library/react';
-import { afterEach, describe, expect, it } from 'vitest';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { createInstance } from 'i18next';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
@@ -22,7 +22,9 @@ const refusal = {
metadata: { event: 'backend_failure', failure_id: 'failed', turn_id: 'turn-1', failure_next_step: 'models' },
} as WorkbenchMessage;
-function mount(message: WorkbenchMessage, canManage: boolean) {
+type StepProps = Omit<Parameters<typeof FailureNextStep>[0], 'message'>;
+
+function mount(message: WorkbenchMessage, canManage: boolean, props: StepProps = {}) {
const authorization = {
remote: true, instanceKind: null, instanceRole: null,
capabilities: { ...DENIED_INSTANCE_CAPABILITIES, can_chat: true, can_manage_instance: canManage },
@@ -32,7 +34,7 @@ function mount(message: WorkbenchMessage, canManage: boolean) {
<InstanceAuthorizationContext.Provider value={authorization as never}>
<MemoryRouter initialEntries={['/chat/session']}>
<Routes>
- <Route path="/chat/session" element={<FailureNextStep message={message} />} />
+ <Route path="/chat/session" element={<FailureNextStep message={message} {...props} />} />
<Route path="/settings/models" element={<p>Models page</p>} />
</Routes>
</MemoryRouter>
@@ -60,4 +62,27 @@ describe('FailureNextStep', () => {
const { container } = mount({ ...refusal, metadata: { ...refusal.metadata, failure_next_step: undefined } }, true);
expect(container.textContent).toBe('');
});
+
+ // The Agent the session runs on was disabled: the notice offers to move to Vibey.
+ const agentOff = {
+ ...refusal,
+ text: '❌ Codex is turned off, so this session can\'t continue on it.',
+ metadata: { ...refusal.metadata, failure_next_step: 'continue_on_vibey' },
+ } as WorkbenchMessage;
+
+ it('continues on Vibey through the notice-bound retry', async () => {
+ const onRetry = vi.fn().mockResolvedValue(true);
+ mount(agentOff, false, { onRetry });
+ fireEvent.click(screen.getByRole('button', { name: 'Continue with Vibey' }));
+ expect(onRetry).toHaveBeenCalledWith('notice', { continueOnBackend: 'vibey' });
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Switched to Vibey' })).toHaveProperty('disabled', true));
+ });
+
+ it('offers nothing on a read-only transcript, and settles from the durable retry state', () => {
+ mount(agentOff, true, { readOnly: true, onRetry: vi.fn() });
+ expect(screen.queryByRole('button')).toBeNull();
+ cleanup();
+ mount({ ...agentOff, content: { failure_retry: { state: 'accepted' } } } as WorkbenchMessage, true, { onRetry: vi.fn() });
+ expect(screen.getByRole('button', { name: 'Switched to Vibey' })).toHaveProperty('disabled', true);
+ });
});
diff --git a/ui/src/components/workbench/FailureNextStep.tsx b/ui/src/components/workbench/FailureNextStep.tsx
index 3edd55f16..c7136eb4a 100644
--- a/ui/src/components/workbench/FailureNextStep.tsx
+++ b/ui/src/components/workbench/FailureNextStep.tsx
@@ -1,24 +1,45 @@
-import { ArrowRight } from 'lucide-react';
+import { useRef, useState } from 'react';
+import { ArrowRight, Check } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate } from 'react-router-dom';
import type { WorkbenchMessage } from '../../context/ApiContext';
import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
-import { isBackendFailureNotice } from '../../lib/chatMessageTypes';
+import { ADMITTED_RETRY_STATES, isBackendFailureNotice, offersContinueOnVibey } from '../../lib/chatMessageTypes';
import { settingsOverlayContinuationState } from '../../lib/settingsOverlay';
import { MODEL_HUB_SETTINGS_PATH } from '../settings/models/modelHubRoutes';
import { Button } from '../ui/button';
+import type { FailureRetryOptions } from './FailureRetry';
/** The step a failure notice names as data (`failure_next_step`), drawn from the Workbench's
* own copy: a notice is plain text, so any link in it comes from here, never from its body.
* Models is for those who manage the instance; anyone else is told who can fix it. Opening Models
- * writes nothing to the Session, so a read-only transcript shows the step too. */
-export function FailureNextStep({ message }: { message: WorkbenchMessage }) {
+ * writes nothing to the Session, so a read-only transcript shows the step too. Continuing on
+ * Vibey writes the Session, so it needs a writable transcript. */
+export function FailureNextStep({
+ message,
+ readOnly,
+ disabled,
+ onRetry,
+}: {
+ message: WorkbenchMessage;
+ readOnly?: boolean;
+ disabled?: boolean;
+ onRetry?: (messageId: string, options?: FailureRetryOptions) => Promise<boolean>;
+}) {
+ if (!isBackendFailureNotice(message)) return null;
+ if (message.metadata?.failure_next_step === 'models') return <OpenModelsStep />;
+ if (!readOnly && onRetry && offersContinueOnVibey(message)) {
+ return <ContinueOnVibeyStep message={message} disabled={disabled} onRetry={onRetry} />;
+ }
+ return null;
+}
+
+function OpenModelsStep() {
const { t } = useTranslation();
const navigate = useNavigate();
const location = useLocation();
const { capabilities } = useInstanceAuthorization();
- if (!isBackendFailureNotice(message) || message.metadata?.failure_next_step !== 'models') return null;
if (!capabilities.can_manage_instance) {
return <span className="px-0.5 text-[11px] text-muted-foreground">{t('chat.failureNextStep.askAdmin')}</span>;
}
@@ -34,3 +55,45 @@ export function FailureNextStep({ message }: { message: WorkbenchMessage }) {
</Button>
);
}
+
+function ContinueOnVibeyStep({
+ message,
+ disabled,
+ onRetry,
+}: {
+ message: WorkbenchMessage;
+ disabled?: boolean;
+ onRetry: (messageId: string, options?: FailureRetryOptions) => Promise<boolean>;
+}) {
+ const { t } = useTranslation();
+ const pending = useRef(false);
+ const [sending, setSending] = useState(false);
+ const [requested, setRequested] = useState(false);
+ const action = message.content?.failure_retry as { state?: string } | undefined;
+ // As with Retry: the durable retry state decides once present; local success only
+ // bridges the response.
+ const admitted = action?.state ? ADMITTED_RETRY_STATES.includes(action.state) : requested;
+ return (
+ <Button
+ type="button"
+ size="2xs"
+ variant="secondary"
+ disabled={disabled || sending || admitted}
+ aria-busy={sending}
+ onClick={async () => {
+ if (pending.current || admitted || disabled) return;
+ pending.current = true;
+ setSending(true);
+ try {
+ setRequested(await onRetry(message.id, { continueOnBackend: 'vibey' }));
+ } finally {
+ pending.current = false;
+ setSending(false);
+ }
+ }}
+ >
+ {admitted ? <Check /> : <ArrowRight />}
+ {t(admitted ? 'chat.failureNextStep.continuedOnVibey' : 'chat.failureNextStep.continueOnVibey')}
+ </Button>
+ );
+}
diff --git a/ui/src/components/workbench/FailureRetry.tsx b/ui/src/components/workbench/FailureRetry.tsx
index 64dcd2b7c..7224c9f81 100644
--- a/ui/src/components/workbench/FailureRetry.tsx
+++ b/ui/src/components/workbench/FailureRetry.tsx
@@ -6,6 +6,11 @@ import type { WorkbenchMessage } from '../../context/ApiContext';
import { ADMITTED_RETRY_STATES, isRetryableFailureNotice } from '../../lib/chatMessageTypes';
import { Button } from '../ui/button';
+/** What a notice-bound Retry may also do: continue on another backend's built-in Agent. */
+export interface FailureRetryOptions {
+ continueOnBackend?: string;
+}
+
export function FailureRetry({
message,
readOnly,
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index e9ae7cefb..268746c1c 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2854,6 +2854,8 @@
"session_archived": "This session is archived, so its Show Page can't be changed.",
"backend_locked": "This session can't change to that backend now. A running turn has to finish first, and a Vibey session stays on Vibey.",
"backend_busy": "This session still has background work running on its current backend. Switch after it finishes.",
+ "controller_unavailable": "Avibe's service isn't reachable right now. Try again in a moment.",
+ "continue_agent_unavailable": "Vibey isn't available right now, so this session can't switch to it.",
"reserved_session": "Avibe owns this session — it only receives workspace notifications.",
"invalid_icon_type": "The icon must be an SVG, PNG, ICO, JPEG, or WebP image.",
"icon_too_large": "That icon is too large. Use an image up to 2 MiB.",
@@ -4940,7 +4942,9 @@
"retryRequested": "Retry requested",
"failureNextStep": {
"openModels": "Open Models",
- "askAdmin": "Ask an Avibe admin to fix this in Models."
+ "askAdmin": "Ask an Avibe admin to fix this in Models.",
+ "continueOnVibey": "Continue with Vibey",
+ "continuedOnVibey": "Switched to Vibey"
},
"retryFailed": "Could not request retry. You can try again safely.",
"collapse": "Collapse",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 332320377..1d7782379 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2854,6 +2854,8 @@
"session_archived": "该会话已归档,无法修改它的展示页面。",
"backend_locked": "这个会话现在不能切换到该后端:正在运行的回合需要先结束,Vibey 会话只能留在 Vibey。",
"backend_busy": "这个会话在当前后端上还有后台任务在运行,等它结束后再切换。",
+ "controller_unavailable": "暂时连不上 Avibe 服务,请稍后再试。",
+ "continue_agent_unavailable": "Vibey 现在用不了,这个会话暂时没法切换过去。",
"reserved_session": "该会话由 Avibe 管理,只接收工作区通知。",
"invalid_icon_type": "图标必须是 SVG、PNG、ICO、JPEG 或 WebP 图片。",
"icon_too_large": "图标太大了,请使用不超过 2 MiB 的图片。",
@@ -4940,7 +4942,9 @@
"retryRequested": "已请求重试",
"failureNextStep": {
"openModels": "打开「模型」页",
- "askAdmin": "请联系 Avibe 管理员在「模型」页处理。"
+ "askAdmin": "请联系 Avibe 管理员在「模型」页处理。",
+ "continueOnVibey": "切换到 Vibey 继续",
+ "continuedOnVibey": "已切换到 Vibey"
},
"retryFailed": "未能提交重试,可以再次点击。",
"collapse": "收起",
diff --git a/ui/src/lib/chatMessageTypes.ts b/ui/src/lib/chatMessageTypes.ts
index fec314d64..d86fc0093 100644
--- a/ui/src/lib/chatMessageTypes.ts
+++ b/ui/src/lib/chatMessageTypes.ts
@@ -101,6 +101,16 @@ export function isRetryableFailureNotice(
&& !(Array.isArray(metadata.watch_ids) && metadata.watch_ids.length > 0);
}
+// A notice whose Agent cannot run (disabled, deleted, or its backend unavailable), which
+// offers to move the session to Vibey and run the failed message there
+// (``failure_next_step: continue_on_vibey``). That action replaces the plain Retry, which
+// would only fail the same way again.
+export function offersContinueOnVibey(
+ message: TerminalAgentMessageCandidate & { source?: string | null },
+): boolean {
+ return isRetryableFailureNotice(message) && message.metadata?.failure_next_step === 'continue_on_vibey';
+}
+
// The Retry states in which the notice's continuation is admitted: it was queued,
// claimed, or accepted into a Turn. ``reserved`` and ``retired`` are not.
export const ADMITTED_RETRY_STATES: readonly string[] = ['queued', 'claimed', 'accepted'];
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 50028baf4..3d395d9b2 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -12,7 +12,9 @@
"modelsNextStepImUrl": "Someone who manages this Avibe can fix it in Models: {url}",
"modelsNextStepIm": "Someone who manages this Avibe can fix it in Models, in the Avibe Workbench.",
"opencodeModelProviderRequired": "Select an OpenCode model with a provider in Avibe, or configure its Model Hub route.",
- "sessionBackendBusy": "This session still has background work running on its current backend. Switch after it finishes."
+ "sessionBackendBusy": "This session still has background work running on its current backend. Switch after it finishes.",
+ "sessionControllerUnavailable": "Avibe's service isn't reachable right now. Try again in a moment.",
+ "sessionContinueAgentUnavailable": "{backend} isn't available right now, so this session can't switch to it."
},
"status": {
"backendUnresponsive": "backend not responding",
@@ -465,6 +467,14 @@
"generic": "Choose an enabled Agent in Agent settings, or enable the backend this Agent uses."
},
"processMessageFailed": "Error: {error}",
+ "agentUnavailable": {
+ "disabled": "{agent} is turned off, so this session can't continue on it.",
+ "missing": "{agent} was deleted, so this session can't continue on it."
+ },
+ "continueOnVibey": {
+ "workbench": "Switch to Vibey to pick up right where you left off.",
+ "im": "Open this session in the Avibe Workbench and switch it to Vibey to keep going."
+ },
"streamTurnInProgress": "⚠️ A reply is already streaming for this session — wait for it to finish, then try again.",
"sessionReset": "Session error detected. Session has been reset. Please try your message again.",
"sessionConnectionLost": "Connection to Claude was lost. Please try your message again.",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index c6f1122b2..44b206171 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -12,7 +12,9 @@
"modelsNextStepImUrl": "管理这个 Avibe 的人可以在「模型」页处理:{url}",
"modelsNextStepIm": "管理这个 Avibe 的人可以在 Avibe 工作台的「模型」页处理。",
"opencodeModelProviderRequired": "请在 Avibe 中选择带供应商的 OpenCode 模型,或配置它的 Model Hub 路由。",
- "sessionBackendBusy": "这个会话在当前后端上还有后台任务在运行,等它结束后再切换。"
+ "sessionBackendBusy": "这个会话在当前后端上还有后台任务在运行,等它结束后再切换。",
+ "sessionControllerUnavailable": "暂时连不上 Avibe 服务,请稍后再试。",
+ "sessionContinueAgentUnavailable": "{backend} 现在用不了,这个会话暂时没法切换过去。"
},
"status": {
"backendUnresponsive": "后端无响应",
@@ -465,6 +467,14 @@
"generic": "请在 Agent 设置里选择一个已启用的 Agent,或启用该 Agent 使用的 backend。"
},
"processMessageFailed": "出错:{error}",
+ "agentUnavailable": {
+ "disabled": "{agent} 已停用,这个会话没法再用它继续。",
+ "missing": "{agent} 已被删除,这个会话没法再用它继续。"
+ },
+ "continueOnVibey": {
+ "workbench": "可以一键切换到 Vibey,无缝接着做。",
+ "im": "可以在 Avibe 工作台打开这个会话,切换到 Vibey 接着做。"
+ },
"streamTurnInProgress": "⚠️ 这个会话已经有一条回复在生成中,请等它完成后再试。",
"sessionReset": "检测到会话错误。会话已重置,请重试。",
"sessionConnectionLost": "与 Claude 的连接已断开,请重试。",
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 58e4390bb..d154fffb9 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -78,7 +78,13 @@ from core.show_session_events import (
show_event_requests_dispatch,
)
from core.terminal_service import TERMINAL_SUPPORTED, TerminalService, TerminalServiceError, sanitize_session_id
-from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS, supports_runtime_refresh
+from modules.agents.catalog import (
+ AGENT_BACKENDS,
+ NATIVE_CLI_BACKENDS,
+ display_name_for_backend,
+ is_agent_backend,
+ supports_runtime_refresh,
+)
from vibe.i18n import get_supported_languages, t
from vibe.logging_config import application_log_paths
from vibe.runtime import get_ui_dist_path, get_working_dir
@@ -10212,6 +10218,81 @@ def _backend_locked_response(err):
)
+def _backend_supply_blocked(backend: str) -> bool:
+ """Whether the Model Hub leaves ``backend`` no model to run on now. Blocking."""
+ from config.v2_config import hub_supply_block
+ from core.services import settings as settings_service
+
+ return hub_supply_block(backend, settings_service.load_config_or_default().model_hub) is not None
+
+
+def _builtin_agent_for_backend(backend: str):
+ """The backend's enabled built-in Agent, or None. Blocking."""
+ from core.vibe_agents import VibeAgentStore
+
+ store = VibeAgentStore()
+ try:
+ return store.get_builtin_default_agent_for_backend(backend)
+ finally:
+ store.close()
+
+
+async def _backend_switch_preflight(engine, session_id: str, requested_backend, *, require_controller: bool = False):
+ """Ask the controller whether the session may change to ``requested_backend``.
+
+ Returns ``(refusal, runtime_idle_through_turn)``: a ready error response, or the
+ turn watermark ``update_session`` commits the switch against. The watermark is
+ read BEFORE the controller is asked, so the switch commits only if no turn
+ started since and the controller's answer still holds then. A BOUND session
+ switches by replacing its native conversation, so the old backend's runtime
+ must also be settled: a detached background Activity (or its undelivered
+ output) would keep working on the replaced conversation. Only the controller
+ knows, so an unreachable controller refuses that switch instead of assuming idle,
+ as it refuses any switch when ``require_controller``.
+ """
+ from core.services import sessions as workbench_sessions_service
+ from vibe import internal_client
+
+ try:
+ with engine.connect() as conn:
+ current = workbench_sessions_service.get_session(conn, session_id)
+ runtime_idle_through_turn = workbench_sessions_service.latest_session_turn_id(conn, session_id)
+ except LookupError as err:
+ return (jsonify({"error": str(err)}), 404), None
+ if str(requested_backend or "") == str(current.get("agent_backend") or "") and not require_controller:
+ return None, runtime_idle_through_turn
+ bound_switch = bool(current.get("native_session_id")) and bool(current.get("agent_backend"))
+ try:
+ turn_result = await internal_client.turn_state(session_id)
+ turn_body = turn_result.get("body") or {}
+ in_flight = bool(turn_body.get("in_flight"))
+ runtime_busy = _backend_runtime_busy(turn_body)
+ except (internal_client.InternalServerUnavailable, internal_client.InternalServerTimeout):
+ if bound_switch or require_controller:
+ from core.services import settings as settings_service
+
+ lang = settings_service.load_config_or_default().language
+ return _coded_error_response(
+ "controller_unavailable", t("errors.sessionControllerUnavailable", lang), 503
+ ), None
+ in_flight = False
+ runtime_busy = False
+ if in_flight:
+ return _backend_locked_response(
+ workbench_sessions_service.SessionBackendLockedError(
+ session_id=session_id,
+ current_backend=current.get("agent_backend"),
+ requested_backend=requested_backend,
+ )
+ ), None
+ if bound_switch and runtime_busy:
+ return _backend_busy_response(
+ current_backend=current.get("agent_backend"),
+ requested_backend=requested_backend,
+ ), None
+ return None, runtime_idle_through_turn
+
+
def _backend_runtime_busy(turn_state: dict) -> bool:
"""Whether the controller reports backend work outside a turn for the session.
@@ -10382,43 +10463,9 @@ async def sessions_update(session_id: str):
# row-status guard inside ``update_session`` (best effort).
runtime_idle_through_turn = None
if should_check_backend_lock:
- try:
- with engine.connect() as conn:
- current = workbench_sessions_service.get_session(conn, session_id)
- # Read BEFORE asking the controller: the switch commits only if no
- # turn started since, so the controller's answer still holds then.
- runtime_idle_through_turn = workbench_sessions_service.latest_session_turn_id(conn, session_id)
- except LookupError as err:
- return jsonify({"error": str(err)}), 404
- if str(requested_backend or "") != str(current.get("agent_backend") or ""):
- # A BOUND session switches by replacing its native conversation, so the
- # old backend's runtime must also be settled: a detached background
- # Activity (or its undelivered output) would keep working on the
- # replaced conversation. Only the controller knows, so an unreachable
- # controller refuses that switch instead of assuming idle.
- bound_switch = bool(current.get("native_session_id")) and bool(current.get("agent_backend"))
- runtime_busy = False
- try:
- turn_result = await internal_client.turn_state(session_id)
- turn_body = turn_result.get("body") or {}
- in_flight = bool(turn_body.get("in_flight"))
- runtime_busy = _backend_runtime_busy(turn_body)
- except (internal_client.InternalServerUnavailable, internal_client.InternalServerTimeout):
- in_flight = False
- runtime_busy = bound_switch
- if in_flight:
- return _backend_locked_response(
- workbench_sessions_service.SessionBackendLockedError(
- session_id=session_id,
- current_backend=current.get("agent_backend"),
- requested_backend=requested_backend,
- )
- )
- if bound_switch and runtime_busy:
- return _backend_busy_response(
- current_backend=current.get("agent_backend"),
- requested_backend=requested_backend,
- )
+ refusal, runtime_idle_through_turn = await _backend_switch_preflight(engine, session_id, requested_backend)
+ if refusal is not None:
+ return refusal
try:
with engine.begin() as conn:
@@ -12106,6 +12153,14 @@ async def sessions_messages_create(session_id: str):
payload = request.json or {}
retry_for = payload.get("retry_for")
+ # ``continue_on_backend`` turns a Retry into "continue on another backend": the
+ # session moves to that backend's built-in Agent and the failed input runs there,
+ # in one transaction (a notice whose Agent was disabled or deleted offers it).
+ continue_on_backend = payload.get("continue_on_backend")
+ if continue_on_backend is not None and (
+ retry_for is None or not isinstance(continue_on_backend, str) or not is_agent_backend(continue_on_backend)
+ ):
+ return jsonify({"error": "invalid continue_on_backend"}), 400
if retry_for is not None:
if not isinstance(retry_for, str) or not retry_for.strip():
return jsonify({"error": "invalid retry_for"}), 400
@@ -12139,7 +12194,10 @@ async def sessions_messages_create(session_id: str):
from core.vibe_agents import ensure_session_agent_access
_config, _session_payload, user_context = _remote_resource_access_context()
- ensure_session_agent_access(conn, session, user_context=user_context)
+ # Continuing on another Agent never runs the session's current one,
+ # which may be deleted; the target Agent's access is checked below.
+ if continue_on_backend is None:
+ ensure_session_agent_access(conn, session, user_context=user_context)
# Archived sessions are terminal + inert: refuse to start a turn on one
# even via a stale/direct request (the workbench hides them from the
# list, so this only fires on a leftover tab or a hand-crafted call).
@@ -12169,6 +12227,35 @@ async def sessions_messages_create(session_id: str):
except PermissionError as err:
return _coded_error_response("agent_access_forbidden", str(err), 403)
+ continue_agent = None
+ continue_idle_through_turn = None
+ if continue_on_backend is not None:
+ from core.vibe_agents import VibeAgentAccessError, ensure_agent_selection_access
+
+ # The store's constructor checks and prefills state: off the event loop.
+ continue_agent = await asyncio.to_thread(_builtin_agent_for_backend, continue_on_backend)
+ # The notice may be older than the state it was offered for: recheck, at the
+ # click, the same answers the offer was made from (``_builtin_vibey_available``).
+ if continue_agent is None or await asyncio.to_thread(_backend_supply_blocked, continue_on_backend):
+ return _coded_error_response(
+ "continue_agent_unavailable",
+ t("errors.sessionContinueAgentUnavailable", _request_ui_language(), backend=display_name_for_backend(continue_on_backend)),
+ 409,
+ )
+ try:
+ with engine.connect() as conn:
+ ensure_agent_selection_access(conn, agent_id=continue_agent.id, user_context=user_context)
+ except VibeAgentAccessError as err:
+ return _coded_error_response("agent_access_forbidden", str(err), 403)
+ # The switch commits only with the controller there to run the input it
+ # retries: committing it for a dispatch that cannot happen would move the
+ # session for nothing.
+ refusal, continue_idle_through_turn = await _backend_switch_preflight(
+ engine, session_id, continue_agent.backend, require_controller=True
+ )
+ if refusal is not None:
+ return refusal
+
dispatch_text = (
(text if isinstance(text, str) else None)
or (content.get("text") if isinstance(content, dict) else None)
@@ -12188,6 +12275,8 @@ async def sessions_messages_create(session_id: str):
conn, session_id=session_id, attachments=raw_attachments
)
+ switched: dict[str, Any] = {}
+
def _persist_user_row() -> dict | None:
"""Atomically persist one unaccepted submission as a Delivery."""
from core.input_admission import InputEnvelope, InputProvenance, InputSender, admit_input
@@ -12225,6 +12314,25 @@ async def sessions_messages_create(session_id: str):
metadata=message_metadata,
message_kind=message_kind,
)
+ from core.backend_failure_retry import existing_retry
+
+ # A repeated click resolves to the retry it already made, without moving
+ # the session again (the user may have picked another Agent since).
+ if continue_agent is not None and existing_retry(conn, session_id, retry_for) is None:
+ # Same switch the Chat header's picker makes, with its guards; a
+ # refused retry below rolls it back with everything else.
+ switched["session"] = workbench_sessions_service.update_session(
+ conn,
+ session_id,
+ agent_id=continue_agent.id,
+ agent_name=continue_agent.name,
+ agent_backend=continue_agent.backend,
+ agent_variant=continue_agent.backend,
+ model=continue_agent.model,
+ reasoning_effort=continue_agent.reasoning_effort,
+ runtime_idle_through_turn=continue_idle_through_turn,
+ authorization_context=getattr(g, "authorization_context", None),
+ )
if retry_for:
from core.backend_failure_retry import reserve_retry
@@ -12252,9 +12360,25 @@ async def sessions_messages_create(session_id: str):
message = _persist_user_row()
except RetryUnavailable as error:
return _coded_error_response(error.code, error.code, 409)
+ except workbench_sessions_service.SessionArchivedError:
+ return _session_archived_response()
+ except workbench_sessions_service.SessionBackendLockedError as err:
+ return _backend_locked_response(err)
+ except (ValueError, LookupError) as err:
+ if continue_agent is None:
+ raise
+ return jsonify({"error": str(err)}), 400
+ except PermissionError as err:
+ if continue_agent is None:
+ raise
+ return jsonify({"error": str(err)}), 403
if message is None:
# Archived between the pre-flight check and the reservation — stay terminal.
return _session_archived_response()
+ if switched.get("session") is not None:
+ from vibe.sse_broker import broker
+
+ _publish_session_update_activity(broker, session_id=session_id, session=switched["session"])
if retry_for:
# Retained pre-write input comes from its immutable Delivery, including
# attachments. The controller independently reconstructs the same input.