Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(workbench): preserve inherited route labels (#1253)
Call White2b30ec7e1e99
diff --git a/config/v2_sessions.py b/config/v2_sessions.pyindex d1a127f94..4d2494959 100644--- a/config/v2_sessions.py+++ b/config/v2_sessions.py@@ -437,14 +437,20 @@ class SessionsStore:self,agent_session_id: str,*,+ agent_id: str | None = None,+ agent_name: str | None = None,model: str | None = None,reasoning_effort: str | None = None,+ expected_route: dict[str, Any] | None = None,) -> bool:self._ensure_service()return self._service.materialize_agent_session_route(agent_session_id,+ agent_id=agent_id,+ agent_name=agent_name,model=model,reasoning_effort=reasoning_effort,+ expected_route=expected_route,)def bind_agent_session_by_id(diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 2328cb534..33511715b 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -450,6 +450,12 @@ class MessageHandler(BaseHandler):effective_reasoning_effort = session_target_reasoning or scope_reasoning_override or (vibe_agent.reasoning_effort if vibe_agent else None)+ materialized_agent_identity = bool(+ vibe_agent+ and isinstance(session_target, dict)+ and not session_target.get("agent_id")+ and not session_target.get("agent_name")+ )# A session may pin a setting to NOTHING on purpose. The cascade above# cannot express that: every `or` reads NULL as "inherit", which is the# correct reading for the whole existing table and the WRONG one for a@@ -460,38 +466,48 @@ class MessageHandler(BaseHandler):# silently re-route every session that is merely inheriting.explicit_overrides: set[str] = set()if isinstance(session_target, dict):- session_meta = session_target.get("metadata")- if isinstance(session_meta, dict):- from storage.session_reclaim import SESSION_SETTINGS_OVERRIDE_KEY+ from storage.session_reclaim import explicit_override_names- marked = session_meta.get(SESSION_SETTINGS_OVERRIDE_KEY)- if isinstance(marked, (list, tuple, set)):- explicit_overrides = {str(name) for name in marked}+ explicit_overrides = explicit_override_names(session_target.get("metadata"))if "model" in explicit_overrides:effective_model = session_target.get("model")if "reasoning_effort" in explicit_overrides:effective_reasoning_effort = session_target.get("reasoning_effort")- # Materialize the resolved route into EMPTY workbench session- # columns NOW, at turn start. A session created on an inherited- # default carries NULLs (dispatch resolves the live Agent default);- # without pinning, the chat header shows an agent with no model /- # effort after the first message. Pinning at turn START — not at- # native bind — means any later explicit header pick in this turn- # (including an explicit clear to NULL) lands after this write and- # is never undone by it. IM (scope/anchor) rows never carry- # ``agent_session_target`` and are untouched: their model semantics- # stay with channel routing.- if isinstance(session_target, dict) and session_target.get("id") and (- (effective_model and not session_target.get("model"))- or (effective_reasoning_effort and not session_target.get("reasoning_effort"))+ # Materialize the resolved route into EMPTY Workbench session+ # columns at turn start. A session created on an inherited default+ # carries NULLs (dispatch resolves the live Agent default); without+ # pinning, the chat header shows an Agent with no model / effort+ # after the first message. Scheduled IM turns can carry the same+ # target projection, so the platform gate is essential: their model+ # semantics remain owned by channel routing.+ if (+ context.platform == "avibe"+ and isinstance(session_target, dict)+ and session_target.get("id")+ and (+ materialized_agent_identity+ or (effective_model and not session_target.get("model"))+ or (effective_reasoning_effort and not session_target.get("reasoning_effort"))+ )):materialize = getattr(self.sessions, "materialize_agent_session_route", None)if callable(materialize):try:materialize(str(session_target["id"]),+ agent_id=vibe_agent.id if materialized_agent_identity else None,+ agent_name=vibe_agent.name if materialized_agent_identity else None,model=effective_model,reasoning_effort=effective_reasoning_effort,+ expected_route={+ "agent_id": session_target.get("agent_id"),+ "agent_name": session_target.get("agent_name"),+ "agent_backend": session_target.get("agent_backend"),+ "agent_variant": session_target.get("agent_variant"),+ "model": session_target.get("model"),+ "reasoning_effort": session_target.get("reasoning_effort"),+ "explicit_overrides": sorted(explicit_overrides),+ },)except Exception:logger.debug("Session route materialization failed; dispatch continues", exc_info=True)diff --git a/modules/sessions_facade.py b/modules/sessions_facade.pyindex 81b8581ad..97ec928e1 100644--- a/modules/sessions_facade.py+++ b/modules/sessions_facade.py@@ -103,6 +103,25 @@ class SessionsFacade:)return self.get_agent_session_row_id(user_key, thread_id, agent_name)+ def materialize_agent_session_route(+ self,+ agent_session_id: str,+ *,+ agent_id: str | None = None,+ agent_name: str | None = None,+ model: str | None = None,+ reasoning_effort: str | None = None,+ expected_route: dict[str, Any] | None = None,+ ) -> bool:+ return self.sessions_store.materialize_agent_session_route(+ agent_session_id,+ agent_id=agent_id,+ agent_name=agent_name,+ model=model,+ reasoning_effort=reasoning_effort,+ expected_route=expected_route,+ )+def bind_agent_session(self,user_id: Union[int, str],diff --git a/storage/sessions_service.py b/storage/sessions_service.pyindex 3d1246229..750898720 100644--- a/storage/sessions_service.py+++ b/storage/sessions_service.py@@ -823,18 +823,23 @@ class SQLiteSessionsService:self,session_id: str,*,+ agent_id: str | None = None,+ agent_name: str | None = None,model: str | None = None,reasoning_effort: str | None = None,+ expected_route: Mapping[str, Any] | None = None,) -> bool:- """Pin the model / effort a turn is about to run with into EMPTY columns.+ """Pin the resolved Agent identity and route into EMPTY columns.A session created on an inherited default carries NULLs (dispatch- resolves the live Agent default); the first turn pins the resolved- values — same lifecycle as the backend pin on native bind. Called at- dispatch time (turn START), so a user's later explicit header pick —- including an explicit clear back to NULL — happens after this write and- is never undone by it. COALESCE keeps the fill-if-empty atomic against- a concurrent pick. Returns True when a row was updated.+ resolves the live Agent default); the first turn pins the resolved Agent+ identity, model, and effort — same lifecycle as the backend pin on native+ bind. Called at dispatch time (turn START). The writer reservation+ serializes the marker read with this write, while ``expected_route`` makes+ a stale turn a no-op if the user has already changed any Agent, model,+ effort, or explicit-pin part of the route.+ COALESCE keeps each setting fill-if-empty. Returns True when a row was+ updated.A setting the row pins EXPLICITLY is never filled, even when its columnis empty: that is the whole point of the explicit-override marker (a@@ -842,6 +847,7 @@ class SQLiteSessionsService:it here would turn the first turn into the thing the rebind was preventing-- the Agent's current default becoming the session's pinned model."""with self.engine.begin() as conn:+ reserve_write_lock(conn)pinned = explicit_override_names(_json_loads(conn.execute(@@ -852,7 +858,18 @@ class SQLiteSessionsService:{},))+ if expected_route is not None and "explicit_overrides" in expected_route:+ expected_pinned = {+ str(name)+ for name in (expected_route.get("explicit_overrides") or [])+ }+ if pinned != expected_pinned:+ return Falsevalues: dict[str, Any] = {}+ if agent_id:+ values["agent_id"] = func.coalesce(func.nullif(agent_sessions.c.agent_id, ""), agent_id)+ if agent_name:+ values["agent_name"] = func.coalesce(func.nullif(agent_sessions.c.agent_name, ""), agent_name)if model and "model" not in pinned:values["model"] = func.coalesce(func.nullif(agent_sessions.c.model, ""), model)if reasoning_effort and "reasoning_effort" not in pinned:@@ -862,12 +879,26 @@ class SQLiteSessionsService:if not values:return Falsevalues["updated_at"] = _utc_now_iso()- result = conn.execute(+ statement = (agent_sessions.update().where(agent_sessions.c.id == str(session_id)).where(agent_sessions.c.status != "archived").values(**values))+ for field in (+ "agent_id",+ "agent_name",+ "agent_backend",+ "agent_variant",+ "model",+ "reasoning_effort",+ ):+ if expected_route is not None and field in expected_route:+ statement = statement.where(+ func.coalesce(getattr(agent_sessions.c, field), "")+ == str(expected_route.get(field) or "")+ )+ result = conn.execute(statement)return bool(result.rowcount)def bind_agent_session_by_id(@@ -964,6 +995,8 @@ class SQLiteSessionsService:).where(agent_sessions.c.id == str(session_id))).mappings().first()current_backend = str((route_row or {}).get("agent_backend") or "")+ 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")))backend_changes = bool(requested_backend) and requested_backend != current_backendif backend_changes and not already_bound:@@ -982,16 +1015,27 @@ class SQLiteSessionsService:adopt_values = dict(values)adopt_values["agent_backend"] = requested_backendadopt_values["agent_variant"] = requested_backend or "default"- adopt_values["model"] = None- adopt_values["reasoning_effort"] = None- adopt_values["metadata_json"] = json.dumps(- reconcile_explicit_overrides(- _json_loads((route_row or {}).get("metadata_json"), {}),- cleared=OVERRIDABLE_SETTING_COLUMNS,- ),- separators=(",", ":"),- ensure_ascii=False,+ # Only Workbench performs turn-start materialization. Its+ # backend-less row therefore owns the resolved route already and+ # initial adoption must keep it. Placeholder IM rows never pass+ # through that lifecycle, so their old route is incompatible with+ # the newly adopted backend and must be cleared like a concrete+ # backend-to-backend replacement (HFR-250).+ preserves_materialized_workbench_route = (+ not _is_owned_backend(current_backend)+ and route_metadata.get("created_via") == "workbench")+ if not preserves_materialized_workbench_route:+ adopt_values["model"] = None+ adopt_values["reasoning_effort"] = None+ adopt_values["metadata_json"] = json.dumps(+ reconcile_explicit_overrides(+ route_metadata,+ cleared=OVERRIDABLE_SETTING_COLUMNS,+ ),+ separators=(",", ":"),+ ensure_ascii=False,+ )adopt_values["native_session_id"] = encoded_session_idadopted = conn.execute(agent_sessions.update()diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yamlindex 996d237d0..cb06eae41 100644--- a/tests/scenarios/harness_failure_recovery/catalog.yaml+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml@@ -4144,6 +4144,15 @@ scenarios:# The durable input keeps Turn ownership, Stop, and audit history intact but# is not a human instruction and therefore never renders in the transcript.test: tests/test_session_delivery_fsm.py::test_agent_initiated_continuation_materializes_as_hidden_turn_input+ - id: HFR-462+ name: inherited Workbench routes materialize through the runtime session facade+ status: covered+ kind: routing+ layer: contract+ backend: shared+ # The handler-to-facade contract forwards the resolved route at Turn start;+ # the refreshed chat header remains a residual manual UI check.+ test: tests/test_message_handler_typing.py::MessageHandlerTypingTests::test_workbench_inherited_route_materializes_at_turn_startmanual_evidence:- local Incus backend process death after prompt acceptance- local Incus controller restart with persisted queued successordiff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.pyindex 8fe0c3dc4..d8da86c79 100644--- a/tests/test_message_handler_typing.py+++ b/tests/test_message_handler_typing.py@@ -11,6 +11,7 @@ ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT))from modules.im import MessageContext+from modules.sessions_facade import SessionsFacadefrom core.processing_indicator import ProcessingIndicatorService@@ -1082,11 +1083,15 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):self.assertIsNone(request.vibe_agent_reasoning_effort)async def test_workbench_inherited_route_materializes_at_turn_start(self):- """A workbench session created on an inherited default (empty model /+ """HFR-462: a workbench session created on an inherited default (empty model /effort) gets the resolved Agent defaults pinned onto its row when theturn STARTS, so the chat-header picker keeps showing the full route."""controller = _StubController(platform="avibe", ack_mode="reaction", typing_result=True)- controller.settings_manager.sessions.materialize_agent_session_route = Mock(return_value=True)+ sessions_store = Mock()+ sessions_store.is_message_in_processed_set.return_value = False+ sessions_store.try_add_to_processed_set.return_value = True+ sessions_store.materialize_agent_session_route = Mock(return_value=True)+ controller.settings_manager.sessions = SessionsFacade(sessions_store)handler = MessageHandler(controller)handler.set_session_handler(_StubSessionHandler())context = MessageContext(@@ -1097,8 +1102,10 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):platform_specific={"agent_session_target": {"id": "ses_wb",+ "agent_id": None,"agent_name": None,"agent_backend": None,+ "agent_variant": None,"model": None,"reasoning_effort": None,}@@ -1107,8 +1114,21 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):await handler.handle_user_message(context, "hello")- controller.settings_manager.sessions.materialize_agent_session_route.assert_called_once_with(- "ses_wb", model="gpt-5.4", reasoning_effort="high"+ sessions_store.materialize_agent_session_route.assert_called_once_with(+ "ses_wb",+ agent_id="agent-default",+ agent_name="default",+ model="gpt-5.4",+ reasoning_effort="high",+ expected_route={+ "agent_id": None,+ "agent_name": None,+ "agent_backend": None,+ "agent_variant": None,+ "model": None,+ "reasoning_effort": None,+ "explicit_overrides": [],+ },)async def test_workbench_explicit_route_skips_materialization(self):@@ -1138,14 +1158,78 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):controller.settings_manager.sessions.materialize_agent_session_route.assert_not_called()+ async def test_workbench_scalar_explicit_route_marker_uses_shared_parser(self):+ """A tolerated legacy scalar marker must mean the same thing to the+ dispatch snapshot and the storage CAS: model stays explicitly null while+ the unpinned effort can still materialize."""+ controller = _StubController(platform="avibe", ack_mode="reaction", typing_result=True)+ sessions_store = Mock()+ sessions_store.is_message_in_processed_set.return_value = False+ sessions_store.try_add_to_processed_set.return_value = True+ sessions_store.materialize_agent_session_route = Mock(return_value=True)+ controller.settings_manager.sessions = SessionsFacade(sessions_store)+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ context = MessageContext(+ user_id="U1",+ channel_id="ses_wb",+ message_id="m1",+ platform="avibe",+ platform_specific={+ "agent_session_target": {+ "id": "ses_wb",+ "agent_id": None,+ "agent_name": None,+ "agent_backend": None,+ "agent_variant": None,+ "model": None,+ "reasoning_effort": None,+ "metadata": {"explicit_setting_overrides": "model"},+ }+ },+ )++ await handler.handle_user_message(context, "hello")++ sessions_store.materialize_agent_session_route.assert_called_once_with(+ "ses_wb",+ agent_id="agent-default",+ agent_name="default",+ model=None,+ reasoning_effort="high",+ expected_route={+ "agent_id": None,+ "agent_name": None,+ "agent_backend": None,+ "agent_variant": None,+ "model": None,+ "reasoning_effort": None,+ "explicit_overrides": ["model"],+ },+ )+async def test_im_turn_never_materializes_session_route(self):- """IM turns carry no ``agent_session_target``; their model semantics- belong to channel routing and must never be pinned onto session rows."""+ """Scheduled IM turns can carry ``agent_session_target``; their model+ semantics still belong to channel routing and must not be pinned."""controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)controller.settings_manager.sessions.materialize_agent_session_route = Mock(return_value=True)handler = MessageHandler(controller)handler.set_session_handler(_StubSessionHandler())- context = MessageContext(user_id="U1", channel_id="C1", message_id="m1", platform="slack")+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ message_id="m1",+ platform="slack",+ platform_specific={+ "agent_session_target": {+ "id": "ses_im",+ "agent_name": "codex",+ "agent_backend": "codex",+ "model": None,+ "reasoning_effort": None,+ }+ },+ )await handler.handle_user_message(context, "hello")diff --git a/tests/test_sqlite_sessions_store.py b/tests/test_sqlite_sessions_store.pyindex 01144d974..df023c265 100644--- a/tests/test_sqlite_sessions_store.py+++ b/tests/test_sqlite_sessions_store.py@@ -2149,7 +2149,18 @@ def test_materialize_agent_session_route_fills_empty_columns_only(tmp_path: Path# First turn resolves the Agent default → empty columns fill in.assert service.materialize_agent_session_route(- reserved_id, model="gpt-5.5", reasoning_effort="xhigh"+ reserved_id,+ model="gpt-5.5",+ reasoning_effort="xhigh",+ expected_route={+ "agent_id": row["agent_id"],+ "agent_name": row["agent_name"],+ "agent_backend": row["agent_backend"],+ "agent_variant": row["agent_variant"],+ "model": None,+ "reasoning_effort": None,+ "explicit_overrides": [],+ },)row = service.get_agent_session_by_id(reserved_id)assert row is not None@@ -2183,6 +2194,386 @@ def test_materialize_agent_session_route_fills_empty_columns_only(tmp_path: Pathservice.close()+def test_materialize_agent_session_route_pins_resolved_agent_identity(tmp_path: Path) -> None:+ db_path = tmp_path / "vibe.sqlite"+ service = SQLiteSessionsService(db_path)+ try:+ with service.engine.begin() as conn:+ scope_id = resolve_scope_from_legacy_key(+ conn, "avibe::project::proj_abc", now="2026-08-10T00:00:00Z"+ )+ assert scope_id is not None+ session_id = create_agent_session_row(+ conn,+ scope_id=scope_id,+ session_anchor="avibe_ses_identity",+ agent_backend="",+ agent_variant="default",+ agent_name=None,+ model=None,+ reasoning_effort=None,+ native_session_id="",+ workdir=str(tmp_path),+ metadata={"created_via": "workbench"},+ )++ assert service.materialize_agent_session_route(+ session_id,+ agent_id="agent-default",+ agent_name="default",+ model="gpt-5.4",+ reasoning_effort="high",+ expected_route={+ "agent_id": None,+ "agent_name": None,+ "agent_backend": None,+ "agent_variant": "default",+ "model": None,+ "reasoning_effort": None,+ "explicit_overrides": [],+ },+ )+ row = service.get_agent_session_by_id(session_id)+ assert row is not None+ assert row["agent_id"] == "agent-default"+ assert row["agent_name"] == "default"+ assert row["model"] == "gpt-5.4"+ assert row["reasoning_effort"] == "high"+ finally:+ service.close()+++def test_materialize_agent_session_route_rejects_stale_agent_route(tmp_path: Path) -> None:+ db_path = tmp_path / "vibe.sqlite"+ service = SQLiteSessionsService(db_path)+ try:+ with service.engine.begin() as conn:+ scope_id = resolve_scope_from_legacy_key(+ conn, "avibe::project::proj_abc", now="2026-08-10T00:00:00Z"+ )+ assert scope_id is not None+ session_id = create_agent_session_row(+ conn,+ scope_id=scope_id,+ session_anchor="avibe_ses1",+ agent_backend="codex",+ agent_variant="codex",+ agent_name="old-agent",+ model=None,+ reasoning_effort=None,+ native_session_id="",+ workdir=str(tmp_path),+ metadata={},+ )+ stale_route = {+ "agent_id": None,+ "agent_name": "old-agent",+ "agent_backend": "codex",+ "agent_variant": "codex",+ "model": None,+ "reasoning_effort": None,+ "explicit_overrides": [],+ }++ with service.engine.begin() as conn:+ conn.execute(+ agent_sessions.update()+ .where(agent_sessions.c.id == session_id)+ .values(agent_name="new-agent")+ )++ assert not service.materialize_agent_session_route(+ session_id,+ model="gpt-5.5",+ reasoning_effort="xhigh",+ expected_route=stale_route,+ )+ row = service.get_agent_session_by_id(session_id)+ assert row is not None+ assert row["agent_name"] == "new-agent"+ assert row["model"] is None+ assert row["reasoning_effort"] is None+ finally:+ service.close()+++def test_materialize_agent_session_route_rejects_stale_same_agent_settings(+ tmp_path: Path,+) -> None:+ db_path = tmp_path / "vibe.sqlite"+ service = SQLiteSessionsService(db_path)+ try:+ with service.engine.begin() as conn:+ scope_id = resolve_scope_from_legacy_key(+ conn, "avibe::project::proj_abc", now="2026-08-10T00:00:00Z"+ )+ assert scope_id is not None+ session_id = create_agent_session_row(+ conn,+ scope_id=scope_id,+ session_anchor="avibe_ses2",+ agent_backend="codex",+ agent_variant="codex",+ agent_name="codex",+ model=None,+ reasoning_effort=None,+ native_session_id="native-1",+ workdir=str(tmp_path),+ metadata={},+ )+ stale_route = {+ "agent_id": None,+ "agent_name": "codex",+ "agent_backend": "codex",+ "agent_variant": "codex",+ "model": None,+ "reasoning_effort": None,+ "explicit_overrides": [],+ }++ from storage.workbench_sessions_service import update_session++ with service.engine.begin() as conn:+ update_session(+ conn,+ session_id,+ model="gpt-5.5",+ reasoning_effort=None,+ )++ assert not service.materialize_agent_session_route(+ session_id,+ model="gpt-5.4",+ reasoning_effort="high",+ expected_route=stale_route,+ )+ row = service.get_agent_session_by_id(session_id)+ assert row is not None+ assert row["model"] == "gpt-5.5"+ assert row["reasoning_effort"] is None+ finally:+ service.close()+++def test_materialize_agent_session_route_rejects_changed_explicit_pin_snapshot(+ tmp_path: Path,+) -> None:+ from storage.session_reclaim import SESSION_SETTINGS_OVERRIDE_KEY+ from storage.workbench_sessions_service import update_session++ db_path = tmp_path / "vibe.sqlite"+ service = SQLiteSessionsService(db_path)+ try:+ with service.engine.begin() as conn:+ scope_id = resolve_scope_from_legacy_key(+ conn, "avibe::project::proj_abc", now="2026-08-10T00:00:00Z"+ )+ assert scope_id is not None+ session_id = create_agent_session_row(+ conn,+ scope_id=scope_id,+ session_anchor="avibe_ses_pin",+ agent_backend="codex",+ agent_variant="codex",+ agent_name="codex",+ model=None,+ reasoning_effort=None,+ native_session_id="native-1",+ workdir=str(tmp_path),+ metadata={SESSION_SETTINGS_OVERRIDE_KEY: ["reasoning_effort"]},+ )+ stale_route = {+ "agent_id": None,+ "agent_name": "codex",+ "agent_backend": "codex",+ "agent_variant": "codex",+ "model": None,+ "reasoning_effort": None,+ "explicit_overrides": ["reasoning_effort"],+ }++ # The picker replaces the explicit-null effort with inherited NULL. The+ # columns are byte-for-byte unchanged; only the route marker proves that+ # the hydrated Turn snapshot is stale.+ with service.engine.begin() as conn:+ update_session(conn, session_id, reasoning_effort=None)++ assert not service.materialize_agent_session_route(+ session_id,+ model="gpt-5.4",+ reasoning_effort="high",+ expected_route=stale_route,+ )+ row = service.get_agent_session_by_id(session_id)+ assert row is not None+ assert row["model"] is None+ assert row["reasoning_effort"] is None+ finally:+ service.close()++[email protected]("placeholder_backend", ["", "default", "unknown"])+def test_first_backend_adoption_preserves_materialized_global_agent_route(+ tmp_path: Path,+ placeholder_backend: str,+) -> None:+ db_path = tmp_path / "vibe.sqlite"+ service = SQLiteSessionsService(db_path)+ try:+ with service.engine.begin() as conn:+ scope_id = resolve_scope_from_legacy_key(+ conn, "avibe::project::proj_abc", now="2026-08-10T00:00:00Z"+ )+ assert scope_id is not None+ session_id = create_agent_session_row(+ conn,+ scope_id=scope_id,+ session_anchor="avibe_ses3",+ agent_backend=placeholder_backend,+ agent_variant="default",+ agent_name=None,+ model=None,+ reasoning_effort=None,+ native_session_id="",+ workdir=str(tmp_path),+ metadata={"created_via": "workbench"},+ )++ assert service.materialize_agent_session_route(+ session_id,+ model="gpt-5.4",+ reasoning_effort="high",+ expected_route={+ "agent_id": None,+ "agent_name": None,+ "agent_backend": placeholder_backend or None,+ "agent_variant": "default",+ "model": None,+ "reasoning_effort": None,+ "explicit_overrides": [],+ },+ )+ assert service.bind_agent_session_by_id(+ session_id=session_id,+ native_session_id="codex-native-1",+ vibe_agent_id="agent-codex",+ vibe_agent_name="codex",+ vibe_agent_backend="codex",+ ) == session_id++ row = service.get_agent_session_by_id(session_id)+ assert row is not None+ assert row["agent_backend"] == "codex"+ assert row["model"] == "gpt-5.4"+ assert row["reasoning_effort"] == "high"+ finally:+ service.close()++[email protected]("placeholder_backend", ["", "default", "unknown"])+def test_placeholder_backend_adoption_clears_non_workbench_route(+ tmp_path: Path,+ placeholder_backend: str,+) -> None:+ from storage.session_reclaim import SESSION_SETTINGS_OVERRIDE_KEY++ db_path = tmp_path / "vibe.sqlite"+ service = SQLiteSessionsService(db_path)+ try:+ with service.engine.begin() as conn:+ scope_id = resolve_scope_from_legacy_key(+ conn, "slack::channel::C123", now="2026-08-10T00:00:00Z"+ )+ assert scope_id is not None+ session_id = create_agent_session_row(+ conn,+ scope_id=scope_id,+ session_anchor="slack_123.456",+ agent_backend=placeholder_backend,+ agent_variant="default",+ agent_name=None,+ model="stale-model",+ reasoning_effort="high",+ native_session_id="",+ workdir=str(tmp_path),+ metadata={SESSION_SETTINGS_OVERRIDE_KEY: ["model", "reasoning_effort"]},+ )++ assert service.bind_agent_session_by_id(+ session_id=session_id,+ native_session_id="codex-native-im",+ vibe_agent_id="agent-codex",+ vibe_agent_name="codex",+ vibe_agent_backend="codex",+ ) == session_id++ row = service.get_agent_session_by_id(session_id)+ assert row is not None+ assert row["agent_backend"] == "codex"+ assert row["model"] is None+ assert row["reasoning_effort"] is None+ with service.engine.connect() as conn:+ metadata_json = conn.execute(+ select(agent_sessions.c.metadata_json).where(agent_sessions.c.id == session_id)+ ).scalar_one()+ assert SESSION_SETTINGS_OVERRIDE_KEY not in json.loads(metadata_json or "{}")+ finally:+ service.close()++[email protected]("raw_metadata_json", ["[]", '"legacy"'])+def test_backend_adoption_normalizes_non_object_route_metadata(+ tmp_path: Path,+ raw_metadata_json: str,+) -> None:+ db_path = tmp_path / "vibe.sqlite"+ service = SQLiteSessionsService(db_path)+ try:+ with service.engine.begin() as conn:+ scope_id = resolve_scope_from_legacy_key(+ conn, "slack::channel::C123", now="2026-08-10T00:00:00Z"+ )+ assert scope_id is not None+ session_id = create_agent_session_row(+ conn,+ scope_id=scope_id,+ session_anchor="slack_123.456",+ agent_backend="default",+ agent_variant="default",+ model="stale-model",+ reasoning_effort="high",+ native_session_id="",+ workdir=str(tmp_path),+ metadata={},+ )+ conn.execute(+ agent_sessions.update()+ .where(agent_sessions.c.id == session_id)+ .values(metadata_json=raw_metadata_json)+ )++ assert service.bind_agent_session_by_id(+ session_id=session_id,+ native_session_id="codex-native-im",+ vibe_agent_id="agent-codex",+ vibe_agent_name="codex",+ vibe_agent_backend="codex",+ ) == session_id++ row = service.get_agent_session_by_id(session_id)+ assert row is not None+ assert row["agent_backend"] == "codex"+ assert row["model"] is None+ assert row["reasoning_effort"] is None+ with service.engine.connect() as conn:+ metadata_json = conn.execute(+ select(agent_sessions.c.metadata_json).where(agent_sessions.c.id == session_id)+ ).scalar_one()+ assert json.loads(metadata_json or "{}") == {}+ finally:+ service.close()++def test_materialize_agent_session_route_never_fills_an_explicitly_pinned_field(tmp_path: Path,) -> None:diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 418babf71..69b21600f 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -93,6 +93,7 @@ import {transcriptSelectionActions,type SessionReadOnlyReason,} from './sessionArchived';+import { createSessionRowRefreshGate } from './sessionRowRefresh';import { InstallHint } from '../InstallHint';import { Badge } from '../ui/badge';import { Button } from '../ui/button';@@ -231,6 +232,7 @@ export const ChatPage: React.FC = () => {// Loaded session (null while bootstrapping — ChatPage renders a loader until// it's set). Lifted above the composer bridge + show-page logic that gate on it.const [session, setSession] = useState<WorkbenchSession | null>(null);+ const sessionRowRefreshGateRef = useRef(createSessionRowRefreshGate());// Archive is terminal: an archived transcript stays fully readable (search's// "include archived" opt-in links straight here) but every mutation is refused// server-side, so the chat renders read-only — no composer, no rename, no@@ -1007,16 +1009,10 @@ export const ChatPage: React.FC = () => {});}, []);- // The header's backend lock keys on ``native_session_id``, which the FIRST- // turn binds server-side with no dedicated event — so an open page wouldn't- // learn it until reload and the picker would keep offering switches the- // server now rejects (409). Until the native is known, refresh the row at- // the recovery points (turn end / reconnect / tab visible). No-op for the- // common already-bound session.- const hasNativeRef = useRef(false);- useEffect(() => {- hasNativeRef.current = Boolean(session?.native_session_id);- }, [session]);+ // The header's route and backend lock both come from the durable Session row.+ // Every settled turn refreshes it because turn start may materialize inherited+ // model / effort even on an already-bound legacy session. A missed turn.end is+ // recovered by syncTurnState, which refreshes the row when it clears stale work.// Read the global banner toggle once per mount (cached GET). Absent/failed →// default ON, so a transient prefs error never hides live background work.useEffect(() => {@@ -1037,28 +1033,34 @@ export const ChatPage: React.FC = () => {// can't stamp one chat's row onto the chat the user moved to. Best-effort by// contract: every caller must already be correct if the request never lands.const refreshSessionRow = useCallback(async () => {- const id = sessionIdRef.current;- if (!id) return;- try {- // cache:false — an earlier refresh (page open / reconnect) may have- // cached a stale row; reusing it inside the read cache's TTL is exactly- // what the callers are trying to escape.- const row = await api.getSession(id, { cache: false });- setSession((prev) => (prev && prev.id === row.id && row.id === sessionIdRef.current ? row : prev));- } catch {- // Best-effort: the next recovery point retries.- }+ const read = async (allowRetry: boolean): Promise<void> => {+ const id = sessionIdRef.current;+ if (!id) return;+ const isCurrent = await sessionRowRefreshGateRef.current.begin();+ try {+ // cache:false — an earlier refresh (page open / reconnect) may have+ // cached a stale row; reusing it inside the read cache's TTL is exactly+ // what the callers are trying to escape.+ const row = await api.getSession(id, { cache: false });+ setSession((prev) =>+ isCurrent() && row.id === sessionIdRef.current ? row : prev,+ );+ } catch {+ // If this was still the newest read, one bounded retry prevents a+ // transient failure from discarding an older route-bearing response+ // without turning a persistent outage into an unbounded loop.+ if (allowRetry && isCurrent() && id === sessionIdRef.current) {+ await read(false);+ }+ }+ };+ await read(true);}, [api]);- const refreshSessionRowUntilNativeBound = useCallback(async () => {- if (hasNativeRef.current) return;- await refreshSessionRow();- }, [refreshSessionRow]);-// ── Converging on a terminal archive this tab missed ────────────────────────//// A backgrounded / offline tab can miss the archive SSE for a session that- // already has a native_session_id, and refreshSessionRowUntilNativeBound then- // early-returns on every reconnect/focus — so a 409 ``session_archived`` from+ // already has a native_session_id, and the recovery row read still needs to+ // run on every reconnect/focus — so a 409 ``session_archived`` from// the FIRST write the user attempts is the only point at which this tab learns// the truth. Whichever write that is: sending, renaming, re-routing the agent,// forking a quote out, or any Show Page mutation. Converging per-verb is what@@ -1079,6 +1081,7 @@ export const ChatPage: React.FC = () => {showPageRequestRef.current += 1;setShowPageBusy(false);writeChatViewMode(archivedSessionId, 'chat');+ sessionRowRefreshGateRef.current.invalidate();setSession((prev) => markSessionArchived(prev, archivedSessionId));void refreshSessionRow();},@@ -1330,6 +1333,7 @@ export const ChatPage: React.FC = () => {if (turnEpochRef.current !== epochAtRequest) return;const sinceSet = Date.now() - workingSetAtRef.current;if (sinceSet > WORKING_SETTLE_GRACE_MS) {+ const recoveredDroppedTurnEnd = workingRef.current;workingRef.current = false;setWorking(false);// Agent Activity: the idle poll recovering a dropped terminal/turn.end is a@@ -1341,6 +1345,7 @@ export const ChatPage: React.FC = () => {dispatchLive({ type: 'settle' });scheduleActivityRefresh(false);}+ if (recoveredDroppedTurnEnd) void refreshSessionRow();} else if (graceResyncRef.current === null) {// Idle INSIDE the grace: either the registration gap (don't clear) or a// quick turn that already finished and whose turn.end we missed (a@@ -1354,7 +1359,7 @@ export const ChatPage: React.FC = () => {} catch {/* controller unreachable — leave the indicator as-is */}- }, [api, sessionId, markWorking, dispatchLive, scheduleActivityRefresh]);+ }, [api, sessionId, markWorking, dispatchLive, scheduleActivityRefresh, refreshSessionRow]);// Keep a ref to the latest syncTurnState so the grace-resync timer can call the// current closure without baking it into a dependency cycle.@@ -1370,10 +1375,17 @@ export const ChatPage: React.FC = () => {// Initial chat open needs the same recent tail window, queue, draft,// route/config state, and current turn state. Fetch them as one bootstrap// payload so remote links don't pay a tunnel round-trip per widget.+ const bootstrapIsCurrent = await sessionRowRefreshGateRef.current.begin();const bootstrap = await api.getSessionBootstrap(sessionId);// Dropped if the user switched chats while this load was in flight.if (sessionId !== sessionIdRef.current) return;- setSession(bootstrap.session);+ if (bootstrapIsCurrent()) {+ setSession(bootstrap.session);+ } else {+ // A newer turn-end/activity read won the row race. Keep its route-bearing+ // snapshot and repair a cold page if that read has not hydrated it yet.+ void refreshSessionRow();+ }setAgents(bootstrap.agents);setDefaultAgentName(bootstrap.default_agent_name);setMessageFontSize(normalizeChatMessageFontSize(bootstrap.config?.ui?.chat_message_font_size));@@ -1418,13 +1430,17 @@ export const ChatPage: React.FC = () => {// its own loading state into a premature not-found / error view (Codex P2).if (sessionId === sessionIdRef.current) setLoading(false);}- }, [api, sessionId, markWorking, scheduleActivityRefresh]);+ }, [api, sessionId, markWorking, scheduleActivityRefresh, refreshSessionRow]);// Clear per-session state the instant the session changes (React Router swaps// only :sessionId, reusing this instance), before the new session's// load/subscribe — so the previous conversation / queue / draft never leak in// and the merge in ``refresh`` only ever unions same-session rows.useEffect(() => {+ // The gate is session-scoped. A PATCH for the previous chat may still be+ // pending after navigation, but it must never hold the new chat's bootstrap+ // or recovery reads hostage.+ sessionRowRefreshGateRef.current = createSessionRowRefreshGate();// Clear ``session`` too (not just messages/queue/draft): otherwise the header// keeps rendering the previous chat's title + agent picker until the new load// finishes, and a rename / agent change would patch() the STALE session.id@@ -1568,11 +1584,10 @@ export const ChatPage: React.FC = () => {dispatchLive({ type: 'settle' });scheduleActivityRefresh(false);}- // The first turn binds the native; pick it up so the header's backend- // lock engages without a reload. A failed first turn leaves no native- // (the refresh confirms that), keeping the backend switchable so the- // user can recover by re-routing.- void refreshSessionRowUntilNativeBound();+ // Turn start can materialize an inherited route even on an already-+ // bound legacy session. Reload the authoritative row on every settle+ // so the header picks up both that route and a first native bind.+ void refreshSessionRow();void syncTurnState();}},@@ -1597,10 +1612,16 @@ export const ChatPage: React.FC = () => {if (data.session_id !== sessionIdRef.current || data.event !== 'updated') return;if (!Object.prototype.hasOwnProperty.call(data, 'title')) return;const nextTitle = data.title ?? null;+ sessionRowRefreshGateRef.current.invalidate();setSession((prev) => {if (!prev || prev.id !== data.session_id || prev.title === nextTitle) return prev;return { ...prev, title: nextTitle };});+ // The activity event carries only a partial Session projection. Its+ // title is newer than an in-flight full-row read, but it cannot replace+ // that read's native bind or materialized route, so retry after the+ // invalidation and converge on the complete committed row.+ void refreshSessionRow();},onConnected: () => {// Every (re)connect recovers any state missed while the socket was down:@@ -1609,7 +1630,7 @@ export const ChatPage: React.FC = () => {void reconcile();void refreshQueue();void syncTurnState({ quiet: true });- void refreshSessionRowUntilNativeBound();+ void refreshSessionRow();},onConnectionState: (state) => {const connected = state === 'connected';@@ -1622,7 +1643,7 @@ export const ChatPage: React.FC = () => {},});return disconnect;- }, [api, sessionId, appendMessage, reconcile, refreshQueue, syncTurnState, refreshSessionRowUntilNativeBound, markWorking, goBack, ingestActivityRow, scheduleActivityRefresh, dispatchLive]);+ }, [api, sessionId, appendMessage, reconcile, refreshQueue, syncTurnState, refreshSessionRow, markWorking, goBack, ingestActivityRow, scheduleActivityRefresh, dispatchLive]);// Mobile tabs (the common case for IM users) get backgrounded mid-turn; the// SSE feed can be suspended without a clean reconnect, dropping the reply.@@ -1637,6 +1658,7 @@ export const ChatPage: React.FC = () => {void reconcile();void refreshQueue();void syncTurnState({ quiet: true });+ void refreshSessionRow();};document.addEventListener('visibilitychange', resync);window.addEventListener('online', resync);@@ -1646,7 +1668,7 @@ export const ChatPage: React.FC = () => {window.removeEventListener('online', resync);window.removeEventListener('focus', resync);};- }, [sessionId, reconcile, refreshQueue, syncTurnState]);+ }, [sessionId, reconcile, refreshQueue, syncTurnState, refreshSessionRow]);useEffect(() => {setRuntimeState((current) => ({ ...current, pending_input_count: queue.length }));@@ -2266,15 +2288,12 @@ export const ChatPage: React.FC = () => {async (changes: Partial<WorkbenchSession>) => {if (!session) return;const patchedId = session.id;+ const finishPatch = sessionRowRefreshGateRef.current.beginMutation();try {- const updated = await api.updateSession(session.id, changes as any);- // Drop a stale response after a chat switch: if the user navigated to a- // different chat (this ChatPage instance is reused) before the PATCH- // resolved, installing A's session into B would show A's title/picker on- // B and make later edits patch the wrong session.id (Codex P2). Mirrors- // the sessionIdRef guards on send/cancel.- if (patchedId !== sessionIdRef.current) return;- setSession(updated);+ await api.updateSession(session.id, changes as any);+ // Do not install the PATCH response: it is only a mutation snapshot and+ // can be older than another committed write. The authoritative refresh+ // in finally is guarded by session id and runs after every active write.} catch (err) {if (patchedId !== sessionIdRef.current) return;// The archive itself has already converged through the shared@@ -2284,9 +2303,12 @@ export const ChatPage: React.FC = () => {// ``handleApiError`` resolved is Show-Page-worded, which is wrong for a// rename or a re-route.setError(isSessionArchivedError(err) ? t('chat.archived.editBlocked') : (errorMessage(err) ?? String(err)));+ } finally {+ finishPatch();+ if (patchedId === sessionIdRef.current) void refreshSessionRow();}},- [api, session, t],+ [api, session, t, refreshSessionRow],);// Session-level actions share the sidebar/mobile row model. The chat header@@ -2306,8 +2328,15 @@ export const ChatPage: React.FC = () => {onArchived: () => navigate('/inbox'),// The provider cache feeds the sidebar, not this page's own session copy. The// write resolves after an await, so only patch if we're still on that session.- onSessionPatched: (changes, sessionId) =>- setSession((prev) => (prev && prev.id === sessionId ? { ...prev, ...changes } : prev)),+ onSessionPatched: (changes, sessionId) => {+ if (sessionId !== sessionIdRef.current) return;+ sessionRowRefreshGateRef.current.invalidate();+ setSession((prev) => (prev && prev.id === sessionId ? { ...prev, ...changes } : prev));+ // Pin updates only carry the changed sidebar field. A successful PATCH can+ // race a turn-end row read, so re-read the complete durable projection to+ // keep any newly materialized route in the header.+ void refreshSessionRow();+ },archiveHint: ARCHIVE_SHORTCUT_LABEL,});diff --git a/ui/src/components/workbench/sessionRowRefresh.test.ts b/ui/src/components/workbench/sessionRowRefresh.test.tsnew file mode 100644index 000000000..f6f9da9f5--- /dev/null+++ b/ui/src/components/workbench/sessionRowRefresh.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from 'vitest';++import { createSessionRowRefreshGate } from './sessionRowRefresh';++describe('Session-row refresh ordering', () => {+ it('accepts only the newest overlapping read', async () => {+ const gate = createSessionRowRefreshGate();+ const firstRead = gate.begin();+ const secondRead = gate.begin();+ const firstReadIsCurrent = await firstRead;+ const secondReadIsCurrent = await secondRead;++ expect(firstReadIsCurrent()).toBe(false);+ expect(secondReadIsCurrent()).toBe(true);+ });++ it('rejects a read after a newer event or mutation is observed', async () => {+ const gate = createSessionRowRefreshGate();+ const readIsCurrent = await gate.begin();++ gate.invalidate();+ const retryIsCurrent = await gate.begin();++ expect(readIsCurrent()).toBe(false);+ expect(retryIsCurrent()).toBe(true);+ });++ it('holds reads until every overlapping mutation settles', async () => {+ const gate = createSessionRowRefreshGate();+ const finishFirst = gate.beginMutation();+ const finishSecond = gate.beginMutation();+ let readStarted = false;+ const read = gate.begin().then(() => {+ readStarted = true;+ });++ await Promise.resolve();+ expect(readStarted).toBe(false);+ finishFirst();+ await Promise.resolve();+ expect(readStarted).toBe(false);+ finishSecond();+ await read;+ expect(readStarted).toBe(true);+ });+});diff --git a/ui/src/components/workbench/sessionRowRefresh.ts b/ui/src/components/workbench/sessionRowRefresh.tsnew file mode 100644index 000000000..aa7f01025--- /dev/null+++ b/ui/src/components/workbench/sessionRowRefresh.ts@@ -0,0 +1,44 @@+// Orders best-effort Session-row reads against every newer local observation.+// Reads wait for in-flight mutations to settle; a push event or mutation then+// invalidates every read that began before that newer state was observed.+export type SessionRowRefreshGate = {+ begin: () => Promise<() => boolean>;+ beginMutation: () => () => void;+ invalidate: () => void;+};++export const createSessionRowRefreshGate = (): SessionRowRefreshGate => {+ let generation = 0;+ let activeMutations = 0;+ let mutationWaiters: Array<() => void> = [];++ const waitForMutations = (): Promise<void> => {+ if (activeMutations === 0) return Promise.resolve();+ return new Promise((resolve) => mutationWaiters.push(resolve));+ };++ return {+ begin: async () => {+ while (activeMutations > 0) await waitForMutations();+ const requestGeneration = ++generation;+ return () => requestGeneration === generation;+ },+ beginMutation: () => {+ activeMutations += 1;+ generation += 1;+ let finished = false;+ return () => {+ if (finished) return;+ finished = true;+ activeMutations -= 1;+ if (activeMutations !== 0) return;+ const waiters = mutationWaiters;+ mutationWaiters = [];+ waiters.forEach((resolve) => resolve());+ };+ },+ invalidate: () => {+ generation += 1;+ },+ };+};