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): let a bound session switch backend with a handoff (#2916)

Call Whiteaf3937cc1b68
diff --git a/config/v2_sessions.py b/config/v2_sessions.py
index d152ce308..29ba8dd3e 100644
--- a/config/v2_sessions.py
+++ b/config/v2_sessions.py
@@ -470,6 +470,10 @@ class SessionsStore:
expected_route=expected_route,
)
+ def get_agent_session_by_id(self, session_id: str) -> Optional[dict]:
+ self._ensure_service()
+ return self._service.get_agent_session_by_id(session_id)
+
def get_agent_session_runtime_marker(
self,
session_id: str,
diff --git a/core/agent_input.py b/core/agent_input.py
index 1ed159a59..cde6b3fb5 100644
--- a/core/agent_input.py
+++ b/core/agent_input.py
@@ -144,9 +144,12 @@ class AgentInputMetadata:
user_id: str | None = None
user_name: str | None = None
harness_source: str | None = None
+ #: The block the first turn after a backend switch carries ahead of everything else
+ #: (``core/session_handoff.py``); it is context for the model, not part of the input.
+ handoff: str | None = None
def render(self, text: str, config: Any, *, now: datetime | None = None) -> str:
- lines: list[str] = []
+ lines: list[str] = [self.handoff.rstrip() + "\n"] if self.handoff and self.handoff.strip() else []
if self.harness_source:
lines.append(f"{HARNESS_MARKER} {self.harness_source}]")
if getattr(config, "include_time_info", True):
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 76870510c..bd56f76e4 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -1,7 +1,9 @@
"""Message routing and Agent communication handlers"""
+import asyncio
import logging
import inspect
+from dataclasses import replace
from typing import Any, List, Optional, Tuple
from core.audio_asr import (
@@ -13,6 +15,7 @@ from core.agent_input import AgentInputMetadata, harness_label
from core.backend_failure import emit_backend_failure
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
from core.message_context import (
resolve_context_platform,
resolve_context_thread_id,
@@ -816,6 +819,7 @@ class MessageHandler(BaseHandler):
)
if processing_indicator is not None:
self.controller.processing_indicator.apply_to_request(request, processing_indicator)
+ await self._attach_backend_handoff(context, agent_name, request)
try:
await self.controller.agent_service.handle_message(agent_name, request)
agent_dispatched = True
@@ -1379,6 +1383,66 @@ class MessageHandler(BaseHandler):
spec[HARNESS_PROMPT_ECHO_SPEC_KEY] = message
context.platform_specific = spec
+ async def _attach_backend_handoff(
+ self, context: MessageContext, backend: str, request: AgentRequest
+ ) -> None:
+ """Prepare a turn of a Session that switched backend and has not continued yet.
+
+ The switch cleared the row's native and left ``backend_handoff``
+ (``docs/plans/2026-10-22-session-backend-switch.md``). The row is read by
+ primary key, whichever projection selected it (a Workbench target or an
+ IM/CLI run target), because a projection can predate the switch. A turn that
+ continues the Session's own conversation on the switched-to backend then:
+
+ - drops any runtime that backend still caches for the Session from an earlier
+ phase, while the row has no native yet, and stops every projection from
+ offering a native the row no longer holds;
+ - carries the handoff in its input, and is tagged so its native-start receipt
+ can spend the marker.
+
+ A turn into a namespaced conversation (a subagent) or on another backend (a
+ one-off Agent run) neither carries nor spends it. Any failure fails the turn
+ before dispatch, so the next turn retries; the first accepted turn on the new
+ native is always one that carried the handoff.
+ """
+ from core.agent_session_context import resolve_context_agent_session_target
+ from core.session_handoff import load_pending_handoff, pending_handoff_for_row
+
+ spec = context.platform_specific or {}
+ if spec.get("vibey_resume") is True:
+ return
+ # The same marks the backends namespace a conversation by: a Claude/Codex
+ # subagent base (set above) or a routing-default subagent.
+ if spec.get("backend_base_session_id") or spec.get("routing_subagent"):
+ return
+ target = resolve_context_agent_session_target(context) or {}
+ session_id = str(target.get("id") or spec.get("agent_session_id") or "").strip()
+ if not session_id:
+ return
+ read_row = getattr(self.sessions, "get_agent_session_by_id", None)
+ if not callable(read_row):
+ return
+ row = await asyncio.to_thread(read_row, session_id)
+ handoff = pending_handoff_for_row(row, backend)
+ if handoff is None:
+ return
+ pending = await asyncio.to_thread(load_pending_handoff, row, handoff, backend)
+ spec = dict(context.platform_specific or {})
+ for key in ("agent_session_target", "agent_run_target"):
+ projection = spec.get(key)
+ if isinstance(projection, dict) and projection.get("native_session_id") != pending.native_session_id:
+ spec[key] = {**projection, "native_session_id": pending.native_session_id}
+ context.platform_specific = spec
+ if not pending.native_session_id:
+ agent = getattr(getattr(self.controller, "agent_service", None), "agents", {}).get(backend)
+ release = getattr(agent, "release_native_runtime", None)
+ if callable(release):
+ await release(request)
+ request.input_metadata = replace(request.input_metadata or AgentInputMetadata(), handoff=pending.text)
+ spec = dict(context.platform_specific or {})
+ spec[BACKEND_HANDOFF_TURN_KEY] = pending.handoff_id
+ context.platform_specific = spec
+
async def prepare_input_metadata(
self, context: MessageContext, *, human: bool
) -> AgentInputMetadata:
diff --git a/core/services/sessions.py b/core/services/sessions.py
index 24f86df6e..9416dc9d3 100644
--- a/core/services/sessions.py
+++ b/core/services/sessions.py
@@ -49,6 +49,7 @@ from storage.workbench_sessions_service import (
get_active_session,
get_session,
is_session_archived,
+ latest_session_turn_id,
list_sessions,
list_sessions_page,
require_enabled_agent_backend,
@@ -76,6 +77,7 @@ __all__ = [
"get_active_session",
"get_session",
"is_session_archived",
+ "latest_session_turn_id",
"list_sessions",
"list_sessions_page",
"require_session_chat_access",
diff --git a/core/session_handoff.py b/core/session_handoff.py
new file mode 100644
index 000000000..9e4139675
--- /dev/null
+++ b/core/session_handoff.py
@@ -0,0 +1,251 @@
+"""The handoff a session's first turn on a new backend carries.
+
+A bound session that switches backend keeps its Avibe session id and transcript,
+but the new backend starts a fresh native conversation
+(``docs/plans/2026-10-22-session-backend-switch.md``). The switch leaves a
+``backend_handoff`` marker on the session; until the new backend has both accepted
+a turn carrying it and bound its native, each turn of that conversation is prefixed
+with this block (``AgentInputMetadata.handoff``).
+
+The block is mechanical and bounded: a continuity notice, the open Harness work
+bound to the session, the most recent transcript that fits the budget, and a
+runnable query for the rest. It reads only durable state, so a retried turn builds
+it again from what is true then.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from typing import Any, Mapping, Sequence
+
+from sqlalchemy.engine import Connection
+
+from modules.agents.catalog import display_name_for_backend
+
+#: ``platform_specific`` key naming the handoff a turn carries; its native-start
+#: receipt accepts exactly that marker (``SessionTurnManager.on_native_start``).
+BACKEND_HANDOFF_TURN_KEY = "backend_handoff_id"
+
+#: The whole block, in characters. Each transcript message is clipped first.
+HANDOFF_BUDGET_CHARS = 16_000
+_MESSAGE_CLIP_CHARS = 1_500
+_TRANSCRIPT_FETCH_LIMIT = 60
+_OPEN_WORK_LIMIT = 12
+
+#: Message types that carry the conversation, and how the block labels them.
+_TRANSCRIPT_LABELS = {
+ "user": "User",
+ "harness": "Harness input",
+ "annotation": "Show Page annotation",
+ "output": "Assistant",
+ "interim": "Assistant",
+ "result": "Assistant",
+ "error": "Error",
+}
+_OPEN_WORK_LABELS = {
+ "agent_run": "Delegated run",
+ "watch": "Watch",
+ "task": "Task",
+}
+#: An id the example query can quote as it is, in SQL and in the shell.
+_PLAIN_ID = re.compile(r"[A-Za-z0-9_-]+")
+
+
+@dataclass(frozen=True)
+class PendingHandoff:
+ """A session's pending switch handoff, read fresh from its row at dispatch."""
+
+ handoff_id: str
+ #: The row's native as it is now: empty until the new backend binds one.
+ native_session_id: str
+ text: str
+
+
+def pending_handoff_for_row(row: Any, backend: str) -> dict[str, Any] | None:
+ """The handoff a turn on ``backend`` owes, from the session row read at dispatch.
+
+ Read by primary key, not from a routing projection: a Delivery admitted before
+ the switch, or an IM run target, can carry a copy from before it. Only the
+ backend the session switched to carries it; a turn routed to another backend
+ (a one-off Agent run) is not continuing this conversation.
+ """
+
+ from storage.agent_session_rows import decode_metadata_object, pending_backend_handoff
+
+ if not isinstance(row, Mapping) or str(row.get("agent_backend") or "") != str(backend or ""):
+ return None
+ return pending_backend_handoff(decode_metadata_object(row.get("metadata_json")))
+
+
+def load_pending_handoff(row: Mapping[str, Any], handoff: Mapping[str, Any], backend: str) -> PendingHandoff:
+ """Build the block for ``handoff`` on its own read connection. Blocking."""
+
+ from storage.agent_session_rows import decode_session_value
+ from storage.db import get_cached_sqlite_engine
+
+ session_id = str(row.get("id") or "")
+ with get_cached_sqlite_engine().connect() as conn:
+ text = build_backend_handoff(conn, session_id, handoff, to_backend=backend)
+ return PendingHandoff(
+ handoff_id=str(handoff["id"]),
+ native_session_id=str(decode_session_value(row.get("native_session_id")) or "").strip(),
+ text=text,
+ )
+
+
+def build_backend_handoff(
+ conn: Connection,
+ session_id: str,
+ handoff: Mapping[str, str],
+ *,
+ to_backend: str,
+) -> str:
+ """Render the handoff for ``session_id`` from the store as it is now."""
+
+ from storage.messages_service import list_session_messages
+ from storage.workbench_sessions_service import derive_session_harness_activities
+
+ page = list_session_messages(
+ conn,
+ session_id=session_id,
+ types=tuple(_TRANSCRIPT_LABELS),
+ tail=True,
+ limit=_TRANSCRIPT_FETCH_LIMIT,
+ )
+ open_work = derive_session_harness_activities(conn, session_id)
+ return render_backend_handoff(
+ session_id,
+ handoff,
+ to_backend=to_backend,
+ messages=page.get("messages") or [],
+ has_older=bool(page.get("next_before_id")),
+ open_work=open_work,
+ )
+
+
+def render_backend_handoff(
+ session_id: str,
+ handoff: Mapping[str, str],
+ *,
+ to_backend: str,
+ messages: Sequence[Mapping[str, Any]],
+ has_older: bool,
+ open_work: Sequence[Mapping[str, Any]],
+ budget: int = HANDOFF_BUDGET_CHARS,
+) -> str:
+ """The block itself: a pure function of what ``build_backend_handoff`` read."""
+
+ from_backend = str(handoff.get("from_backend") or "")
+ from_label = display_name_for_backend(from_backend) if from_backend else "another"
+ to_label = display_name_for_backend(to_backend) if to_backend else "a new"
+ head = [
+ "[Avibe handoff]",
+ (
+ f"This continues Avibe session `{session_id}`. It ran on the {from_label} backend until the user"
+ f" switched it to {to_label}, so you start without that backend's context. The working directory,"
+ " its files, and everything Avibe holds for this session (Watches, Tasks, delegated runs) are unchanged."
+ ),
+ (
+ "Continue the work from the record below. Tool calls and their outputs from before the switch are not"
+ " in it; read files or re-run commands when you need them."
+ ),
+ ]
+ query = _history_query(session_id)
+ tail = ["[End of Avibe handoff]"]
+ if query:
+ tail.insert(0, f"The full conversation is in Avibe's messages table. For example:\n{query}")
+
+ remaining = budget - _size(head) - _size(tail)
+ work_lines = _open_work_lines(open_work)
+ if work_lines and remaining > 0:
+ work_block = _fit(["Open work bound to this session:", *work_lines], remaining)
+ remaining -= _size(work_block)
+ else:
+ work_block = []
+
+ transcript = _transcript_lines(messages, remaining - len("Recent conversation, oldest first:") - 2)
+ if transcript:
+ omitted = has_older or len(transcript) < len(messages)
+ transcript_block = [
+ "Recent conversation, oldest first" + (" (earlier messages omitted):" if omitted else ":"),
+ *transcript,
+ ]
+ else:
+ transcript_block = []
+ return "\n\n".join(
+ "\n".join(block) for block in (head, work_block, transcript_block, tail) if block
+ )
+
+
+def _history_query(session_id: str) -> str | None:
+ if _PLAIN_ID.fullmatch(session_id) is None:
+ return None
+ sql = (
+ "SELECT created_at, type, substr(content_text,1,2000) FROM messages"
+ f" WHERE session_id='{session_id}' ORDER BY created_at, id LIMIT 50 OFFSET 0"
+ )
+ return f'vibe data query --sql "{sql}"'
+
+
+def _open_work_lines(items: Sequence[Mapping[str, Any]]) -> list[str]:
+ lines: list[str] = []
+ seen: set[tuple[str, str]] = set()
+ for item in items:
+ kind = str(item.get("item_kind") or item.get("kind") or "")
+ item_id = str(item.get("id") or "")
+ if (kind, item_id) in seen:
+ continue
+ seen.add((kind, item_id))
+ label = _one_line(str(item.get("label") or item.get("description") or ""), 160)
+ status = str(item.get("status") or "")
+ parts = [_OPEN_WORK_LABELS.get(kind, kind or "Item"), item_id]
+ if status:
+ parts.append(f"({status})")
+ line = "- " + " ".join(part for part in parts if part)
+ lines.append(f"{line}: {label}" if label else line)
+ if len(lines) > _OPEN_WORK_LIMIT:
+ omitted = len(lines) - _OPEN_WORK_LIMIT
+ lines = lines[:_OPEN_WORK_LIMIT] + [f"- ... {omitted} more; see `vibe watch list`, `vibe task list`, `vibe runs list`."]
+ return lines
+
+
+def _transcript_lines(messages: Sequence[Mapping[str, Any]], budget: int) -> list[str]:
+ """The newest messages that fit ``budget``, returned oldest first."""
+
+ picked: list[str] = []
+ used = 0
+ for message in reversed(messages):
+ text = str(message.get("text") or "").strip()
+ if not text:
+ continue
+ label = _TRANSCRIPT_LABELS.get(str(message.get("type") or ""), "Message")
+ when = str(message.get("created_at") or "")[:19].replace("T", " ")
+ clipped = text if len(text) <= _MESSAGE_CLIP_CHARS else text[:_MESSAGE_CLIP_CHARS] + " [...]"
+ entry = f"[{label}{' ' + when if when else ''}]\n{clipped}"
+ if used + len(entry) + 1 > budget:
+ break
+ picked.append(entry)
+ used += len(entry) + 1
+ picked.reverse()
+ return picked
+
+
+def _fit(lines: list[str], budget: int) -> list[str]:
+ kept: list[str] = []
+ used = 0
+ for line in lines:
+ if used + len(line) + 1 > budget:
+ break
+ kept.append(line)
+ used += len(line) + 1
+ return kept if len(kept) > 1 else []
+
+
+def _one_line(value: str, limit: int) -> str:
+ text = " ".join(value.split())
+ return text if len(text) <= limit else text[: limit - 3] + "..."
+
+
+def _size(lines: Sequence[str]) -> int:
+ return sum(len(line) + 1 for line in lines) + 2
diff --git a/core/session_turns.py b/core/session_turns.py
index 7d81afa47..de47ce01e 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -57,6 +57,7 @@ from core.run_settlement import (
)
from core.processing_indicator import INTERRUPTED_REACTION_EMOJI
from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turn_with_outcome
+from core.session_handoff import BACKEND_HANDOFF_TURN_KEY
from core.services.agent_steering import (
SteerOutcome,
SteerReconcileRequest,
@@ -70,7 +71,7 @@ from core.services.agent_steering import (
from storage import loop_writers, messages_service
from storage import message_deliveries as delivery_store
from storage.agent_transcript import last_response, recovered_watch_ids
-from storage.agent_session_rows import reserve_write_lock
+from storage.agent_session_rows import accept_backend_handoff, decode_session_value, reserve_write_lock
from storage.db import get_cached_sqlite_engine
from storage.background import (
OWED_FAILURE_NOTICE_KEY,
@@ -1436,6 +1437,10 @@ class SessionTurnManager:
context.platform_specific = spec
return context
+ @staticmethod
+ def _binding_native(binding: dict[str, Any]) -> str:
+ return str(decode_session_value(binding.get("native_session_id")) or "").strip()
+
@staticmethod
def _binding_metadata(binding: dict[str, Any]) -> dict[str, Any]:
raw_metadata = binding.get("metadata_json")
@@ -1555,6 +1560,15 @@ class SessionTurnManager:
return True
if "metadata" in projection and projection.get("metadata") != SessionTurnManager._binding_metadata(binding):
return True
+ # A Delivery admitted before a backend switch still carries the native
+ # the switch replaced; resuming it on the new backend would fail.
+ if (
+ "native_session_id" in projection
+ and "native_session_id" in binding
+ and str(projection.get("native_session_id") or "").strip()
+ != SessionTurnManager._binding_native(binding)
+ ):
+ return True
return False
session_target = spec.get("agent_session_target")
@@ -1620,6 +1634,8 @@ class SessionTurnManager:
"metadata": SessionTurnManager._binding_metadata(binding),
}
)
+ if "native_session_id" in binding:
+ target["native_session_id"] = SessionTurnManager._binding_native(binding)
spec["agent_session_target"] = target
# Keep every routing projection on the same durable winner. MessageHandler
# and Controller prefer these cached fields over agent_session_target, so
@@ -1653,6 +1669,8 @@ class SessionTurnManager:
"reasoning_effort": binding.get("reasoning_effort"),
}
)
+ if "native_session_id" in binding:
+ run_target["native_session_id"] = SessionTurnManager._binding_native(binding)
spec["agent_run_target"] = run_target
context.platform_specific = spec
@@ -1666,6 +1684,7 @@ class SessionTurnManager:
agent_sessions.c.agent_variant,
agent_sessions.c.model,
agent_sessions.c.reasoning_effort,
+ agent_sessions.c.native_session_id,
agent_sessions.c.metadata_json,
agent_sessions.c.status,
)
@@ -6048,6 +6067,14 @@ class SessionTurnManager:
execution=execution,
)
materialized: list[dict[str, Any]] = []
+ handoff_id = str(
+ (getattr(context, "platform_specific", None) or {}).get(BACKEND_HANDOFF_TURN_KEY) or ""
+ ).strip()
+ if bound is not None and handoff_id:
+ # The new backend accepted the turn that carried the switch
+ # handoff; once the row also holds its native, later turns
+ # continue that conversation without one.
+ accept_backend_handoff(conn, session_id, handoff_id)
if bound is not None:
materialized = delivery_store.materialize_start_acceptance(
conn,
diff --git a/docs/plans/2026-10-01-session-context-rotation.md b/docs/plans/2026-10-01-session-context-rotation.md
index 492c56250..f6dc829fa 100644
--- a/docs/plans/2026-10-01-session-context-rotation.md
+++ b/docs/plans/2026-10-01-session-context-rotation.md
@@ -397,7 +397,8 @@ continuity but does not fail dispatch.
- Self-heal when the native resume target is gone (Claude/Codex currently fail
the turn) for sessions with rotation enabled.
- Backend switch on a bound session through rotation instead of
- `SessionBackendLockedError`.
+ `SessionBackendLockedError` (done without the rotation triggers:
+ `docs/plans/2026-10-22-session-backend-switch.md`).
- OpenCode context usage.
- Agent-authored handoff note.
diff --git a/docs/plans/2026-10-22-session-backend-switch.md b/docs/plans/2026-10-22-session-backend-switch.md
new file mode 100644
index 000000000..1ea473544
--- /dev/null
+++ b/docs/plans/2026-10-22-session-backend-switch.md
@@ -0,0 +1,145 @@
+# Session Backend Switch
+
+Status: implemented (2026-10-22)
+
+## Background
+
+A session that already has a backend-native conversation cannot change backend
+(`SessionBackendLockedError`). The lock exists because a native session can only
+be resumed by the backend that created it; switching the backend while the row
+still held the old native made the new backend fail on a foreign id.
+
+The main reason to lift it is to let people move existing sessions onto Vibey.
+
+## Goal
+
+- A bound session on Claude Code, Codex, or OpenCode can switch to any enabled
+ Agent, including Vibey and the other native backends.
+- A bound Vibey session stays on the Vibey backend. Agents within the Vibey
+ backend remain switchable, as before.
+- The Avibe session id, transcript, deliveries, Harness callbacks, Watches,
+ Tasks, and the Workbench URL do not change. Only the backend-native context
+ underneath is replaced.
+- The first turn on the new backend receives a bounded handoff so the work
+ continues.
+
+This is the backend-switch follow-up of
+`docs/plans/2026-10-01-session-context-rotation.md`, without that plan's
+context-pressure triggers or automatic policy.
+
+## Rules
+
+A cross-backend change on a session with a bound native is accepted only when:
+
+- the current backend is not `vibey`;
+- no durable Turn of the session is unsettled, the row is not `running`, and it
+ is not a pending fork. The Turn row is written by the controller under the
+ same SQLite write lock before anything is dispatched, so it is the reservation
+ the switch commits against; `agent_status` and the controller's in-memory
+ registry both lag it;
+- the controller is reachable and reports no backend Activity and no unclaimed
+ Activity output for the session. A detached Claude Activity runs on the old
+ client and would otherwise keep producing output for a session that moved.
+ That answer is a point-in-time read, so the caller first reads the session's
+ newest durable Turn id and the switch commits only if it is still the newest
+ (`update_session(runtime_idle_through_turn=...)`). Every Activity starts in a
+ turn, and every turn writes its row before dispatch, so an unchanged watermark
+ means the controller's answer still holds at commit;
+- the request selects an Agent on the new backend. The Agent identity routes the
+ next turn ahead of `agent_backend`, so a backend-only edit is refused (`400`).
+
+Refusals stay retryable `409`s: `backend_locked` (running or unsettled Turn,
+pending fork, bound Vibey) and `backend_busy` (background backend work,
+controller unreachable).
+
+Unbound sessions keep today's behavior.
+
+## Design
+
+### Switch (storage, one transaction)
+
+`update_session` takes the bound-switch branch:
+
+1. Snapshot the current binding as an inert archived row
+ (`<anchor>:superseded:<id>`), the shape `replace_agent_session_native`
+ already writes. The insertion is shared by both callers.
+2. Clear `native_session_id` and apply the new Agent route.
+3. Record `metadata_json.backend_handoff = {id, from_backend, from_native,
+ to_backend, switched_at}`.
+
+The UPDATE re-asserts the state the decision was made from: same native, same
+backend, not running, no unsettled Turn, the same newest Turn, not archived.
+
+A forked session's spent fork source (`fork_source_native_session_id`,
+`fork_source_backend`) is dropped by the switch, so the emptied native cannot
+re-arm a native fork or pin the picker to the fork's backend.
+
+### While the handoff is pending
+
+- `bind_agent_session_by_id` refuses a bind of `from_native`, or from any
+ backend other than the row's. A late event from the old runtime or a one-off
+ Agent run on another backend cannot rebind or relabel the switched row.
+- The durable binding refresh carries the row's `native_session_id` into the
+ routing projections, so a Delivery admitted before the switch cannot offer
+ the replaced native to the new backend's resume helpers.
+
+### First turn on the new backend (controller)
+
+At dispatch, `MessageHandler` reads the session row by primary key, whichever
+projection selected it (Workbench target or IM/CLI run target). A turn that
+continues the session's own conversation on the switched-to backend (not a
+namespaced subagent, not a one-off run on another backend):
+
+1. If the row has no native yet, releases any runtime the target backend still
+ caches for this session (`BaseAgent.release_native_runtime`): Claude ends its
+ SDK client, Codex releases its thread binding. This covers A -> B -> A.
+2. Carries the handoff in `AgentInputMetadata.handoff`, which every backend
+ renders at its last write boundary. The canonical Message keeps the user's
+ text.
+3. Is tagged with the handoff id.
+
+Any failure there fails the turn before dispatch; the next turn retries.
+
+The marker is spent once both facts hold, in either order: a tagged turn's
+native-start receipt (`accept_backend_handoff`, in the receipt transaction) and
+the row bound to the new native (`settle_backend_handoff_on_bind`, in the bind
+transaction). Claude reports acceptance before its init binds the id; Vibey,
+Codex and OpenCode bind first. A native bound before any tagged turn was
+accepted (a Codex thread whose `turn/start` failed) keeps the marker, so the
+next turn still carries the handoff.
+
+### Handoff content
+
+One bounded block, rendered in English for the model:
+
+1. Continuity notice: Avibe session id, previous backend, fresh context.
+2. Open Harness work bound to the session (delegated runs, Watches, Tasks), from
+ `derive_session_harness_activities`, truncated with an omitted count.
+3. Recent transcript tail, newest first until the character budget is spent,
+ then shown in order. Each message is clipped.
+4. A runnable `vibe data query` for the full history.
+
+## Known by design
+
+- The handoff is lossy: tool calls, file reads, and reasoning of the old backend
+ are not carried. The workspace on disk is shared, and the full transcript is
+ queryable.
+- An idle runtime left on the old backend is reclaimed by that backend's idle
+ eviction. It is idle by the switch rule and cannot rebind the row.
+- Legacy non-durable turns do not record a native-start receipt; on that path
+ the handoff can be sent again on the next turn.
+- A namespaced subagent turn after a switch starts its own conversation without
+ the handoff; the session's own conversation still receives it.
+
+## Todo
+
+- [x] Plan
+- [x] Storage: shared snapshot insert, bound-switch branch, Vibey lock
+- [x] Stale bind guard
+- [x] Handoff builder and `AgentInputMetadata.handoff`
+- [x] Dispatch: release, inject, tag; receipt clears the marker
+- [x] `release_native_runtime` for Claude and Codex
+- [x] PATCH preflight (`backend_busy`)
+- [x] Chat header picker rule and error copy
+- [x] Tests
+- [ ] Public docs (avibe-docs, en and zh)
diff --git a/modules/agents/base.py b/modules/agents/base.py
index 7aa3bc503..6d645b5e8 100644
--- a/modules/agents/base.py
+++ b/modules/agents/base.py
@@ -172,6 +172,19 @@ class BaseAgent(ABC):
return None
+ async def release_native_runtime(self, request: AgentRequest) -> None:
+ """Drop any runtime this backend still holds for the request's Session.
+
+ Called before the first turn after the Session switched to this backend
+ while its row has no native yet (``core/session_handoff.py``). A runtime
+ still cached from an earlier phase on this backend holds the conversation
+ the switch replaced, so the turn must not reuse it. No turn of the Session
+ is running. Must be idempotent and cheap when nothing is cached; a
+ backend that keeps no per-Session state outside the row needs nothing.
+ """
+
+ return None
+
def backend_alive(self, context: Any) -> Optional[bool]:
"""Best-effort liveness of this backend for the given turn context.
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index 86592a04e..d814024cf 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -2081,6 +2081,16 @@ class ClaudeAgent(BaseAgent):
return True
+ async def release_native_runtime(self, request: AgentRequest) -> None:
+ """End the SDK client an earlier Claude phase of this Session left cached.
+
+ A cached client is reused before the row is consulted, and it still holds
+ the conversation the backend switch replaced.
+ """
+ composite_key = self.runtime_turn_key(request)
+ if composite_key and composite_key in self.claude_sessions:
+ await self.end_runtime_session(composite_key)
+
async def end_runtime_session(self, composite_key: str) -> bool:
"""Interrupt and clean up one runtime without racing native steering."""
async with self._steering_lock(composite_key):
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index 4040d928f..8baf5a00f 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -1429,6 +1429,19 @@ class CodexAgent(BaseAgent):
return
await self._release_session_thread(generation, base_session_id)
+ async def release_native_runtime(self, request: AgentRequest) -> None:
+ """Unload the thread an earlier Codex phase of this Session left bound.
+
+ Without it the in-memory thread mapping, consulted before the row, would
+ resume the conversation the backend switch replaced.
+ """
+ payload = getattr(request.context, "platform_specific", None) or {}
+ base_session_id = str(payload.get("backend_base_session_id") or request.base_session_id or "")
+ if not base_session_id:
+ return
+ async with self.session_lifecycle(base_session_id):
+ await self.release_session_runtime(base_session_id)
+
async def end_session(self, base_session_id: str) -> dict[str, bool]:
"""End one Session's live runtime, for End in Running Agents.
diff --git a/modules/sessions_facade.py b/modules/sessions_facade.py
index cbd7afff4..c409f3b98 100644
--- a/modules/sessions_facade.py
+++ b/modules/sessions_facade.py
@@ -122,6 +122,13 @@ class SessionsFacade:
expected_route=expected_route,
)
+ def get_agent_session_by_id(self, agent_session_id: str) -> Optional[dict]:
+ """The persisted ``agent_sessions`` row, read by primary key."""
+ getter = getattr(self.sessions_store, "get_agent_session_by_id", None)
+ if not callable(getter):
+ return None
+ return getter(agent_session_id)
+
def get_agent_session_runtime_marker(
self,
agent_session_id: str,
diff --git a/storage/agent_session_rows.py b/storage/agent_session_rows.py
index 485c08535..08b583f71 100644
--- a/storage/agent_session_rows.py
+++ b/storage/agent_session_rows.py
@@ -6,7 +6,7 @@ import os
import secrets
from datetime import datetime, timezone
from pathlib import Path
-from typing import Any
+from typing import Any, Mapping
from sqlalchemy import Connection, func, select, update
@@ -639,6 +639,149 @@ SUPERSEDED_ANCHOR_MARKER = "superseded"
SUPERSEDED_ANCHOR_INFIX = f":{SUPERSEDED_ANCHOR_MARKER}:"
+def insert_superseded_native_snapshot(
+ conn: Connection,
+ row: Mapping[str, Any],
+ *,
+ now: str,
+ binding: Mapping[str, Any],
+) -> str:
+ """Keep a session's current native binding as an inert archived row.
+
+ ``row`` is the full active ``agent_sessions`` row. The snapshot copies it under
+ a fresh id, an anchor suffixed with ``SUPERSEDED_ANCHOR_INFIX``, archived and
+ background, so it never appears in session lists or anchor lookups while the
+ replaced native id stays on record. ``binding`` is stored as the snapshot's
+ ``superseded_native_binding`` metadata. The caller holds the write lock and
+ then replaces the active row's binding in the same transaction.
+ """
+
+ snapshot_id = new_session_id(conn)
+ anchor = str(row["session_anchor"] or "")
+ metadata_value = decode_metadata_object(row["metadata_json"])
+ metadata_value["superseded_native_binding"] = dict(binding)
+ snapshot = dict(row)
+ snapshot.update(
+ {
+ "id": snapshot_id,
+ "session_anchor": f"{anchor}{SUPERSEDED_ANCHOR_INFIX}{snapshot_id}",
+ "status": "archived",
+ "visibility": "background",
+ "pinned": 0,
+ "agent_status": "idle",
+ "composer_draft_text": None,
+ "composer_draft_updated_at": None,
+ "metadata_json": json.dumps(metadata_value, separators=(",", ":"), ensure_ascii=False),
+ "updated_at": now,
+ }
+ )
+ conn.execute(agent_sessions.insert().values(**snapshot))
+ return snapshot_id
+
+
+#: The backend a bound session can switch to but never away from
+#: (``docs/plans/2026-10-22-session-backend-switch.md``).
+TERMINAL_SWITCH_BACKEND = "vibey"
+
+#: ``metadata_json`` key a cross-backend switch leaves on the active row. It names the
+#: binding the switch replaced and stays until BOTH a turn that carried the handoff was
+#: accepted by the new backend (its native-start receipt) AND the row is bound to the
+#: new backend's native. Either can come first: Claude reports acceptance before its
+#: init message binds the id, while Vibey, Codex and OpenCode bind before accepting.
+#: While it stays, a bind of the replaced native or from another backend is refused.
+BACKEND_HANDOFF_METADATA_KEY = "backend_handoff"
+_BACKEND_HANDOFF_FIELDS = ("id", "from_backend", "from_native", "to_backend", "switched_at")
+
+
+def pending_backend_handoff(metadata: Any) -> dict[str, Any] | None:
+ """The pending switch handoff in a session's metadata, or None.
+
+ A value without a non-empty string ``id`` (malformed, or a shape this release
+ does not know) reads as absent, so it can never fail a turn or a bind.
+ ``accepted`` records that a turn carrying it reached the new native.
+ """
+
+ value = metadata.get(BACKEND_HANDOFF_METADATA_KEY) if isinstance(metadata, Mapping) else None
+ if not isinstance(value, Mapping):
+ return None
+ handoff_id = value.get("id")
+ if not isinstance(handoff_id, str) or not handoff_id.strip():
+ return None
+ pending: dict[str, Any] = {name: str(value.get(name) or "") for name in _BACKEND_HANDOFF_FIELDS}
+ pending["accepted"] = value.get("accepted") is True
+ return pending
+
+
+def accept_backend_handoff(conn: Connection, session_id: str, handoff_id: str) -> bool:
+ """Record that a turn carrying ``handoff_id`` was accepted by the new backend.
+
+ The marker is spent here when the row already holds the new native (Vibey,
+ Codex and OpenCode bind before they accept); otherwise it is flagged accepted
+ and the bind spends it (``settle_backend_handoff_on_bind``). Compare-and-set on
+ the id, so a late receipt cannot touch a newer switch. The caller holds the
+ write lock; other metadata keys are kept. Returns whether it changed anything.
+ """
+
+ row = conn.execute(
+ select(agent_sessions.c.metadata_json, agent_sessions.c.native_session_id).where(
+ agent_sessions.c.id == str(session_id)
+ )
+ ).first()
+ if row is None:
+ return False
+ metadata = decode_metadata_object(row[0])
+ pending = pending_backend_handoff(metadata)
+ if pending is None or pending["id"] != str(handoff_id):
+ return False
+ native = str(row[1] or "")
+ if native and native != pending["from_native"]:
+ metadata.pop(BACKEND_HANDOFF_METADATA_KEY, None)
+ else:
+ metadata[BACKEND_HANDOFF_METADATA_KEY] = {**metadata[BACKEND_HANDOFF_METADATA_KEY], "accepted": True}
+ _write_session_metadata(conn, session_id, metadata)
+ return True
+
+
+def settle_backend_handoff_on_bind(conn: Connection, session_id: str, native_session_id: str) -> bool:
+ """Spend an accepted handoff once the row is bound to the new backend's native.
+
+ Called inside the transaction whose first-bind UPDATE already holds the write
+ lock. A handoff not yet accepted stays, so a native bound before its first turn
+ was accepted (a Codex thread whose ``turn/start`` then failed) still gets it.
+ """
+
+ raw = conn.execute(
+ select(agent_sessions.c.metadata_json).where(agent_sessions.c.id == str(session_id))
+ ).scalar_one_or_none()
+ metadata = decode_metadata_object(raw)
+ pending = pending_backend_handoff(metadata)
+ if pending is None or not pending["accepted"] or str(native_session_id or "") in {"", pending["from_native"]}:
+ return False
+ metadata.pop(BACKEND_HANDOFF_METADATA_KEY, None)
+ _write_session_metadata(conn, session_id, metadata)
+ return True
+
+
+def _write_session_metadata(conn: Connection, session_id: str, metadata: Mapping[str, Any]) -> None:
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == str(session_id))
+ .values(metadata_json=json.dumps(metadata, separators=(",", ":"), ensure_ascii=False))
+ )
+
+
+def decode_metadata_object(raw: Any) -> dict[str, Any]:
+ """An ``agent_sessions.metadata_json`` value as a dict; anything else reads as empty."""
+
+ if isinstance(raw, dict):
+ return dict(raw)
+ try:
+ value = json.loads(raw) if raw else {}
+ except (TypeError, ValueError):
+ return {}
+ return value if isinstance(value, dict) else {}
+
+
def unchanged_text(column: Any, value: Any) -> Any:
"""Predicate re-asserting that a TEXT column still holds what a read observed.
diff --git a/storage/sessions_service.py b/storage/sessions_service.py
index 60cf96d49..c98aaf59f 100644
--- a/storage/sessions_service.py
+++ b/storage/sessions_service.py
@@ -24,8 +24,11 @@ from storage.agent_session_rows import (
decode_session_value,
encode_session_value,
get_or_create_agent_session_row,
+ insert_superseded_native_snapshot,
new_session_id,
normalize_workdir,
+ pending_backend_handoff,
+ settle_backend_handoff_on_bind,
reserve_write_lock,
snapshot_scope_workdir,
)
@@ -1184,6 +1187,25 @@ class SQLiteSessionsService:
parsed_route_metadata = _json_loads((route_row or {}).get("metadata_json"), {})
route_metadata = parsed_route_metadata if isinstance(parsed_route_metadata, dict) else {}
already_bound = bool(decode_session_value((route_row or {}).get("native_session_id")))
+ handoff = pending_backend_handoff(route_metadata)
+ if handoff is not None and (
+ (handoff["from_native"] and handoff["from_native"] == encoded_session_id)
+ or (requested_backend and requested_backend != current_backend)
+ ):
+ # The session switched backend and the new one has not taken over
+ # yet. The replaced native is known only to the old backend's
+ # runtime, and another backend's bind (a one-off Agent run, a late
+ # event) would relabel the row: either undoes the user's switch.
+ # Keep the row as the switch left it.
+ logger.warning(
+ "Ignoring a bind into a session that is switching backend; "
+ "native=%s agent_session=%s backend=%s requested=%s",
+ native_session_id,
+ session_id,
+ current_backend,
+ requested_backend,
+ )
+ return str(session_id)
backend_changes = bool(requested_backend) and requested_backend != current_backend
if backend_changes and not already_bound:
# The three cases below are decided from a SNAPSHOT, and these reads
@@ -1288,6 +1310,9 @@ class SQLiteSessionsService:
.values(**values, native_session_id=encoded_session_id)
)
if first_bind.rowcount:
+ # The UPDATE holds the write lock, so this read-merge-write of
+ # the metadata is atomic with the bind.
+ settle_backend_handoff_on_bind(conn, str(session_id), encoded_session_id)
return str(session_id)
# LOST the first bind. Return the winner immediately, exactly as the
# cross-backend branch above does -- the two lost-race paths now
@@ -1358,37 +1383,12 @@ class SQLiteSessionsService:
if current != expected:
return None
- snapshot_id = new_session_id(conn)
- anchor = str(row["session_anchor"] or "")
- superseded_anchor = f"{anchor}{SUPERSEDED_ANCHOR_INFIX}{snapshot_id}"
- metadata_value = _json_loads(row["metadata_json"], {})
- snapshot_metadata = (
- dict(metadata_value) if isinstance(metadata_value, dict) else {}
- )
- snapshot_metadata["superseded_native_binding"] = {
- "active_session_id": str(session_id),
- "replaced_at": now,
- }
- snapshot = dict(row)
- snapshot.update(
- {
- "id": snapshot_id,
- "session_anchor": superseded_anchor,
- "status": "archived",
- "visibility": "background",
- "pinned": 0,
- "agent_status": "idle",
- "composer_draft_text": None,
- "composer_draft_updated_at": None,
- "metadata_json": json.dumps(
- snapshot_metadata,
- separators=(",", ":"),
- ensure_ascii=False,
- ),
- "updated_at": now,
- }
+ insert_superseded_native_snapshot(
+ conn,
+ row,
+ now=now,
+ binding={"active_session_id": str(session_id), "replaced_at": now},
)
- conn.execute(agent_sessions.insert().values(**snapshot))
replaced = conn.execute(
agent_sessions.update()
.where(agent_sessions.c.id == str(session_id))
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index 31e646881..9920211a1 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -16,6 +16,7 @@ from __future__ import annotations
import json
import os
+import uuid
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Mapping, Optional
@@ -32,6 +33,9 @@ from vibe.authorization import (
)
from storage.agent_session_rows import (
ASSIGNABLE_SESSION_VISIBILITIES,
+ BACKEND_HANDOFF_METADATA_KEY,
+ TERMINAL_SWITCH_BACKEND,
+ insert_superseded_native_snapshot,
SESSION_PROJECT_BASE_METADATA_KEY,
WORKSPACE_NOTICE_SESSION_ID,
create_agent_session_row,
@@ -57,6 +61,7 @@ from storage.models import (
run_definitions,
scope_settings,
scopes,
+ session_turns,
show_pages,
state_meta,
agents,
@@ -938,12 +943,13 @@ class ReservedSessionError(PermissionError):
class SessionBackendLockedError(Exception):
- """Raised when a caller tries to switch the backend of a session that already
- 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 same
- backend stays allowed."""
+ """Raised when a caller tries to change a session's backend while that is not
+ allowed: its turn is running (the in-flight turn will bind its native on the
+ current route any moment), it is a pending fork, it is a bound Vibey session
+ (Vibey is where a bound session can switch to but never away from), or a bound
+ session would be cleared to a blank backend. A bound session on another backend
+ switches by replacing its native conversation (``update_session``). Changing the
+ agent WITHIN the same backend stays allowed."""
def __init__(self, *, session_id: str, current_backend: Optional[str], requested_backend: Optional[str]):
self.session_id = session_id
@@ -988,11 +994,18 @@ def update_session(
visibility: Any = _UNSET,
pinned: Any = _UNSET,
scope_id: Any = _UNSET,
+ runtime_idle_through_turn: Optional[str] = None,
authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
user_context: Any = None,
) -> dict[str, Any]:
"""Apply a caller's edits to one session row.
+ A cross-backend change of a BOUND session replaces its native conversation and
+ requires ``runtime_idle_through_turn``: the session's ``latest_session_turn_id``
+ read BEFORE the caller confirmed with the controller that the old backend keeps
+ no background work for it. A turn created after that read could have left such
+ work, so the switch refuses unless the newest turn is still that one.
+
THE RESERVED WORKSPACE-NOTICE SESSION IS REFUSED HERE TOO, for the same reason
``archive_session`` refuses it and on the same IDENTITY test (so the answer does not
depend on whether the lazily-created row exists yet). That row is D5 rung (5)'s home
@@ -1126,9 +1139,14 @@ def update_session(
):
raise VibeAgentAccessError("Agent access is not permitted.")
- # 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. A RUNNING turn locks it too — the first turn is
+ # A bound session may change backend by REPLACING its native conversation
+ # (docs/plans/2026-10-22-session-backend-switch.md): the current binding is
+ # kept as an inert superseded snapshot, the active row's native is cleared,
+ # and a ``backend_handoff`` marker makes the new backend's first turn carry a
+ # handoff. Same Avibe session id, so the transcript, deliveries, callbacks,
+ # Watches, Tasks and URL all stay. Two bound cases stay locked: a Vibey
+ # session never leaves Vibey, and a bound row cannot be cleared to a blank
+ # (default) backend. A RUNNING turn locks every backend change — 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``
@@ -1144,17 +1162,30 @@ def update_session(
# 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 ""
- )
+ current_backend = str(existing.agent_backend or "")
+ bound_native = str(existing.native_session_id or "")
+ backend_changes = agent_backend is not _UNSET and str(agent_backend or "") != current_backend
existing_metadata = _load_metadata(existing.metadata_json)
pending_fork = bool(
existing_metadata.get("created_via") == "session_fork"
- and not str(existing.native_session_id or "")
+ and not bound_native
and str(existing_metadata.get("fork_source_backend") or "")
)
+ bound_switch = backend_changes and bool(bound_native and current_backend)
+ if bound_switch and str(agent_backend or "") and not (selector_changed and (agent_name or agent_id)):
+ # The Agent identity routes the next turn ahead of ``agent_backend``; a
+ # backend-only edit would leave the old Agent sending it to the old backend.
+ raise ValueError("A backend switch must select an Agent on the new backend")
if backend_changes and (
- (str(existing.native_session_id or "") and str(existing.agent_backend or ""))
+ (bound_switch and (current_backend == TERMINAL_SWITCH_BACKEND or not str(agent_backend or "")))
+ or (bound_switch and conn.execute(_open_turn_for_session(session_id)).first() is not None)
+ or (
+ bound_switch
+ and (
+ runtime_idle_through_turn is None
+ or latest_session_turn_id(conn, session_id) != str(runtime_idle_through_turn)
+ )
+ )
or str(existing.agent_status or "") == "running"
or pending_fork
):
@@ -1165,6 +1196,35 @@ def update_session(
)
values: dict[str, Any] = {"updated_at": _utc_now_iso()}
+ if bound_switch:
+ full_row = conn.execute(
+ select(agent_sessions).where(agent_sessions.c.id == session_id)
+ ).mappings().one()
+ insert_superseded_native_snapshot(
+ conn,
+ full_row,
+ now=values["updated_at"],
+ binding={
+ "active_session_id": str(session_id),
+ "replaced_at": values["updated_at"],
+ "reason": "backend_switch",
+ "to_backend": str(agent_backend),
+ },
+ )
+ values["native_session_id"] = ""
+ # A fork already bound its native, so its pending-fork source is spent;
+ # left on a row whose native is empty again it would re-arm the fork
+ # (or pin the picker to the fork's backend) on the next turn.
+ existing_metadata.pop("fork_source_native_session_id", None)
+ existing_metadata.pop("fork_source_backend", None)
+ existing_metadata[BACKEND_HANDOFF_METADATA_KEY] = {
+ "id": uuid.uuid4().hex,
+ "from_backend": current_backend,
+ "from_native": bound_native,
+ "to_backend": str(agent_backend),
+ "switched_at": values["updated_at"],
+ }
+ values["metadata_json"] = _dumps_metadata(existing_metadata)
if title is not _UNSET:
cleaned = str(title or "").strip()
values["title"] = cleaned or None
@@ -1279,7 +1339,23 @@ def update_session(
.where(agent_sessions.c.id == session_id)
.where(agent_sessions.c.status != "archived")
)
- if backend_changes:
+ if bound_switch:
+ # The switch was decided from this exact binding: still idle, still on
+ # the backend and native the snapshot above recorded, and no durable Turn
+ # owns the session. The Turn row is what the controller writes, under the
+ # same SQLite write lock, before it dispatches anything; ``agent_status``
+ # and the controller's in-memory registry both lag it.
+ stmt = (
+ stmt.where(func.coalesce(agent_sessions.c.agent_status, "idle") != "running")
+ .where(func.coalesce(agent_sessions.c.agent_backend, "") == current_backend)
+ .where(func.coalesce(agent_sessions.c.native_session_id, "") == bound_native)
+ .where(~_open_turn_for_session(session_id).exists())
+ .where(
+ func.coalesce(_latest_turn_for_session(session_id).scalar_subquery(), "")
+ == str(runtime_idle_through_turn)
+ )
+ )
+ elif backend_changes:
# Re-assert the lock INSIDE the UPDATE: the guard above is read-then-
# write, and a turn start / native bind can commit in between (the
# SELECT runs before this statement takes the write lock). The predicate
@@ -1329,6 +1405,38 @@ def update_session(
return get_session(conn, session_id, authorization_context=authorization)
+def _latest_turn_for_session(session_id: str):
+ return (
+ select(session_turns.c.id)
+ .where(session_turns.c.session_id == str(session_id))
+ .order_by(session_turns.c.created_at.desc(), session_turns.c.id.desc())
+ .limit(1)
+ )
+
+
+def latest_session_turn_id(conn: Connection, session_id: str) -> str:
+ """The session's newest durable Turn id, or ``""``: the watermark a bound backend
+ switch is verified against (``update_session(runtime_idle_through_turn=...)``).
+
+ Every turn, and so every background Activity a turn starts, writes a row here
+ before it dispatches; an unchanged newest id means nothing ran since the read.
+ """
+
+ return str(conn.execute(_latest_turn_for_session(session_id)).scalar_one_or_none() or "")
+
+
+def _open_turn_for_session(session_id: str):
+ """A durable Turn of the session that has not settled: one is starting, running,
+ or queued to start on the backend it was claimed for."""
+
+ return (
+ select(session_turns.c.id)
+ .where(session_turns.c.session_id == str(session_id))
+ .where(session_turns.c.state != "terminal")
+ .limit(1)
+ )
+
+
def _backend_for_agent_name(conn: Connection, agent_name: str) -> str:
cleaned = str(agent_name or "").strip()
if not cleaned:
diff --git a/tests/test_claude_receiver_result_settle.py b/tests/test_claude_receiver_result_settle.py
index 469a439e8..5cd9b360d 100644
--- a/tests/test_claude_receiver_result_settle.py
+++ b/tests/test_claude_receiver_result_settle.py
@@ -1071,6 +1071,25 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):
agent.controller.emit_agent_message.assert_awaited_once()
agent._release_service_runtime_turn.assert_called_once_with(context)
+ async def test_backend_switch_release_ends_the_client_an_earlier_phase_left(self):
+ """Claude -> other -> Claude: the cached SDK client, reused before the row is
+ read, still holds the replaced conversation, so the switched Session's first
+ turn ends it; with nothing cached the release is a no-op."""
+ agent = _build_agent([])
+ composite_key = "session-switch:/tmp/work"
+ agent.end_runtime_session = AsyncMock(return_value=True)
+ request = SimpleNamespace(
+ composite_session_id=composite_key,
+ context=SimpleNamespace(platform_specific={}),
+ )
+
+ await agent.release_native_runtime(request)
+ agent.end_runtime_session.assert_not_awaited()
+
+ agent.claude_sessions[composite_key] = object()
+ await agent.release_native_runtime(request)
+ agent.end_runtime_session.assert_awaited_once_with(composite_key)
+
async def test_end_runtime_session_serializes_with_steering_write(self):
mark_idle_calls: list[str] = []
agent = _build_agent(mark_idle_calls)
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index 1590150a6..625ac75e1 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -1254,6 +1254,26 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
# The aborted reservation leaves the generation admitting owners.
self.assertTrue(activation.commit_if_current(identity, lambda: "owner").admitted)
+ async def test_backend_switch_release_drops_the_thread_an_earlier_phase_left(self):
+ """Codex -> other -> Codex: the in-memory thread mapping, consulted before the
+ row, still names the replaced conversation, so the switched Session's first
+ turn releases it, and a live binding is released through its process."""
+ agent = init_generation_state(object.__new__(CodexAgent))
+ agent._session_locks = {}
+ agent._session_mgr = RealCodexSessionManager()
+ agent._session_mgr.set_thread_id("session-1", "thread-old")
+ request = SimpleNamespace(base_session_id="session-1", context=SimpleNamespace(platform_specific={}))
+
+ await agent.release_native_runtime(request)
+ self.assertIsNone(agent._session_mgr.get_thread_id("session-1"))
+
+ generation = install_codex_transport(
+ agent, "/tmp/work", SimpleNamespace(stop=AsyncMock(), _process=None), sessions={"session-1": "thread-old"}
+ )
+ with patch.object(CodexAgent, "_release_session_thread", new=AsyncMock()) as release:
+ await agent.release_native_runtime(request)
+ release.assert_awaited_once_with(generation, "session-1")
+
async def test_last_session_end_settles_activity_owners_before_the_kill(self):
"""End kills the process only after the ending Session's Activities settle."""
agent = init_generation_state(object.__new__(CodexAgent))
diff --git a/tests/test_core_services_sessions.py b/tests/test_core_services_sessions.py
index 75b28b72e..c604e4dcc 100644
--- a/tests/test_core_services_sessions.py
+++ b/tests/test_core_services_sessions.py
@@ -20,7 +20,7 @@ from core.services import sessions as sessions_service
from storage import workbench_sessions_service as storage_sessions
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
-from storage.models import agent_sessions, scope_settings
+from storage.models import agent_sessions, scope_settings, session_turns
from storage.settings_service import upsert_scope
@@ -95,6 +95,8 @@ def test_public_surface_is_stable():
"reserve_standalone_agent_session",
# Backend-pin guard raised by update_session on a cross-backend switch:
"SessionBackendLockedError",
+ # The turn watermark a bound backend switch is verified against:
+ "latest_session_turn_id",
# Terminal-archive guard raised by update_session on an archived row:
"SessionArchivedError",
# Localized user-facing copy for that guard's 409 body:
@@ -648,11 +650,14 @@ def test_update_session_pending_fork_locks_backend_until_native_bind(isolated_st
sessions_service.update_session(conn, sid, agent_backend=None, agent_name=None)
-def test_update_session_locks_backend_once_native_exists(isolated_state):
- """Once the first turn bound a native conversation the backend is pinned for
- life — the native can only be resumed by the backend that created it.
- Same-backend agent/model changes stay allowed; a cross-backend switch or a
- clear back to default raises SessionBackendLockedError."""
+def test_update_session_bound_backend_switch_replaces_native(isolated_state):
+ """A bound session switches backend by replacing its native conversation
+ (docs/plans/2026-10-22-session-backend-switch.md): the Avibe session id stays,
+ the old binding is kept as an archived superseded snapshot, the row's native is
+ cleared, and a handoff marker names what was replaced. Vibey is terminal: a
+ bound Vibey session never leaves it. A bound row cannot clear to the default."""
+
+ from sqlalchemy import select
engine = create_sqlite_engine()
with engine.begin() as conn:
@@ -660,16 +665,117 @@ def test_update_session_locks_backend_once_native_exists(isolated_state):
sid = sessions_service.create_session(
conn, scope_id=scope_id, agent_backend="claude", agent_name="claude"
)["id"]
- _bind_native(conn, sid)
- # Same-backend change (different agent / model) is still allowed.
+ _bind_native(conn, sid, "claude-native")
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == sid)
+ .values(
+ metadata_json='{"created_via":"session_fork","fork_source_session_id":"sesparent",'
+ '"fork_source_backend":"claude","fork_source_native_session_id":"parent-native"}'
+ )
+ )
+ # Same-backend change (different agent / model) keeps the conversation.
sessions_service.update_session(conn, sid, agent_backend="claude", agent_name="claude-pro", model="opus")
- # Cross-backend switch is rejected.
+ assert sessions_service.get_session(conn, sid)["native_session_id"] == "claude-native"
+ # Clearing back to the inherited default stays rejected.
+ with pytest.raises(sessions_service.SessionBackendLockedError):
+ sessions_service.update_session(conn, sid, agent_backend=None, agent_name=None)
+
+ # The switch must name the turn history the old runtime was found idle
+ # against, and select an Agent: the Agent identity routes the next turn.
with pytest.raises(sessions_service.SessionBackendLockedError):
sessions_service.update_session(conn, sid, agent_backend="codex", agent_name="codex")
- # Clearing back to the inherited default is rejected too: a future
- # default switch could route the old session through another backend.
+ with pytest.raises(ValueError):
+ sessions_service.update_session(conn, sid, agent_backend="codex", runtime_idle_through_turn="")
+ switched = sessions_service.update_session(
+ conn, sid, agent_backend="codex", agent_name="codex", runtime_idle_through_turn=""
+ )
+ assert switched["id"] == sid
+ assert switched["agent_backend"] == "codex"
+ assert not switched["native_session_id"]
+ handoff = switched["metadata"]["backend_handoff"]
+ assert handoff["id"]
+ assert (handoff["from_backend"], handoff["from_native"], handoff["to_backend"]) == (
+ "claude",
+ "claude-native",
+ "codex",
+ )
+ # The spent fork source must not re-arm a native fork on the empty row.
+ assert "fork_source_native_session_id" not in switched["metadata"]
+ assert "fork_source_backend" not in switched["metadata"]
+ assert switched["metadata"]["fork_source_session_id"] == "sesparent"
+ snapshots = conn.execute(
+ select(agent_sessions).where(agent_sessions.c.native_session_id == "claude-native")
+ ).mappings().all()
+ assert len(snapshots) == 1
+ snapshot = snapshots[0]
+ assert snapshot["id"] != sid
+ assert (snapshot["status"], snapshot["visibility"], snapshot["agent_backend"]) == (
+ "archived",
+ "background",
+ "claude",
+ )
+ assert ":superseded:" in snapshot["session_anchor"]
+ # Only the receipt of a turn that carried THIS handoff can accept it.
+ from storage.agent_session_rows import accept_backend_handoff
+
+ assert accept_backend_handoff(conn, sid, "an-older-switch") is False
+ assert sessions_service.get_session(conn, sid)["metadata"]["backend_handoff"] == handoff
+
+ # The new backend binds; the session can still move, here onto Vibey, but
+ # not while a durable Turn owns it: the controller writes that row before
+ # it dispatches, under the same write lock, ahead of agent_status.
+ _bind_native(conn, sid, "codex-thread")
+ conn.execute(
+ session_turns.insert().values(
+ id="turn-open",
+ session_id=sid,
+ initial_delivery_id="delivery-open",
+ state="starting",
+ backend="codex",
+ start_attempt_id="attempt-open",
+ dispatch_text="next",
+ dispatch_sha256="dispatch",
+ created_at="2026-10-22T00:00:00Z",
+ updated_at="2026-10-22T00:00:00Z",
+ )
+ )
with pytest.raises(sessions_service.SessionBackendLockedError):
- sessions_service.update_session(conn, sid, agent_backend=None, agent_name=None)
+ sessions_service.update_session(
+ conn, sid, agent_backend="vibey", agent_name="vibey", runtime_idle_through_turn="turn-open"
+ )
+ # A turn that ran after the controller was asked, even one already
+ # settled, may have left background work: the stale watermark refuses.
+ conn.execute(
+ session_turns.update()
+ .where(session_turns.c.id == "turn-open")
+ .values(
+ state="terminal",
+ terminal_outcome="not_written",
+ terminal_at="2026-10-22T00:00:01Z",
+ start_attempt_id=None,
+ dispatch_text=None,
+ dispatch_sha256=None,
+ )
+ )
+ with pytest.raises(sessions_service.SessionBackendLockedError):
+ sessions_service.update_session(
+ conn, sid, agent_backend="vibey", agent_name="vibey", runtime_idle_through_turn=""
+ )
+ assert sessions_service.latest_session_turn_id(conn, sid) == "turn-open"
+ sessions_service.update_session(
+ conn, sid, agent_backend="vibey", agent_name="vibey", runtime_idle_through_turn="turn-open"
+ )
+ # (The seeded Turn names no real Delivery; drop it before the commit.)
+ conn.execute(session_turns.delete().where(session_turns.c.id == "turn-open"))
+ _bind_native(conn, sid, sid)
+ # A bound Vibey session stays on Vibey; Agents within Vibey stay switchable.
+ with pytest.raises(sessions_service.SessionBackendLockedError):
+ sessions_service.update_session(
+ conn, sid, agent_backend="claude", agent_name="claude", runtime_idle_through_turn="turn-open"
+ )
+ sessions_service.update_session(conn, sid, agent_backend="vibey", agent_name="vibey-helper")
+ assert sessions_service.get_session(conn, sid)["native_session_id"] == sid
def test_update_session_running_turn_locks_backend(isolated_state):
@@ -762,8 +868,8 @@ def test_update_session_backend_switch_reserves_writer_before_decision(isolated_
def test_update_session_legacy_blank_backend_keeps_initial_pin_escape(isolated_state):
"""Legacy agent-less rows whose native predates the bind-time backend
backfill don't know which backend owns their native; the empty -> concrete
- "initial pin" stays allowed so their picker isn't permanently stuck. The pin
- then locks the session like any other."""
+ "initial pin" stays allowed so their picker isn't permanently stuck, without
+ replacing the native. The pin then makes it an ordinary bound session."""
engine = create_sqlite_engine()
with engine.begin() as conn:
@@ -772,10 +878,15 @@ def test_update_session_legacy_blank_backend_keeps_initial_pin_escape(isolated_s
_bind_native(conn, sid)
# Empty -> concrete is the initial pin, even with a native bound.
sessions_service.update_session(conn, sid, agent_backend="codex", agent_name="codex")
- assert sessions_service.get_session(conn, sid)["agent_backend"] == "codex"
- # Now pinned: a different backend is rejected.
- with pytest.raises(sessions_service.SessionBackendLockedError):
- sessions_service.update_session(conn, sid, agent_backend="claude", agent_name="claude")
+ pinned = sessions_service.get_session(conn, sid)
+ assert (pinned["agent_backend"], pinned["native_session_id"]) == ("codex", "native-1")
+ assert "backend_handoff" not in pinned["metadata"]
+ # Now pinned: a different backend replaces the native like any bound switch.
+ switched = sessions_service.update_session(
+ conn, sid, agent_backend="claude", agent_name="claude", runtime_idle_through_turn=""
+ )
+ assert not switched["native_session_id"]
+ assert switched["metadata"]["backend_handoff"]["from_native"] == "native-1"
# --- HFR-247: the override marker must not outlive the columns it describes ----
diff --git a/tests/test_session_backend_handoff.py b/tests/test_session_backend_handoff.py
new file mode 100644
index 000000000..be0467901
--- /dev/null
+++ b/tests/test_session_backend_handoff.py
@@ -0,0 +1,189 @@
+"""The first turn after a session switched backend (docs/plans/2026-10-22-session-backend-switch.md)."""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from core.agent_input import AgentInputMetadata
+from core.handlers.message_handler import MessageHandler
+from core.session_handoff import BACKEND_HANDOFF_TURN_KEY, HANDOFF_BUDGET_CHARS, render_backend_handoff
+from modules.im import MessageContext
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from storage.models import agent_sessions, messages
+from storage.settings_service import upsert_scope
+from storage.workbench_sessions_service import create_session
+
+_HANDOFF = {"id": "switch-1", "from_backend": "claude", "from_native": "n1", "to_backend": "vibey", "switched_at": ""}
+
+
+def anyio_backend() -> str:
+ return "asyncio"
+
+
+def _seed_session(tmp_path, monkeypatch, *, native: str = "") -> str:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn, platform="avibe", scope_type="project", native_id="proj_handoff", now="2026-10-22T00:00:00Z"
+ )
+ sid = create_session(conn, scope_id=scope_id, agent_backend="vibey", agent_name="vibey")["id"]
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == sid)
+ .values(native_session_id=native, metadata_json=json.dumps({"backend_handoff": dict(_HANDOFF)}))
+ )
+ for index, (author, kind, text) in enumerate(
+ (
+ ("user", "user", "Please migrate the parser to the new API."),
+ ("agent", "result", "Done with the lexer; the parser is next."),
+ ("user", "user", "Keep the old CLI flags working."),
+ ("agent", "interim", "Rewriting the flag parser now, before the turn stopped."),
+ )
+ ):
+ stamp = f"2026-10-22T00:00:0{index}Z"
+ conn.execute(
+ messages.insert().values(
+ id=f"msg-{index}",
+ scope_id=scope_id,
+ session_id=sid,
+ platform="avibe",
+ author=author,
+ type=kind,
+ content_text=text,
+ content_json="{}",
+ metadata_json="{}",
+ created_at=stamp,
+ updated_at=stamp,
+ )
+ )
+ return sid
+
+
+def _im_turn(sid: str, **spec) -> tuple[MessageContext, SimpleNamespace]:
+ """An IM turn: the session is selected by its run target, which can predate the
+ switch and still offer the replaced native."""
+ context = MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ platform="slack",
+ platform_specific={
+ "agent_run_target": {"agent_session_id": sid, "agent_backend": "vibey", "native_session_id": "n1"},
+ **spec,
+ },
+ )
+ request = SimpleNamespace(input_metadata=AgentInputMetadata(user_id="U1", user_name="Alex"))
+ return context, request
+
+
+def _handler(agent, backend: str = "vibey") -> MessageHandler:
+ from config import paths
+ from storage.sessions_service import SQLiteSessionsService
+
+ handler = MessageHandler.__new__(MessageHandler)
+ handler.controller = SimpleNamespace(agent_service=SimpleNamespace(agents={backend: agent}))
+ handler.sessions = SQLiteSessionsService(paths.get_sqlite_state_path())
+ return handler
+
+
+async def test_switched_session_turn_releases_stale_runtime_and_carries_the_handoff(tmp_path, monkeypatch):
+ """The first turn on the new backend reads the session row by id, whichever
+ projection selected it. With no native bound yet it drops any runtime that
+ backend still caches and stops the projections offering the replaced native; it
+ prefixes the input with the handoff (the canonical text is untouched) and is
+ tagged so its native-start receipt can spend the marker."""
+
+ sid = _seed_session(tmp_path, monkeypatch)
+ agent = SimpleNamespace(release_native_runtime=AsyncMock())
+ context, request = _im_turn(sid)
+ await _handler(agent)._attach_backend_handoff(context, "vibey", request)
+
+ agent.release_native_runtime.assert_awaited_once_with(request)
+ assert context.platform_specific["agent_run_target"]["native_session_id"] == ""
+ assert context.platform_specific[BACKEND_HANDOFF_TURN_KEY] == "switch-1"
+ handoff = request.input_metadata.handoff
+ assert f"Avibe session `{sid}`" in handoff
+ assert handoff.index("Please migrate the parser") < handoff.index("Keep the old CLI flags")
+ # A stopped turn's narration survives only as an interim row; it is the latest work.
+ assert "Rewriting the flag parser now" in handoff
+ rendered = request.input_metadata.render("next step", SimpleNamespace(include_time_info=False))
+ assert rendered.startswith("[Avibe handoff]")
+ assert rendered.endswith("[Alex<U1>]\nnext step")
+
+
+ ("backend", "spec", "carries"),
+ [
+ # Bound but not yet accepted (a first turn whose start then failed): no
+ # release, the handoff is still owed.
+ ("vibey", {}, True),
+ # A one-off run on another backend does not continue this conversation.
+ ("claude", {}, False),
+ # Nor does a subagent's namespaced conversation.
+ ("vibey", {"routing_subagent": "reviewer"}, False),
+ ("vibey", {"backend_base_session_id": "base:reviewer"}, False),
+ ],
+)
+async def test_only_turns_continuing_the_switched_conversation_carry_the_handoff(
+ tmp_path, monkeypatch, backend, spec, carries
+):
+ sid = _seed_session(tmp_path, monkeypatch, native="vibey-native")
+ agent = SimpleNamespace(release_native_runtime=AsyncMock())
+ context, request = _im_turn(sid, **spec)
+ await _handler(agent, backend)._attach_backend_handoff(context, backend, request)
+
+ agent.release_native_runtime.assert_not_awaited()
+ assert bool(request.input_metadata.handoff) is carries
+ assert (BACKEND_HANDOFF_TURN_KEY in context.platform_specific) is carries
+
+
+async def test_a_handoff_that_cannot_be_built_fails_the_turn(tmp_path, monkeypatch):
+ """The first accepted turn must carry the complete handoff, so a store failure
+ (here reading the open work) fails the turn before dispatch instead of starting
+ without it, or with an incomplete one."""
+
+ sid = _seed_session(tmp_path, monkeypatch)
+ monkeypatch.setattr(
+ "storage.workbench_sessions_service.derive_session_harness_activities",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("database is locked")),
+ )
+ context, request = _im_turn(sid)
+ with pytest.raises(RuntimeError, match="database is locked"):
+ await _handler(SimpleNamespace(release_native_runtime=AsyncMock()))._attach_backend_handoff(
+ context, "vibey", request
+ )
+ assert BACKEND_HANDOFF_TURN_KEY not in context.platform_specific
+
+
+def test_handoff_keeps_the_newest_conversation_within_its_budget():
+ """However long the history, the block stays within budget, keeps the newest
+ messages in chronological order, says older ones were left out, and always
+ ends with the query for the full record."""
+
+ history = [
+ {"type": "user" if index % 2 == 0 else "result", "text": f"message {index} " + "x" * 3000, "created_at": ""}
+ for index in range(40)
+ ]
+ open_work = [{"item_kind": "watch", "id": f"watch-{index}", "label": "CI", "status": "enabled"} for index in range(30)]
+ block = render_backend_handoff(
+ "sesabc", _HANDOFF, to_backend="vibey", messages=history, has_older=True, open_work=open_work
+ )
+
+ assert len(block) <= HANDOFF_BUDGET_CHARS
+ assert "message 39 " in block
+ assert "message 0 " not in block
+ assert block.index("message 38 ") < block.index("message 39 ")
+ assert "(earlier messages omitted)" in block
+ assert "- ... 18 more" in block
+ assert "WHERE session_id='sesabc'" in block
+ assert block.rstrip().endswith("[End of Avibe handoff]")
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index 67f493498..39607456e 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -270,6 +270,71 @@ def test_fsm_template_matches_real_empty_metadata(tmp_path, _fsm_schema_template
assert clone.execute("PRAGMA integrity_check").fetchone() == ("ok",)
+def test_durable_binding_refresh_drops_a_native_the_session_switched_away_from() -> None:
+ """A Delivery admitted before a backend switch carries the replaced native in its
+ projections; the durable refresh must replace it with the row's, or the new
+ backend's resume helpers would try to resume the old backend's conversation."""
+ context = _context()
+ context.platform_specific["agent_session_target"].update(
+ {"agent_backend": "codex", "native_session_id": "claude-native"}
+ )
+ context.platform_specific["agent_run_target"] = {
+ "agent_session_id": "ses_fsm",
+ "agent_backend": "codex",
+ "native_session_id": "claude-native",
+ }
+ binding = {"id": "ses_fsm", "agent_backend": "codex", "agent_variant": "codex", "native_session_id": ""}
+
+ assert SessionTurnManager._binding_projection_is_stale(context, binding)
+ SessionTurnManager._apply_session_binding_to_context(context, binding)
+ assert context.platform_specific["agent_session_target"]["native_session_id"] == ""
+ assert context.platform_specific["agent_run_target"]["native_session_id"] == ""
+
+
+async def test_native_start_receipt_accepts_the_handoff_its_turn_carried(managers) -> None:
+ """A backend switch's handoff is accepted in the native-start receipt transaction of
+ the turn that carried it; the rest of the session metadata is kept. The row is
+ not bound yet (Claude reports acceptance before its init binds the id), so the
+ marker stays, flagged accepted, for the bind to spend."""
+ from core.session_handoff import BACKEND_HANDOFF_TURN_KEY
+ from storage.agent_session_rows import pending_backend_handoff
+
+ manager, _other, engine, _engine_b, _starts = managers
+ with engine.begin() as conn:
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == "ses_fsm")
+ .values(metadata_json=json.dumps({"keep": 1, "backend_handoff": {"id": "switch-1"}}))
+ )
+
+ def metadata() -> dict:
+ with engine.connect() as conn:
+ return json.loads(
+ conn.execute(
+ select(agent_sessions.c.metadata_json).where(agent_sessions.c.id == "ses_fsm")
+ ).scalar_one()
+ )
+
+ context = _context()
+ admitted = await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="next"),
+ context=context,
+ )
+ assert admitted.turn_id
+ assert pending_backend_handoff(metadata()) is not None
+ context.platform_specific["turn_token"] = admitted.turn_id
+ context.platform_specific[BACKEND_HANDOFF_TURN_KEY] = "switch-1"
+ manager._active_identity = lambda _backend, _session_id, logical_id: (logical_id, f"native-{logical_id}")
+ manager.on_native_start(
+ context,
+ backend="codex",
+ runtime_key=f"runtime-key-{admitted.turn_id}",
+ runtime_turn_id=f"runtime-{admitted.turn_id}",
+ )
+ assert metadata() == {"keep": 1, "backend_handoff": {"id": "switch-1", "accepted": True}}
+
+
@pytest.mark.anyio
async def test_session_lifecycle_invalidates_snapshot_after_operation(managers) -> None:
manager, _other, _engine, _engine_b, _starts = managers
diff --git a/tests/test_sqlite_sessions_store.py b/tests/test_sqlite_sessions_store.py
index f1c9dbed3..2191d0b35 100644
--- a/tests/test_sqlite_sessions_store.py
+++ b/tests/test_sqlite_sessions_store.py
@@ -2864,6 +2864,69 @@ def test_bind_agent_session_by_id_does_not_use_anchor_suffix_as_workdir(tmp_path
service.close()
+def test_bind_agent_session_by_id_holds_a_switched_session_for_the_new_backend(tmp_path: Path) -> None:
+ """After a bound session switches backend, a late bind of the replaced native, or
+ a bind from any other backend, must not rebind or relabel the row. The switch's
+ handoff marker is spent only once a turn carrying it was accepted AND the row is
+ bound to the new native, in whichever order the backend reports the two."""
+ from storage import workbench_sessions_service
+ from storage.agent_session_rows import accept_backend_handoff, pending_backend_handoff
+
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+
+ def switched(anchor: str, from_backend: str, to_backend: str) -> str:
+ reserved_id = service.reserve_agent_session(
+ scope_key="slack::channel::C123",
+ agent_backend=from_backend,
+ session_anchor=anchor,
+ agent_name=from_backend,
+ )
+ assert reserved_id is not None
+ service.bind_agent_session_by_id(session_id=reserved_id, native_session_id=f"{from_backend}-native")
+ with service.engine.begin() as conn:
+ workbench_sessions_service.update_session(
+ conn, reserved_id, agent_backend=to_backend, agent_name=to_backend, runtime_idle_through_turn=""
+ )
+ return reserved_id
+
+ def state(session_id: str) -> tuple[str, str, dict | None]:
+ row = service.get_agent_session_by_id(session_id)
+ assert row is not None
+ return row["agent_backend"], row["native_session_id"], pending_backend_handoff(json.loads(row["metadata_json"]))
+
+ def accept(session_id: str) -> None:
+ handoff = state(session_id)[2]
+ assert handoff is not None
+ with service.engine.begin() as conn:
+ assert accept_backend_handoff(conn, session_id, handoff["id"])
+
+ try:
+ # Bind-then-accept (Vibey, Codex, OpenCode).
+ vibey = switched("slack_vibey", "claude", "vibey")
+ for native, backend in (("claude-native", "claude"), ("claude-native", None), ("codex-thread", "codex")):
+ assert service.bind_agent_session_by_id(
+ session_id=vibey, native_session_id=native, vibe_agent_backend=backend
+ ) == vibey
+ assert state(vibey)[:2] == ("vibey", "")
+ service.bind_agent_session_by_id(session_id=vibey, native_session_id=vibey, vibe_agent_backend="vibey")
+ backend, native, handoff = state(vibey)
+ # Bound before any turn was accepted (a thread whose first turn then failed):
+ # the next turn still owes the handoff.
+ assert (backend, native) == ("vibey", vibey) and handoff is not None and not handoff["accepted"]
+ accept(vibey)
+ assert state(vibey) == ("vibey", vibey, None)
+
+ # Accept-then-bind (Claude reports acceptance before its init binds the id).
+ claude = switched("slack_claude", "codex", "claude")
+ accept(claude)
+ assert state(claude)[2]["accepted"] is True
+ service.bind_agent_session_by_id(session_id=claude, native_session_id="claude-new", vibe_agent_backend="claude")
+ assert state(claude) == ("claude", "claude-new", None)
+ finally:
+ service.close()
+
+
def test_bind_agent_session_by_id_does_not_derive_variant_from_vibe_agent_name(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
service = SQLiteSessionsService(db_path)
@@ -6828,6 +6891,12 @@ _MARKER_EXEMPT_ROUTE_WRITE_SITES = {
# caller, which is the layer that knows whether the new row PINS its
# model / effort or merely inherits them.
"create_agent_session_row": "INSERT path: metadata comes from the caller",
+ # Native replacement snapshot (OpenCode repair, backend switch): the INSERT
+ # copies the old binding's complete route and metadata marker unchanged
+ # into an inert superseded row.
+ "insert_superseded_native_snapshot": (
+ "superseded snapshot: route and marker are copied together unchanged"
+ ),
},
"storage/sessions_service.py": {
# Native-bind UPDATEs -- TWO detected sites since HFR-254 split the write
@@ -6867,12 +6936,6 @@ _MARKER_EXEMPT_ROUTE_WRITE_SITES = {
"legacy import: the detected site is the INSERT path, and the upsert's "
"set_ excludes both pinnable columns (see the note on its backend relabel)"
),
- # Native repair snapshot: the INSERT copies the old binding's complete
- # route and metadata marker unchanged into an inert superseded row. The
- # active-row UPDATE changes only native_session_id and timestamps.
- "replace_agent_session_native": (
- "native repair snapshot: route and marker are copied together unchanged"
- ),
},
}
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 2381ef2a6..cbb0d7236 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -794,6 +794,12 @@ def _machine_coded_error_builders():
# Round 5d: terminal archive vs retryable lock, on the same route. A client can
# only tell them apart if BOTH codes survive.
("backend_locked", lambda: ui_server._backend_locked_response(locked), "backend_locked", 409),
+ (
+ "backend_busy",
+ lambda: ui_server._backend_busy_response(current_backend="claude", requested_backend="vibey"),
+ "backend_busy",
+ 409,
+ ),
# The runtime-reserved workspace-notifications row: one code, three verbs, so the
# per-verb sentence is the only thing that varies and BOTH must keep the code.
(
@@ -1311,6 +1317,66 @@ def test_sessions_patch_archived_outranks_the_backend_lock_preflight(monkeypatch
assert in_flight.await_count == 1
+def test_sessions_patch_bound_backend_switch_waits_for_the_old_runtime(monkeypatch, tmp_path):
+ """A bound session switches backend only once its old runtime is settled.
+
+ The switch replaces the native conversation, but a detached backend Activity (or
+ its undelivered output) would keep running on the replaced one; only the
+ controller can tell, so an unreachable controller refuses too. Harness items in
+ the same list follow the session and do not block. A settled session switches.
+ """
+ from unittest.mock import AsyncMock, patch
+
+ from core.vibe_agents import VibeAgentStore
+ from storage.db import create_sqlite_engine
+ from storage.models import agent_sessions
+ from storage.projects_service import create_project
+ from storage.workbench_sessions_service import create_session
+ from vibe import internal_client
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ project_dir = tmp_path / "project"
+ project_dir.mkdir()
+ with engine.begin() as conn:
+ project = create_project(conn, str(project_dir), display_name="Project")
+ sid = create_session(conn, scope_id=project["scope_id"], agent_backend="claude", title="Bound")["id"]
+ conn.execute(
+ agent_sessions.update().where(agent_sessions.c.id == sid).values(native_session_id="claude-native")
+ )
+ store = VibeAgentStore()
+ try:
+ store.create(name="reviewer", backend="codex")
+ finally:
+ store.close()
+
+ client = app.test_client()
+ headers = csrf_headers(client)
+
+ def turn_state(**body):
+ 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")),
+ )
+ for probe 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"
+
+ settled = turn_state(background_activities=[{"item_kind": "watch", "id": "watch-1"}])
+ with patch("vibe.internal_client.turn_state", settled):
+ switched = client.patch(f"/api/sessions/{sid}", json={"agent_name": "reviewer"}, headers=headers)
+ assert switched.status_code == 200
+ body = switched.get_json()
+ assert (body["id"], body["agent_backend"], body["native_session_id"]) == (sid, "codex", "")
+ assert body["metadata"]["backend_handoff"]["from_native"] == "claude-native"
+
+
def test_sessions_patch_missing_session_is_still_404(monkeypatch, tmp_path):
"""The archived short-circuit must not swallow the not-found case.
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 41c39800d..e7944d6ba 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -3673,27 +3673,31 @@ export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, d
const hasMobileSessionActions = writable && mobileSessionActions.length > 0;
const defaultAgent = defaultAgentName ? agents.find((agent) => agent.name === defaultAgentName) : null;
const sessionAgentLabel = sessionAgentDisplayName(session, agents);
- // 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. 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".
+ // Mirrors update_session's guard. A session with a NATIVE conversation can
+ // still move to another backend: the server replaces the conversation and
+ // hands the next turn a handoff (docs/plans/2026-10-22-session-backend-switch.md).
+ // It stays on its backend while a turn is RUNNING (the in-flight turn binds
+ // its native on the current route any moment), as a pending fork, and for
+ // good once it has a Vibey conversation: Vibey is where a session can move
+ // to, never from. A bound session also has no "default" choice, which would
+ // clear it to a blank backend. 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 nativeBound = Boolean(session.native_session_id);
const pendingForkBackend =
!session.native_session_id &&
session.metadata?.created_via === 'session_fork' &&
typeof session.metadata?.fork_source_backend === 'string'
? session.metadata.fork_source_backend.trim() || null
: null;
- const backendLocked = Boolean(session.native_session_id) || working || Boolean(pendingForkBackend);
+ const backendLocked =
+ (nativeBound && concreteBackend === 'vibey') || working || Boolean(pendingForkBackend);
const pinnedBackend = pendingForkBackend ?? (backendLocked ? concreteBackend : null);
- const canClearToDefault = !backendLocked;
+ const canClearToDefault = !backendLocked && !nativeBound;
const pickerDisabled = working && !concreteBackend && !pendingForkBackend;
const defaultRoute = defaultAgent
? {
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index a6667bb22..7496ceb52 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2849,6 +2849,8 @@
"not_public": "Make the Show Page public first to change its link.",
"session_agent_unavailable": "The source session's Agent is no longer available. Choose an enabled Agent to fork this session.",
"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.",
"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.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index c76cbd103..6c811effd 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2849,6 +2849,8 @@
"not_public": "请先把展示页面设为公开,再修改链接。",
"session_agent_unavailable": "源会话的 Agent 已不可用。请选择一个已启用的 Agent 来复刻此会话。",
"session_archived": "该会话已归档,无法修改它的展示页面。",
+ "backend_locked": "这个会话现在不能切换到该后端:正在运行的回合需要先结束,Vibey 会话只能留在 Vibey。",
+ "backend_busy": "这个会话在当前后端上还有后台任务在运行,等它结束后再切换。",
"reserved_session": "该会话由 Avibe 管理,只接收工作区通知。",
"invalid_icon_type": "图标必须是 SVG、PNG、ICO、JPEG 或 WebP 图片。",
"icon_too_large": "图标太大了,请使用不超过 2 MiB 的图片。",
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index d508190ed..50028baf4 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -11,7 +11,8 @@
"modelSourceRequired": "{backend} has no model source yet. Add an API key or a subscription in Models.",
"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."
+ "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."
},
"status": {
"backendUnresponsive": "backend not responding",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index cf775adb2..c6f1122b2 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -11,7 +11,8 @@
"modelSourceRequired": "{backend} 还没有模型来源。请在「模型」页添加 API Key 或订阅。",
"modelsNextStepImUrl": "管理这个 Avibe 的人可以在「模型」页处理:{url}",
"modelsNextStepIm": "管理这个 Avibe 的人可以在 Avibe 工作台的「模型」页处理。",
- "opencodeModelProviderRequired": "请在 Avibe 中选择带供应商的 OpenCode 模型,或配置它的 Model Hub 路由。"
+ "opencodeModelProviderRequired": "请在 Avibe 中选择带供应商的 OpenCode 模型,或配置它的 Model Hub 路由。",
+ "sessionBackendBusy": "这个会话在当前后端上还有后台任务在运行,等它结束后再切换。"
},
"status": {
"backendUnresponsive": "后端无响应",
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 39d4682c2..58e4390bb 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -10212,6 +10212,36 @@ def _backend_locked_response(err):
)
+def _backend_runtime_busy(turn_state: dict) -> bool:
+ """Whether the controller reports backend work outside a turn for the session.
+
+ Harness items in the same list (Watches, Tasks, delegated runs) are durable and
+ follow the session to its new backend; only process-local backend Activities
+ and their unclaimed output belong to the runtime a switch leaves behind.
+ """
+ activities = turn_state.get("background_activities") or []
+ if any(isinstance(item, dict) and item.get("item_kind") == "backend_activity" for item in activities):
+ return True
+ try:
+ return int(turn_state.get("pending_activity_output_count") or 0) > 0
+ except (TypeError, ValueError):
+ return True
+
+
+def _backend_busy_response(*, current_backend, requested_backend):
+ """Retryable 409 for a backend switch the old runtime's background work blocks."""
+ from core.services import settings as settings_service
+
+ lang = settings_service.load_config_or_default().language
+ return _coded_error_response(
+ "backend_busy",
+ t("errors.sessionBackendBusy", lang),
+ 409,
+ current_backend=current_backend,
+ requested_backend=requested_backend,
+ )
+
+
def _publish_session_update_activity(
broker,
*,
@@ -10350,18 +10380,32 @@ 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).
+ 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)
- in_flight = bool((turn_result.get("body") or {}).get("in_flight"))
+ 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(
@@ -10370,6 +10414,11 @@ async def sessions_update(session_id: str):
requested_backend=requested_backend,
)
)
+ if bound_switch and runtime_busy:
+ return _backend_busy_response(
+ current_backend=current.get("agent_backend"),
+ requested_backend=requested_backend,
+ )
try:
with engine.begin() as conn:
@@ -10394,6 +10443,7 @@ async def sessions_update(session_id: str):
session = workbench_sessions_service.update_session(
conn,
session_id,
+ runtime_idle_through_turn=runtime_idle_through_turn,
authorization_context=getattr(g, "authorization_context", None),
**updatable,
)