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
refactor(im): one backend-neutral channel route form, giving Vibey its model and effort choice (#2938)
Call White36a4afeb3818
diff --git a/core/auth.py b/core/auth.pyindex e9fb906ad..d8bfc2bf1 100644--- a/core/auth.py+++ b/core/auth.py@@ -40,9 +40,10 @@ BIND_EXEMPT_COMMANDS: frozenset = frozenset({"bind"})def _is_admin_protected(action: str) -> bool:"""Check if an action requires admin permission.- Handles both exact matches and prefix matches (e.g. ``vibe_update_now:v1.2``).+ Handles exact matches and a protected action with a ``:`` suffix (e.g. ``vibe_update_now:v1.2``,+ ``routing_submit:claude``), so a dynamic suffix never sheds the protection of the action it names."""- if action in ADMIN_PROTECTED_ACTIONS:+ if action in ADMIN_PROTECTED_ACTIONS or action.partition(":")[0] in ADMIN_PROTECTED_ACTIONS:return True# Prefix match for actions with dynamic suffixesif action.startswith("vibe_update_now"):diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex e1752e5f2..be4ffadf7 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -5903,6 +5903,17 @@ class ModelHubService:config, self._agent(config, backend), live_recovery=self.recovery.annotations(config),)+ async def read_agent_sources(self, backend: str) -> dict:+ """``get_agent_sources`` for a caller on the controller loop, which owns the recovery state.++ Reading that state may wake its waiters, so it is read here; the config read and the payload are+ built off the loop.+ """+ config = await asyncio.to_thread(self.store.load)+ agent = self._agent(config, backend)+ live_recovery = self.recovery.annotations(config)+ return await asyncio.to_thread(self._agent_payload, config, agent, live_recovery=live_recovery)+async def set_agent_chain(self, backend: str, model_id: object, payload: object) -> dict:if (backend not in MODEL_HUB_BACKENDSdiff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.pyindex bdded22df..a632a3b93 100644--- a/core/handlers/settings_handler.py+++ b/core/handlers/settings_handler.py@@ -2,6 +2,7 @@import asyncioimport logging+import sysfrom typing import Optionalfrom modules.agents import get_agent_display_name@@ -13,7 +14,15 @@ from modules.agents.catalog import (is_builtin_backend,)from modules.im import MessageContext, InlineKeyboard, InlineButton-from core.modals import RoutingModalData, RoutingModalSelection+from config.v2_settings import normalize_routing_settings+from core.modals import (+ DEFAULT_OPTION_VALUE,+ STORED_OPTION_VALUE,+ BackendRouteMenu,+ RouteOption,+ RoutingModalData,+ RoutingModalSelection,+)from vibe import backend_model_catalogfrom .base import BaseHandler@@ -23,6 +32,20 @@ logger = logging.getLogger(__name__)_UNSET = object()+def _unique_options(values) -> list[RouteOption]:+ names = dict.fromkeys(str(value).strip() for value in values if value and str(value).strip())+ return [RouteOption(name, name) for name in names]+++def _effort_options(entries) -> list[RouteOption]:+ """Catalog effort entries as route options, without the Default entry every select adds itself."""+ return [+ RouteOption(str(entry["value"]), str(entry.get("label") or entry["value"]))+ for entry in entries or []+ if entry.get("value") and entry["value"] != DEFAULT_OPTION_VALUE+ ]++class SettingsHandler(BaseHandler):"""Handles settings and configuration operations"""@@ -403,21 +426,51 @@ class SettingsHandler(BaseHandler):"""Handle routing command - show agent/model selection"""try:platform = context.platform or (context.platform_specific or {}).get("platform") or self.config.platform- # Only Slack has modal support for now+ im_client = self._get_im_client(context)+ if not hasattr(im_client, "open_routing_modal"):+ await im_client.send_message(context, self._t("routing.slackOnly"))+ return+ platform_specific = context.platform_specific or {}if platform == "slack":- await self._handle_routing_slack(context)+ # A Slack modal opens only from an interaction; a typed command gets a button that is one.+ trigger = platform_specific.get("trigger_id")+ if not trigger:+ keyboard = InlineKeyboard(+ buttons=[+ [+ InlineButton(+ text=f"🤖 {self._t('button.agentSettings')}",+ callback_data="open_routing_modal",+ )+ ]+ ]+ )+ await im_client.send_message_with_buttons(+ context,+ f"🤖 *{self._t('routing.introTitle')}*\n\n{self._t('routing.introDesc')}",+ keyboard,+ )+ returnelif platform == "discord":- await self._handle_routing_discord(context)- elif platform == "telegram":- await self._handle_routing_telegram(context)- elif platform == "lark":- await self._handle_routing_lark(context)+ trigger = platform_specific.get("interaction") or contextelse:- # For other platforms, show a simple message- await self._get_im_client(context).send_message(- context,- self._t("routing.slackOnly"),+ trigger = context+ # A form refreshed through ``update_routing_modal`` loads each backend as it is shown; the others+ # render every backend up front.+ routing_data = await self._gather_routing_modal_data(+ context, include_all_backend_data=not hasattr(im_client, "update_routing_modal")+ )+ try:+ await im_client.run_on_client_loop(+ im_client.open_routing_modal(+ trigger_id=trigger,+ channel_id=context.channel_id,+ routing=routing_data,+ ))+ except Exception as e:+ logger.error(f"Error opening routing modal: {e}", exc_info=True)+ await im_client.send_message(context, f"❌ {self._t('error.routingModalFailed')}")except Exception as e:logger.error(f"Error showing routing settings: {e}", exc_info=True)await self._get_im_client(context).send_message(@@ -430,7 +483,7 @@ class SettingsHandler(BaseHandler):selected_backend: Optional[str] = None,include_all_backend_data: bool = False,) -> RoutingModalData:- """Collect backend/agent/model data for routing modal renderers."""+ """Collect each shown backend's route menu for the routing form renderers."""settings_key = self._get_settings_key(context)current_routing = self._get_settings_manager(context).get_channel_routing(settings_key)@@ -449,92 +502,157 @@ class SettingsHandler(BaseHandler):if selected_backend in registered_backends:active_backend = selected_backendvisible_current_backend = current_backend if current_backend in registered_backends else active_backend- backends_to_load = set(registered_backends) if include_all_backend_data else {active_backend}-- opencode_agents = []- opencode_models = {}- opencode_default_config = {}- claude_agents = []- claude_models = []- codex_agents = []- codex_models = []- backend_reasoning_options = {}-- if "opencode" in backends_to_load:- try:- opencode_agent = self.controller.agent_service.agents.get("opencode")- if opencode_agent and hasattr(opencode_agent, "current_server"):- async with opencode_agent.current_server() as server: # type: ignore[attr-defined]- cwd = self.controller.get_cwd(context)- opencode_agents = await server.get_available_agents(cwd)- model_hub_service = getattr(- self.controller,- "model_hub_service",- None,- )- public_models = (- model_hub_service.opencode_public_models()- if model_hub_service is not None- else None- )- if public_models is None:- opencode_models = await server.get_available_models(cwd)- else:- opencode_models = await server.get_available_models(- cwd,- model_hub_models=public_models,- )- opencode_default_config = await server.get_default_config(cwd)- except Exception as e:- logger.warning(f"Failed to fetch OpenCode data: {e}")+ backends_to_load = registered_backends if include_all_backend_data else [active_backend]- if "claude" in backends_to_load:- try:- from vibe.api import claude_agents as get_claude_agents, claude_models as get_claude_models-- cwd = self.controller.get_cwd(context)- agents_result = get_claude_agents(cwd)- if agents_result.get("ok"):- claude_agents = agents_result.get("agents", [])- models_result = await asyncio.to_thread(get_claude_models)- if models_result.get("ok"):- claude_models = models_result.get("models", [])- reasoning_options = models_result.get("reasoning_options")- if isinstance(reasoning_options, dict):- backend_reasoning_options["claude"] = reasoning_options- except Exception as e:- logger.warning(f"Failed to fetch Claude data: {e}")-- if "codex" in backends_to_load:- try:- from vibe.api import codex_agents as get_codex_agents, codex_models as get_codex_models-- models_result = await asyncio.to_thread(get_codex_models)- if models_result.get("ok"):- codex_models = models_result.get("models", [])- reasoning_options = models_result.get("reasoning_options")- if isinstance(reasoning_options, dict):- backend_reasoning_options["codex"] = reasoning_options- cwd = self.controller.get_cwd(context)- agents_result = get_codex_agents(cwd)- if agents_result.get("ok"):- codex_agents = agents_result.get("agents", [])- except Exception as e:- logger.warning(f"Failed to fetch Codex data: {e}")-- return RoutingModalData(+ data = RoutingModalData(registered_backends=registered_backends,current_backend=visible_current_backend,current_routing=current_routing,- opencode_agents=opencode_agents,- opencode_models=opencode_models,- opencode_default_config=opencode_default_config,- claude_agents=claude_agents,- claude_models=claude_models,- codex_agents=codex_agents,- codex_models=codex_models,- backend_reasoning_options=backend_reasoning_options,)+ im_client = self._get_im_client(context)+ for backend in backends_to_load:+ menu = BackendRouteMenu(+ backend,+ option_limit=getattr(im_client, "route_option_limit", None),+ value_limit=getattr(im_client, "route_option_value_limit", None),+ stored=data.stored_draft(backend),+ )+ loader = self._route_menu_loaders.get(backend)+ if loader is not None:+ try:+ await loader(self, context, menu, menu.stored.model)+ except Exception as e:+ logger.warning("Failed to load %s routing options: %s", backend, e)+ data.menus[backend] = menu+ return data++ # Where each backend's route lists come from: the only backend-specific part of the routing form. Each+ # loader fills ``menu`` in place; ``stored_model`` is the stored route's model when this is its backend.++ async def _load_opencode_route_menu(self, context, menu: BackendRouteMenu, stored_model: Optional[str]) -> None:+ from modules.agents.opencode.utils import (+ build_opencode_model_option_items,+ build_reasoning_effort_options,+ resolve_opencode_allowed_providers,+ resolve_opencode_provider_preferences,+ )++ opencode_agent = self.controller.agent_service.agents.get("opencode")+ if not opencode_agent or not hasattr(opencode_agent, "current_server"):+ return+ async with opencode_agent.current_server() as server: # type: ignore[attr-defined]+ cwd = self.controller.get_cwd(context)+ agents = await server.get_available_agents(cwd)+ model_hub_service = getattr(self.controller, "model_hub_service", None)+ public_models = model_hub_service.opencode_public_models() if model_hub_service is not None else None+ if public_models is None:+ models = await server.get_available_models(cwd)+ else:+ models = await server.get_available_models(cwd, model_hub_models=public_models)+ default_config = await server.get_default_config(cwd)+ menu.variants = _unique_options(+ agent.get("name") if isinstance(agent, dict) else agent for agent in agents or []+ )+ # OpenCode spreads a select's cap over its providers, so the list is built for the select that shows it,+ # without the values it cannot carry; a platform without a cap (a paged picker) gets every model.+ entries = build_opencode_model_option_items(+ models,+ max_total=(menu.option_limit - 1) if menu.option_limit else sys.maxsize,+ preferred_providers=resolve_opencode_provider_preferences(default_config, stored_model),+ allowed_providers=resolve_opencode_allowed_providers(default_config, models),+ keep=menu.fits,+ )+ menu.models = [RouteOption(str(entry["value"]), str(entry["label"])) for entry in entries if entry.get("value")]+ for model in {"", *(option.value for option in menu.models), stored_model or ""}:+ menu.efforts[model] = _effort_options(build_reasoning_effort_options(models, model or None))++ async def _load_claude_route_menu(self, context, menu: BackendRouteMenu, stored_model: Optional[str]) -> None:+ from modules.agents.opencode.utils import (+ build_claude_reasoning_options,+ format_claude_model_label,+ resolve_model_reasoning_options,+ )+ from vibe.api import claude_agents as get_claude_agents, claude_models as get_claude_models+ from vibe.claude_model_catalog import DEFAULT_CLAUDE_MODEL_ALIASES++ agents_result = get_claude_agents(self.controller.get_cwd(context))+ if agents_result.get("ok"):+ menu.variants = _unique_options(agent.get("id") for agent in agents_result.get("agents", []))+ models_result = await asyncio.to_thread(get_claude_models)+ if not models_result.get("ok"):+ return+ models = [str(model) for model in models_result.get("models", []) if model]+ # The bare aliases are always valid and the most useful, so a capped select trims dated snapshots first.+ aliases = [alias for alias in DEFAULT_CLAUDE_MODEL_ALIASES if alias in models]+ ordered = aliases + [model for model in models if model not in aliases]+ menu.models = [RouteOption(model, format_claude_model_label(model)) for model in ordered]+ catalog = models_result.get("reasoning_options")+ catalog = catalog if isinstance(catalog, dict) else None+ for model in {"", *ordered, stored_model or ""}:+ menu.efforts[model] = _effort_options(+ resolve_model_reasoning_options(catalog, model, build_claude_reasoning_options(model or None))+ )++ async def _load_codex_route_menu(self, context, menu: BackendRouteMenu, stored_model: Optional[str]) -> None:+ from modules.agents.opencode.utils import build_codex_reasoning_options, resolve_model_reasoning_options+ from vibe.api import codex_agents as get_codex_agents, codex_models as get_codex_models++ models_result = await asyncio.to_thread(get_codex_models)+ agents_result = get_codex_agents(self.controller.get_cwd(context))+ if agents_result.get("ok"):+ menu.variants = _unique_options(agent.get("id") for agent in agents_result.get("agents", []))+ if not models_result.get("ok"):+ return+ models = [str(model) for model in models_result.get("models", []) if model]+ menu.models = [RouteOption(model, model) for model in models]+ catalog = models_result.get("reasoning_options")+ catalog = catalog if isinstance(catalog, dict) else None+ for model in {"", *models, stored_model or ""}:+ menu.efforts[model] = _effort_options(+ resolve_model_reasoning_options(catalog, model, build_codex_reasoning_options())+ )++ async def _load_vibey_route_menu(self, context, menu: BackendRouteMenu, stored_model: Optional[str]) -> None:+ """Vibey's menu from Model Hub, as the Web route picker reads it.++ An effort Model Hub's ``effort_menu`` omits would only fail, so it is not offered. A route without its+ own model inherits the built-in Vibey Agent's, so ``""`` holds that model's efforts.+ """+ model_hub_service = getattr(self.controller, "model_hub_service", None)+ if model_hub_service is None:+ return+ catalog = (await model_hub_service.read_agent_sources("vibey")).get("catalog_models") or []+ for row in catalog:+ model_id = str(row.get("id") or "").strip()+ if not model_id or row.get("routeable") is False or model_id in menu.efforts:+ continue+ omitted = set((row.get("effort_menu") or {}).get("omitted") or [])+ menu.models.append(RouteOption(model_id, str(row.get("display_name") or model_id)))+ menu.efforts[model_id] = (+ []+ if row.get("supports_reasoning") is False+ else [+ RouteOption(effort, effort)+ for effort in dict.fromkeys(row.get("reasoning_efforts") or [])+ if effort not in omitted+ ]+ )+ store = getattr(self.controller, "vibe_agent_store", None)+ agent = (+ await asyncio.to_thread(store.get_builtin_default_agent_for_backend, "vibey", enabled_only=False)+ if store+ else None+ )+ inherited = menu.efforts.get(str(getattr(agent, "model", None) or "").strip())+ if inherited is not None:+ menu.efforts[""] = inherited++ _route_menu_loaders = {+ "opencode": _load_opencode_route_menu,+ "claude": _load_claude_route_menu,+ "codex": _load_codex_route_menu,+ "vibey": _load_vibey_route_menu,+ }def _is_backend_enabled(self, backend: str) -> bool:if is_builtin_backend(backend):@@ -585,13 +703,8 @@ class SettingsHandler(BaseHandler):def _routing_target_from_settings(self, routing) -> tuple[str, str, str, str, str]:agent_name = str(getattr(routing, "agent_name", None) or "").strip()backend = str(self._resolve_route_backend(agent_name) or agent_name).strip()- variant = ""- if backend == "opencode":- variant = str(getattr(routing, "opencode_agent", None) or "").strip()- elif backend == "claude":- variant = str(getattr(routing, "claude_agent", None) or "").strip()- elif backend == "codex":- variant = str(getattr(routing, "codex_agent", None) or "").strip()+ variant = getattr(routing, f"{backend}_agent", None) if backend in NATIVE_CLI_BACKENDS else None+ variant = str(variant or "").strip()return (agent_name,backend,@@ -610,97 +723,6 @@ class SettingsHandler(BaseHandler):next_backend = next_target[1]return bool(current_backend and next_backend and current_backend != next_backend)- async def _handle_routing_slack(self, context: MessageContext):- """Handle routing for Slack using modal dialog"""- im_client = self._get_im_client(context)- trigger_id = context.platform_specific.get("trigger_id") if context.platform_specific else None-- if not trigger_id:- # No trigger_id, show button to open modal- buttons = [- [- InlineButton(- text=f"🤖 {self._t('button.agentSettings')}",- callback_data="open_routing_modal",- )- ]- ]- keyboard = InlineKeyboard(buttons=buttons)- await im_client.send_message_with_buttons(- context,- f"🤖 *{self._t('routing.introTitle')}*\n\n{self._t('routing.introDesc')}",- keyboard,- )- return-- routing_data = await self._gather_routing_modal_data(context)-- # Open modal- try:- await im_client.run_on_client_loop(- im_client.open_routing_modal(- trigger_id=trigger_id,- channel_id=context.channel_id,- **routing_data.as_kwargs(),- )- )- except Exception as e:- logger.error(f"Error opening routing modal: {e}", exc_info=True)- await im_client.send_message(context, f"❌ {self._t('error.routingModalFailed')}")-- async def _handle_routing_discord(self, context: MessageContext):- im_client = self._get_im_client(context)- interaction = context.platform_specific.get("interaction") if context.platform_specific else None- routing_data = await self._gather_routing_modal_data(context, include_all_backend_data=True)-- try:- await im_client.run_on_client_loop(- im_client.open_routing_modal(- trigger_id=interaction or context,- channel_id=context.channel_id,- **routing_data.as_kwargs(),- )- )- except Exception as e:- logger.error(f"Error opening routing modal: {e}", exc_info=True)- await im_client.send_message(context, f"❌ {self._t('error.routingModalFailed')}")-- async def _handle_routing_telegram(self, context: MessageContext):- im_client = self._get_im_client(context)- routing_data = await self._gather_routing_modal_data(context, include_all_backend_data=True)- try:- await im_client.run_on_client_loop(- im_client.open_routing_modal(- trigger_id=context,- channel_id=context.channel_id,- **routing_data.as_kwargs(),- )- )- except Exception as e:- logger.error(f"Error opening Telegram routing flow: {e}", exc_info=True)- await im_client.send_message(context, f"❌ {self._t('error.routingModalFailed')}")-- async def _handle_routing_lark(self, context: MessageContext):- """Handle routing for Lark/Feishu using interactive form card.-- Gathers the same backend/model/agent data as Slack/Discord so the- Feishu card can display selectors for all available options.- """- im_client = self._get_im_client(context)- routing_data = await self._gather_routing_modal_data(context, include_all_backend_data=True)-- try:- await im_client.run_on_client_loop(- im_client.open_routing_modal(- trigger_id=context,- channel_id=context.channel_id,- **routing_data.as_kwargs(),- )- )- except Exception as e:- logger.error(f"Error opening routing card for Lark: {e}", exc_info=True)- await im_client.send_message(context, f"❌ {self._t('error.routingModalFailed')}")-async def handle_settings_update(self,user_id: str,@@ -806,11 +828,10 @@ class SettingsHandler(BaseHandler):resolved_backend = self.controller.resolve_agent_for_context(context)selected_backend = selection.selected_backend or resolved_backendrouting_data = await self._gather_routing_modal_data(context, selected_backend=selected_backend)- current_routing = routing_data.current_routing- registered_backends = routing_data.registered_backends- current_backend = routing_data.current_backendvisible_selected_backend = (- selected_backend if selected_backend in registered_backends else current_backend+ selected_backend+ if selected_backend in routing_data.registered_backends+ else routing_data.current_backend)if hasattr(im_client, "update_routing_modal"):@@ -818,27 +839,10 @@ class SettingsHandler(BaseHandler):view_id=view_id,view_hash=view_hash,channel_id=resolved_channel_id,- registered_backends=registered_backends,- current_backend=current_backend,- current_routing=current_routing,- opencode_agents=routing_data.opencode_agents,- opencode_models=routing_data.opencode_models,- opencode_default_config=routing_data.opencode_default_config,- claude_agents=routing_data.claude_agents,- claude_models=routing_data.claude_models,- codex_agents=routing_data.codex_agents,- codex_models=routing_data.codex_models,- backend_reasoning_options=routing_data.backend_reasoning_options,+ routing=routing_data,selected_backend=visible_selected_backend,- selected_opencode_agent=selection.selected_opencode_agent,- selected_opencode_model=selection.selected_opencode_model,- selected_opencode_reasoning=selection.selected_opencode_reasoning,- selected_claude_agent=selection.selected_claude_agent,- selected_claude_model=selection.selected_claude_model,- selected_claude_reasoning=selection.selected_claude_reasoning,- selected_codex_agent=selection.selected_codex_agent,- selected_codex_model=selection.selected_codex_model,- selected_codex_reasoning=selection.selected_codex_reasoning,+ # A backend switch shows a section the form had no controls for: the stored route, not blanks.+ draft=selection.draft if visible_selected_backend == selected_backend else None,)except Exception as e:logger.error(f"Error updating routing modal: {e}", exc_info=True)@@ -848,22 +852,20 @@ class SettingsHandler(BaseHandler):user_id: str,channel_id: str,backend: str,- opencode_agent: Optional[str],- opencode_model: Optional[str],*,+ variant: object = _UNSET,+ model: Optional[str] = None,+ reasoning_effort: Optional[str] = None,thread_id: Optional[str] = None,- opencode_reasoning_effort: Optional[str] = None,- claude_agent: Optional[str] = None,- claude_model: Optional[str] = None,- claude_reasoning_effort: Optional[str] = None,- codex_agent: object = _UNSET,- codex_model: Optional[str] = None,- codex_reasoning_effort: Optional[str] = None,notify_user: bool = True,is_dm: bool = False,platform: Optional[str] = None,):- """Handle routing update submission (from modal)."""+ """Save a routing form's choices for one backend.++ ``variant`` is the backend's native agent; omitted, the stored one stays. Other backends' native agents+ always stay, so switching back finds them.+ """from config.v2_settings import RoutingSettingsfrom modules.agents.opencode.utils import normalize_claude_reasoning_effort@@ -879,74 +881,52 @@ class SettingsHandler(BaseHandler):im_client = self._get_im_client(context)settings_manager = self._get_settings_manager(context)existing_routing = settings_manager.get_channel_routing(settings_key)- normalized_claude_reasoning_effort = normalize_claude_reasoning_effort(- claude_model,- claude_reasoning_effort,- backend_model_catalog.catalog_reasoning_efforts_for_model("claude", claude_model),- )- if backend == "codex" and codex_agent is _UNSET:- resolved_codex_agent = existing_routing.codex_agent if existing_routing else None- else:- resolved_codex_agent = codex_agent+ # A platform shows a stored choice it cannot carry as its own option value through a stand-in option;+ # saving that option keeps the stored choice. It stands for this backend's route only: one changed to+ # another backend since the form rendered has no such choice, so the stand-in saves as Default.+ stored = normalize_routing_settings(existing_routing)+ if self._resolve_route_backend(stored.agent_name) != backend:+ stored = normalize_routing_settings(None)+ if model == STORED_OPTION_VALUE:+ model = stored.model+ if reasoning_effort == STORED_OPTION_VALUE:+ reasoning_effort = stored.reasoning_effort+ if variant == STORED_OPTION_VALUE:+ variant = _UNSET+ variants = {+ native: getattr(existing_routing, f"{native}_agent", None) if existing_routing else None+ for native in NATIVE_CLI_BACKENDS+ }+ if backend in variants and variant is not _UNSET:+ variants[backend] = variant+ if backend == "claude":+ # Claude Code rejects an effort its model does not support.+ reasoning_effort = normalize_claude_reasoning_effort(+ model,+ reasoning_effort,+ backend_model_catalog.catalog_reasoning_efforts_for_model("claude", model),+ )routing = RoutingSettings(agent_name=self._routing_agent_name(backend),- model=(- opencode_model- if backend == "opencode"- else claude_model- if backend == "claude"- else codex_model- if backend == "codex"- else None- ),- reasoning_effort=(- opencode_reasoning_effort- if backend == "opencode"- else normalized_claude_reasoning_effort- if backend == "claude"- else codex_reasoning_effort- if backend == "codex"- else None- ),- opencode_agent=opencode_agent- if backend == "opencode"- else (existing_routing.opencode_agent if existing_routing else None),- claude_agent=claude_agent- if backend == "claude"- else (existing_routing.claude_agent if existing_routing else None),- codex_agent=resolved_codex_agent- if backend == "codex"- else (existing_routing.codex_agent if existing_routing else None),+ model=model,+ reasoning_effort=reasoning_effort,+ **{f"{native}_agent": value for native, value in variants.items()},)settings_manager.set_channel_routing(settings_key, routing)needs_new_session_hint = self._routing_update_needs_new_session_hint(context, routing)parts = [f"{self._t('routing.label.backend')}: **{display_name_for_backend(backend)}**"]- if backend == "opencode":- if opencode_agent:- parts.append(f"{self._t('routing.label.agent')}: **{opencode_agent}**")- if opencode_model:- parts.append(f"{self._t('routing.label.model')}: **{opencode_model}**")- if opencode_reasoning_effort:- parts.append(f"{self._t('routing.label.reasoningEffort')}: **{opencode_reasoning_effort}**")- elif backend == "claude":- if claude_agent:- parts.append(f"{self._t('routing.label.agent')}: **{claude_agent}**")- if claude_model:- parts.append(f"{self._t('routing.label.model')}: **{claude_model}**")- if normalized_claude_reasoning_effort:- parts.append(- f"{self._t('routing.label.reasoningEffort')}: **{normalized_claude_reasoning_effort}**"- )- elif backend == "codex":- if resolved_codex_agent:- parts.append(f"{self._t('routing.label.agent')}: **{resolved_codex_agent}**")- if codex_model:- parts.append(f"{self._t('routing.label.model')}: **{codex_model}**")- if codex_reasoning_effort:- parts.append(f"{self._t('routing.label.reasoningEffort')}: **{codex_reasoning_effort}**")+ for label_key, value in (+ ("routing.label.agent", variants.get(backend)),+ ("routing.label.model", model),+ ("routing.label.reasoningEffort", reasoning_effort),+ ):+ if value:+ # Route values are opaque and unbounded; a confirmation must fit any platform's message.+ shown = value if len(value) <= 100 else f"{value[:99]}…"+ parts.append(f"{self._t(label_key)}: **{shown}**")if needs_new_session_hint:parts.extend(["", self._t("success.routingUpdateNeedsNewSession")])@@ -958,12 +938,8 @@ class SettingsHandler(BaseHandler):)logger.info(- f"Routing updated for {settings_key}: backend={backend}, "- f"opencode_agent={opencode_agent}, opencode_model={opencode_model}, "- f"claude_agent={claude_agent}, claude_model={claude_model}, "- f"claude_reasoning_effort={normalized_claude_reasoning_effort}, "- f"codex_agent={resolved_codex_agent}, codex_model={codex_model}, "- f"codex_reasoning_effort={codex_reasoning_effort}"+ f"Routing updated for {settings_key}: backend={backend}, variant={variants.get(backend)}, "+ f"model={model}, reasoning_effort={reasoning_effort}")except Exception as e:diff --git a/core/modals.py b/core/modals.pyindex 1ea0049ab..47530b3c7 100644--- a/core/modals.py+++ b/core/modals.py@@ -1,12 +1,119 @@-"""Platform-neutral modal data models."""+"""Platform-neutral modal data models.++A channel route is the same four choices for every backend: the backend, its native agent (``variant``; only+native CLI backends have one), the model, and the reasoning effort. Backends differ only in where those lists+come from, which the settings handler resolves into one :class:`BackendRouteMenu` per backend. Each IM platform+then renders a single generic section from the menu and a :class:`RouteDraft`, so a new backend needs no+platform code.+"""from __future__ import annotations-from dataclasses import dataclass-from typing import Any, Optional+from dataclasses import dataclass, field, replace+from typing import Callable, Optional+from config.v2_settings import normalize_routing_settings+from modules.agents.catalog import NATIVE_CLI_BACKENDSfrom modules.settings_manager import ChannelRouting+# The value of every select's Default option: no choice of its own, so the route inherits its Agent's.+DEFAULT_OPTION_VALUE = "__default__"+# The value of the option showing a stored choice the platform cannot carry as an option value of its own (too+# long, or a reserved value). Saving it keeps the stored choice (``SettingsHandler.handle_routing_update``).+STORED_OPTION_VALUE = "__stored__"+++@dataclass(frozen=True)+class RouteOption:+ value: str+ label: str+++@dataclass(frozen=True)+class RouteDraft:+ """What a routing form shows for one backend; ``None`` is the Default option."""++ variant: Optional[str] = None+ model: Optional[str] = None+ reasoning_effort: Optional[str] = None++ def with_model(self, model: Optional[str]) -> RouteDraft:+ # A model change offers that model's efforts afresh. It is also why an effort the menu does not list can+ # only be the stored route's, which ``BackendRouteMenu.effort_options`` keeps shown. Picking the shown+ # model again changes nothing.+ if model == self.model:+ return self+ return replace(self, model=model, reasoning_effort=None)+++@dataclass+class BackendRouteMenu:+ """What one backend offers a channel route, sized for the platform that renders it.++ ``efforts`` maps a model to its efforts (the Default option excluded); ``""`` holds those of a route without+ its own model, and a model with no entry falls back to them. ``option_limit`` caps one select's options, the+ Default option included; ``value_limit`` is the longest option value the platform carries. ``stored`` is the+ stored route as this backend shows it, which names the choice a ``STORED_OPTION_VALUE`` option stands for.+ """++ backend: str+ variants: list[RouteOption] = field(default_factory=list)+ models: list[RouteOption] = field(default_factory=list)+ efforts: dict[str, list[RouteOption]] = field(default_factory=dict)+ option_limit: Optional[int] = None+ value_limit: Optional[int] = None+ stored: RouteDraft = field(default_factory=RouteDraft)++ def variant_options(self, current: Optional[str]) -> list[RouteOption]:+ return self._bounded(self.variants, current, self.stored.variant)++ def model_options(self, current: Optional[str]) -> list[RouteOption]:+ return self._bounded(self.models, current, self.stored.model)++ def effort_options(self, model: Optional[str], current: Optional[str]) -> list[RouteOption]:+ model = self.stored.model if model == STORED_OPTION_VALUE else model+ listed = self.efforts.get(model or "")+ return self._bounded(+ self.efforts.get("", []) if listed is None else listed, current, self.stored.reasoning_effort+ )++ def fits(self, value: object) -> bool:+ """Whether a select on this platform can carry ``value`` as an option of its own."""+ return (+ isinstance(value, str)+ and bool(value)+ and value not in (DEFAULT_OPTION_VALUE, STORED_OPTION_VALUE)+ and (self.value_limit is None or len(value) <= self.value_limit)+ )++ def chosen(self, field: str, value: Optional[str]) -> Optional[str]:+ """The choice a selected option stands for: the stored ``field`` for the stand-in option."""+ return getattr(self.stored, field) if value == STORED_OPTION_VALUE else value++ def shown_value(self, current: Optional[str]) -> str:+ """The option value a select shows for ``current``."""+ if not current:+ return DEFAULT_OPTION_VALUE+ return current if self.fits(current) or current == STORED_OPTION_VALUE else STORED_OPTION_VALUE++ def _bounded(self, options: list[RouteOption], current: Optional[str], stored: Optional[str]) -> list[RouteOption]:+ """``options`` within one select's cap, keeping ``current`` shown, listed or not.++ Saving a form unchanged then never drops a stored choice: one the list omits (a catalog that changed, an+ effort Model Hub now refuses), one past the cap, or one the platform cannot carry stays selectable.+ """+ room = None if self.option_limit is None else max(self.option_limit - 1, 0)+ kept = [option for option in options if self.fits(option.value)]+ shown = self.shown_value(current)+ if shown != DEFAULT_OPTION_VALUE and all(option.value != shown for option in kept[:room]):+ named = stored if current == STORED_OPTION_VALUE else current+ label = next((option.label for option in options if option.value == named), str(named or current))+ kept = [option for option in kept if option.value != shown]+ if room is not None:+ kept = kept[: max(room - 1, 0)]+ kept.append(RouteOption(shown, label))+ return kept if room is None else kept[:room]+@dataclassclass RoutingModalData:@@ -15,42 +122,43 @@ class RoutingModalData:registered_backends: list[str]current_backend: strcurrent_routing: ChannelRouting | None- opencode_agents: list[str]- opencode_models: dict[str, list[str]]- opencode_default_config: dict[str, Any]- claude_agents: list[str]- claude_models: list[str]- codex_agents: list[str]- codex_models: list[str]- backend_reasoning_options: dict[str, dict[str, list[dict[str, str]]]]-- def as_kwargs(self) -> dict[str, Any]:- return {- "registered_backends": self.registered_backends,- "current_backend": self.current_backend,- "current_routing": self.current_routing,- "opencode_agents": self.opencode_agents,- "opencode_models": self.opencode_models,- "opencode_default_config": self.opencode_default_config,- "claude_agents": self.claude_agents,- "claude_models": self.claude_models,- "codex_agents": self.codex_agents,- "codex_models": self.codex_models,- "backend_reasoning_options": self.backend_reasoning_options,- }+ menus: dict[str, BackendRouteMenu] = field(default_factory=dict)++ def menu(self, backend: str) -> BackendRouteMenu:+ return self.menus.get(backend) or BackendRouteMenu(backend, stored=self.stored_draft(backend))++ def stored_draft(self, backend: str) -> RouteDraft:+ """The stored route as one backend's form shows it before any change.++ The stored model and effort belong to the stored backend's Agent only; another backend starts at Default.+ """+ routing = self.current_routing+ variant = getattr(routing, f"{backend}_agent", None) if routing and backend in NATIVE_CLI_BACKENDS else None+ if routing is None or backend != self.current_backend:+ return RouteDraft(variant=variant)+ normalized = normalize_routing_settings(routing)+ return RouteDraft(variant=variant, model=normalized.model, reasoning_effort=normalized.reasoning_effort)@dataclassclass RoutingModalSelection:- """Normalized routing modal selection state."""+ """A routing form's state as an update reports it.++ ``draft`` is the shown backend's choices; ``None`` when the form had no section for ``selected_backend`` (a+ backend switch), which then starts from the stored route instead of blanks that saving would persist.+ """selected_backend: str- selected_opencode_agent: Optional[str] = None- selected_opencode_model: Optional[str] = None- selected_opencode_reasoning: Optional[str] = None- selected_claude_agent: Optional[str] = None- selected_claude_model: Optional[str] = None- selected_claude_reasoning: Optional[str] = None- selected_codex_agent: Optional[str] = None- selected_codex_model: Optional[str] = None- selected_codex_reasoning: Optional[str] = None+ draft: Optional[RouteDraft] = None+++def route_option_label(translate: Callable[[str], str], option: RouteOption, *, effort: bool = False) -> str:+ """An option's text: Default and effort tiers are translated, a model or agent keeps its catalog label."""+ if option.value == DEFAULT_OPTION_VALUE:+ return translate("common.default")+ if effort:+ key = f"reasoning.{option.value}"+ translated = translate(key)+ if translated != key:+ return translated+ return option.labeldiff --git a/modules/agents/opencode/utils.py b/modules/agents/opencode/utils.pyindex ee094f2eb..9e1ecdf26 100644--- a/modules/agents/opencode/utils.py+++ b/modules/agents/opencode/utils.py@@ -6,7 +6,7 @@ Shared by OpenCode, Claude, and Codex integrations for reasoning-effort option bfrom __future__ import annotations-from typing import Any, Dict, Iterable, List, Optional, Tuple+from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple_REASONING_FALLBACK_OPTIONS = [@@ -390,8 +390,13 @@ def build_opencode_model_option_items(max_total: int,preferred_providers: Optional[List[str]] = None,allowed_providers: Optional[List[str]] = None,+ keep: Optional[Callable[[str], bool]] = None,) -> List[Dict[str, str]]:- """Build sorted model options for OpenCode providers."""+ """Build sorted model options for OpenCode providers.++ ``keep`` drops an option value before it takes a provider's share of ``max_total`` (a value the select that+ shows the list cannot carry), so the share goes to models that can be shown.+ """if not isinstance(opencode_models, dict) or max_total <= 0:return []@@ -465,6 +470,8 @@ def build_opencode_model_option_items(model_id,model_info,)+ if keep is not None and not keep(full_model):+ continuedisplay = (model_nameif opencode_model_is_hub_projected(model_info)diff --git a/modules/im/discord.py b/modules/im/discord.pyindex 82d211d9e..2f5ba6b57 100644--- a/modules/im/discord.py+++ b/modules/im/discord.py@@ -1,11 +1,12 @@import asyncio-from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS, display_name_for_backend+from modules.agents.catalog import NATIVE_CLI_BACKENDS, display_name_for_backendimport ioimport jsonimport loggingimport osimport threadingimport time+from dataclasses import replacefrom typing import Dict, Any, Optional, Callable, Listimport aiohttp@@ -28,19 +29,9 @@ from .download_target import open_download_targetfrom config.v2_config import DiscordConfigfrom .formatters import DiscordFormatterfrom vibe.i18n import get_supported_languages, t as i18n_t-from modules.agents.opencode.utils import (- build_claude_reasoning_options,- build_opencode_model_option_items,- build_codex_reasoning_options,- format_claude_model_label,- build_reasoning_effort_options,- resolve_model_reasoning_options,- resolve_opencode_allowed_providers,- resolve_opencode_provider_preferences,-)+from core.modals import DEFAULT_OPTION_VALUE, RouteDraft, RouteOption, RoutingModalData, route_option_labelfrom modules.agents.native_sessions.display import format_display_summary, format_display_timefrom modules.agents.native_sessions.types import NativeResumeSession-from vibe.claude_model_catalog import DEFAULT_CLAUDE_MODEL_ALIASESlogger = logging.getLogger(__name__)@@ -53,27 +44,17 @@ _RUNTIME_RETRY_INITIAL_SECONDS = 1.0_RUNTIME_RETRY_MAX_SECONDS = 30.0-def _prioritize_claude_model_choices(models: List[str], current_model: Optional[str]) -> List[str]:- """Order Claude model ids so the active selection and the canonical bare- aliases (opus/sonnet/haiku) survive Discord's 25-option select-menu cap.-- ``api.claude_models()`` appends the bare aliases after the full catalog, so a- plain truncation silently drops the most useful, always-valid picks — and the- user's current selection. Surfacing them first means the cap only trims the- long tail of dated snapshots instead.- """- priority: List[str] = []- seen: set[str] = set()- for candidate in (current_model, *DEFAULT_CLAUDE_MODEL_ALIASES):- if candidate and candidate in models and candidate not in seen:- priority.append(candidate)- seen.add(candidate)- return priority + [model for model in models if model not in seen]+def _choice(value: Optional[str]) -> Optional[str]:+ return None if value in (None, DEFAULT_OPTION_VALUE) else valueclass DiscordBot(BaseIMClient):"""Discord implementation of the IM client."""+ # A select menu holds at most 25 options, each value at most 100 characters.+ route_option_limit = 25+ route_option_value_limit = 100+def __init__(self, config: DiscordConfig):super().__init__(config)self.config = config@@ -1579,116 +1560,63 @@ class DiscordBot(BaseIMClient):raise RuntimeError("Discord channel not found")await channel.send(intro_text, view=view)- async def open_routing_modal(- self,- trigger_id: Any,- channel_id: str,- registered_backends: list,- current_backend: str,- current_routing: Any,- opencode_agents: list,- opencode_models: dict,- opencode_default_config: dict,- claude_agents: list,- claude_models: list,- codex_agents: list,- codex_models: list,- backend_reasoning_options: Optional[dict] = None,- ):+ async def open_routing_modal(self, trigger_id: Any, channel_id: str, routing: RoutingModalData):interaction = trigger_id if isinstance(trigger_id, discord.Interaction) else None- backend_display_names = {- backend: display_name_for_backend(backend) for backend in AGENT_BACKENDS- }-- def _prefixed_label(prefix_key: str, label: str, limit: int = 100) -> str:- prefix = self._t(prefix_key)+ def _prefixed_label(prefix: str, label: str, limit: int = 100) -> str:combined = f"{prefix}: {label}" if prefix else label- if len(combined) > limit:- return combined[:limit]- return combined-- def _normalize_agent_name(agent: Any) -> Optional[str]:- if isinstance(agent, str):- return agent- if isinstance(agent, dict):- for key in ("name", "id", "label", "agent"):- value = agent.get(key)- if isinstance(value, str) and value:- return value- return None-- def _unique_agent_names(agents: list) -> list:- seen = set()- names = []- for agent in agents or []:- name = _normalize_agent_name(agent)- if not name or name in seen:- continue- seen.add(name)- names.append(name)- return names+ return combined[:limit]class RoutingView(discord.ui.View):def __init__(self, outer: DiscordBot, owner_id: Optional[str]):super().__init__(timeout=900)self.outer = outerself.owner_id = owner_id- self.step = "backend"- self.selected_backend = current_backend or (- registered_backends[0] if registered_backends else "opencode"+ registered = routing.registered_backends+ self.selected_backend = (+ routing.current_backend+ if routing.current_backend in registered+ else (registered[0] if registered else routing.current_backend))- canonical_model = getattr(current_routing, "model", None) if current_routing else None- canonical_reasoning = getattr(current_routing, "reasoning_effort", None) if current_routing else None-- def _canonical_applies_to_backend(backend: str) -> bool:- return backend == (current_backend or "opencode")-- def _current_model(field_name: str, backend: str) -> Optional[str]:- value = getattr(current_routing, field_name, None) if current_routing else None- if value is not None:- return value- if self.selected_backend == backend and _canonical_applies_to_backend(backend):- return canonical_model- return None-- def _current_reasoning(field_name: str, backend: str) -> Optional[str]:- value = getattr(current_routing, field_name, None) if current_routing else None- if value is not None:- return value- if self.selected_backend == backend and _canonical_applies_to_backend(backend):- return canonical_reasoning- return None-- self.oc_agent = getattr(current_routing, "opencode_agent", None) if current_routing else None- self.oc_model = _current_model("opencode_model", "opencode")- self.oc_reasoning = _current_reasoning("opencode_reasoning_effort", "opencode")- self.claude_agent = getattr(current_routing, "claude_agent", None) if current_routing else None- self.claude_model = _current_model("claude_model", "claude")- self.claude_reasoning = _current_reasoning("claude_reasoning_effort", "claude")- self.codex_agent = getattr(current_routing, "codex_agent", None) if current_routing else None- self.codex_model = _current_model("codex_model", "codex")- self.codex_reasoning = _current_reasoning("codex_reasoning_effort", "codex")+ # Each backend keeps its own choices while the view is open; one not yet shown starts stored.+ self.drafts: dict[str, RouteDraft] = {}self._render()+ def _draft(self) -> RouteDraft:+ backend = self.selected_backend+ if backend not in self.drafts:+ self.drafts[backend] = routing.stored_draft(backend)+ return self.drafts[backend]++ def _select(self, placeholder: str, prefix: str, options, shown: str, *, effort=False):+ default = RouteOption(DEFAULT_OPTION_VALUE, "")+ return discord.ui.Select(+ placeholder=placeholder,+ options=[+ discord.SelectOption(+ label=_prefixed_label(prefix, route_option_label(self.outer._t, option, effort=effort)),+ value=option.value,+ default=option.value == shown,+ )+ for option in [default, *options]+ ],+ min_values=1,+ max_values=1,+ )+def _render(self):self.clear_items()- options = []- for backend in registered_backends:- display = backend_display_names.get(backend, backend.capitalize())- label = _prefixed_label("discord.labels.backend", display)- options.append(+ t = self.outer._t+ backend_select = discord.ui.Select(+ placeholder=t("modal.routing.selectBackend"),+ options=[discord.SelectOption(- label=label,+ label=_prefixed_label(t("discord.labels.backend"), display_name_for_backend(backend)),value=backend,default=backend == self.selected_backend,)- )- if len(options) > 25:- options = options[:25]- backend_select = discord.ui.Select(- placeholder=self.outer._t("modal.routing.selectBackend"),- options=options,+ for backend in routing.registered_backends[:25]+ ],min_values=1,max_values=1,)@@ -1696,402 +1624,86 @@ class DiscordBot(BaseIMClient):async def backend_callback(select_interaction: discord.Interaction):if backend_select.values:self.selected_backend = backend_select.values[0]- self._render()- updated_embed = discord.Embed(- title=self._content(),- description=self.outer._t("discord.routingSubtitle"),- )- await select_interaction.response.edit_message(embed=updated_embed, view=self)+ await self._refresh(select_interaction)backend_select.callback = backend_callbackself.add_item(backend_select)- if self.selected_backend == "opencode":- opencode_agent_names = _unique_agent_names(opencode_agents)- target_model = self.oc_model if self.oc_model not in (None, "__default__") else None- preferred_providers = resolve_opencode_provider_preferences(- opencode_default_config,- target_model,- )- allowed_providers = resolve_opencode_allowed_providers(- opencode_default_config,- opencode_models,- )- agent_options = [- discord.SelectOption(- label=_prefixed_label(- "discord.labels.opencodeAgent",- self.outer._t("common.default"),- ),- value="__default__",- default=self.oc_agent in (None, "__default__"),- )- ]- agent_options += [- discord.SelectOption(- label=_prefixed_label("discord.labels.opencodeAgent", a),- value=a,- default=a == self.oc_agent,- )- for a in opencode_agent_names- ]- if len(agent_options) > 25:- agent_options = agent_options[:25]- agent_select = discord.ui.Select(- placeholder=self.outer._t("modal.routing.selectOpencodeAgent"),- options=agent_options,- min_values=1,- max_values=1,- )-- async def agent_callback(select_interaction: discord.Interaction):- if agent_select.values:- self.oc_agent = agent_select.values[0]- await select_interaction.response.defer()-- agent_select.callback = agent_callback- self.add_item(agent_select)-- default_label = self.outer._t("common.default")- model_options = [- discord.SelectOption(- label=_prefixed_label("discord.labels.model", default_label),- value="__default__",- default=self.oc_model in (None, "__default__"),- )- ]- model_entries = build_opencode_model_option_items(- opencode_models,- max_total=24,- preferred_providers=preferred_providers,- allowed_providers=allowed_providers,- )- for entry in model_entries:- label = entry.get("label", "")- value = entry.get("value", "")- if not label or not value:- continue- model_options.append(- discord.SelectOption(- label=_prefixed_label("discord.labels.model", label),- value=value,- default=value == self.oc_model,- )- )- model_select = discord.ui.Select(- placeholder=self.outer._t("modal.routing.selectModel"),- options=model_options,- min_values=1,- max_values=1,- )-- async def model_callback(select_interaction: discord.Interaction):- if model_select.values:- self.oc_model = model_select.values[0]- self._render()- updated_embed = discord.Embed(- title=self._content(),- description=self.outer._t("discord.routingSubtitle"),- )- await select_interaction.response.edit_message(embed=updated_embed, view=self)-- model_select.callback = model_callback- self.add_item(model_select)-- reasoning_entries = build_reasoning_effort_options(opencode_models, target_model)- selected_reasoning = (- self.oc_reasoning if self.oc_reasoning not in (None, "__default__") else "__default__"- )- available_reasoning = {entry.get("value") for entry in reasoning_entries}- if selected_reasoning not in available_reasoning:- selected_reasoning = "__default__"- reasoning_options = []- for entry in reasoning_entries:- value = entry.get("value")- if not value:- continue- if value == "__default__":- label = self.outer._t("common.default")- else:- translated = self.outer._t(f"reasoning.{value}")- label = translated if translated != f"reasoning.{value}" else entry.get("label", value)- reasoning_options.append(- discord.SelectOption(- label=_prefixed_label("discord.labels.reasoningEffort", label),- value=value,- default=value == selected_reasoning,- )- )- reasoning_select = discord.ui.Select(- placeholder=self.outer._t("modal.routing.selectReasoningEffort"),- options=reasoning_options,- min_values=1,- max_values=1,- )-- async def reasoning_callback(select_interaction: discord.Interaction):- if reasoning_select.values:- self.oc_reasoning = reasoning_select.values[0]- await select_interaction.response.defer()-- reasoning_select.callback = reasoning_callback- self.add_item(reasoning_select)-- if self.selected_backend == "claude":- claude_agent_names = _unique_agent_names(claude_agents)- agent_options = [- discord.SelectOption(- label=_prefixed_label(- "discord.labels.claudeAgent",- self.outer._t("common.default"),- ),- value="__default__",- default=self.claude_agent in (None, "__default__"),- )- ]- agent_options += [- discord.SelectOption(label=a, value=a, default=a == self.claude_agent)- for a in claude_agent_names- ]- if len(agent_options) > 25:- agent_options = agent_options[:25]- agent_select = discord.ui.Select(- placeholder=self.outer._t("modal.routing.selectClaudeAgent"),- options=agent_options,- min_values=1,- max_values=1,+ backend = self.selected_backend+ menu = routing.menu(backend)+ draft = self._draft()+ backend_name = display_name_for_backend(backend)+ variants = menu.variant_options(draft.variant)+ if variants:+ variant_select = self._select(+ t("modal.routing.selectBackendAgent", backend=backend_name),+ t("discord.labels.backendAgent", backend=backend_name),+ variants,+ menu.shown_value(draft.variant),)- async def claude_agent_callback(select_interaction: discord.Interaction):- if agent_select.values:- self.claude_agent = agent_select.values[0]- await select_interaction.response.defer()-- agent_select.callback = claude_agent_callback- self.add_item(agent_select)-- model_options = [- discord.SelectOption(- label=_prefixed_label("discord.labels.model", self.outer._t("common.default")),- value="__default__",- default=self.claude_model in (None, "__default__"),- )- ]- # Discord select menus cap at 25 options; prioritize the active- # pick and the bare aliases so the truncation below only trims the- # long tail of dated snapshots (see _prioritize_claude_model_choices).- model_options += [- discord.SelectOption(- label=_prefixed_label("discord.labels.model", format_claude_model_label(m)),- value=m,- default=m == self.claude_model,- )- for m in _prioritize_claude_model_choices(claude_models, self.claude_model)- ]- if len(model_options) > 25:- model_options = model_options[:25]- model_select = discord.ui.Select(- placeholder=self.outer._t("modal.routing.selectModel"),- options=model_options,- min_values=1,- max_values=1,- )-- async def claude_model_callback(select_interaction: discord.Interaction):- if model_select.values:- self.claude_model = model_select.values[0]- self.claude_reasoning = None- self._render()- updated_embed = discord.Embed(- title=self._content(),- description=self.outer._t("discord.routingSubtitle"),- )- await select_interaction.response.edit_message(embed=updated_embed, view=self)-- model_select.callback = claude_model_callback- self.add_item(model_select)-- target_claude_model = (- self.claude_model if self.claude_model not in (None, "__default__") else None- )- claude_reasoning_entries = resolve_model_reasoning_options(- (backend_reasoning_options or {}).get("claude"),- target_claude_model,- build_claude_reasoning_options(target_claude_model),- )- selected_cl_reasoning = (- self.claude_reasoning if self.claude_reasoning not in (None, "__default__") else "__default__"- )- available_cl_reasoning = {entry.get("value") for entry in claude_reasoning_entries}- if selected_cl_reasoning not in available_cl_reasoning:- selected_cl_reasoning = "__default__"- self.claude_reasoning = None- reasoning_options = []- for entry in claude_reasoning_entries:- value = entry.get("value")- if not value:- continue- if value == "__default__":- label = self.outer._t("common.default")- else:- translated = self.outer._t(f"reasoning.{value}")- label = translated if translated != f"reasoning.{value}" else entry.get("label", value)- reasoning_options.append(- discord.SelectOption(- label=_prefixed_label("discord.labels.reasoningEffort", label),- value=value,- default=value == selected_cl_reasoning,+ async def variant_callback(select_interaction: discord.Interaction):+ if variant_select.values:+ self.drafts[backend] = replace(+ self._draft(), variant=menu.chosen("variant", _choice(variant_select.values[0])))- )- reasoning_select = discord.ui.Select(- placeholder=self.outer._t("modal.routing.selectReasoningEffort"),- options=reasoning_options,- min_values=1,- max_values=1,- )-- async def claude_reasoning_callback(select_interaction: discord.Interaction):- if reasoning_select.values:- self.claude_reasoning = reasoning_select.values[0]await select_interaction.response.defer()- reasoning_select.callback = claude_reasoning_callback- self.add_item(reasoning_select)+ variant_select.callback = variant_callback+ self.add_item(variant_select)- if self.selected_backend == "codex":- codex_agent_names = _unique_agent_names(codex_agents)- agent_options = [- discord.SelectOption(- label=_prefixed_label(- "discord.labels.codexAgent",- self.outer._t("common.default"),- ),- value="__default__",- default=self.codex_agent in (None, "__default__"),- )- ]- agent_options += [- discord.SelectOption(label=a, value=a, default=a == self.codex_agent)- for a in codex_agent_names- ]- if len(agent_options) > 25:- agent_options = agent_options[:25]- agent_select = discord.ui.Select(- placeholder=self.outer._t("modal.routing.selectCodexAgent"),- options=agent_options,- min_values=1,- max_values=1,- )-- async def codex_agent_callback(select_interaction: discord.Interaction):- if agent_select.values:- self.codex_agent = agent_select.values[0]- await select_interaction.response.defer()-- agent_select.callback = codex_agent_callback- self.add_item(agent_select)+ model_select = self._select(+ t("modal.routing.selectModel"),+ t("discord.labels.model"),+ menu.model_options(draft.model),+ menu.shown_value(draft.model),+ )- model_options = [- discord.SelectOption(- label=_prefixed_label("discord.labels.model", self.outer._t("common.default")),- value="__default__",- default=self.codex_model in (None, "__default__"),- )- ]- model_options += [- discord.SelectOption(- label=_prefixed_label("discord.labels.model", m),- value=m,- default=m == self.codex_model,+ async def model_callback(select_interaction: discord.Interaction):+ if model_select.values:+ self.drafts[backend] = self._draft().with_model(+ menu.chosen("model", _choice(model_select.values[0])))- for m in codex_models- ]- if len(model_options) > 25:- model_options = model_options[:25]- model_select = discord.ui.Select(- placeholder=self.outer._t("modal.routing.selectModel"),- options=model_options,- min_values=1,- max_values=1,- )+ await self._refresh(select_interaction)- async def codex_model_callback(select_interaction: discord.Interaction):- if model_select.values:- self.codex_model = model_select.values[0]- self.codex_reasoning = None- self._render()- updated_embed = discord.Embed(- title=self._content(),- description=self.outer._t("discord.routingSubtitle"),- )- await select_interaction.response.edit_message(embed=updated_embed, view=self)+ model_select.callback = model_callback+ self.add_item(model_select)- model_select.callback = codex_model_callback- self.add_item(model_select)+ effort_select = self._select(+ t("modal.routing.selectReasoningEffort"),+ t("discord.labels.reasoningEffort"),+ menu.effort_options(draft.model, draft.reasoning_effort),+ menu.shown_value(draft.reasoning_effort),+ effort=True,+ )- target_codex_model = (- self.codex_model if self.codex_model not in (None, "__default__") else None- )- codex_reasoning_entries = resolve_model_reasoning_options(- (backend_reasoning_options or {}).get("codex"),- target_codex_model,- build_codex_reasoning_options(),- )- selected_cx_reasoning = (- self.codex_reasoning if self.codex_reasoning not in (None, "__default__") else "__default__"- )- available_cx_reasoning = {entry.get("value") for entry in codex_reasoning_entries}- if selected_cx_reasoning not in available_cx_reasoning:- selected_cx_reasoning = "__default__"- self.codex_reasoning = None- reasoning_options = []- for entry in codex_reasoning_entries:- value = entry.get("value")- if not value:- continue- if value == "__default__":- label = self.outer._t("common.default")- else:- translated = self.outer._t(f"reasoning.{value}")- label = translated if translated != f"reasoning.{value}" else entry.get("label", value)- reasoning_options.append(- discord.SelectOption(- label=_prefixed_label("discord.labels.reasoningEffort", label),- value=value,- default=value == selected_cx_reasoning,- )+ async def effort_callback(select_interaction: discord.Interaction):+ if effort_select.values:+ self.drafts[backend] = replace(+ self._draft(),+ reasoning_effort=menu.chosen("reasoning_effort", _choice(effort_select.values[0])),)- reasoning_select = discord.ui.Select(- placeholder=self.outer._t("modal.routing.selectReasoningEffort"),- options=reasoning_options,- min_values=1,- max_values=1,- )-- async def codex_reasoning_callback(select_interaction: discord.Interaction):- if reasoning_select.values:- self.codex_reasoning = reasoning_select.values[0]- await select_interaction.response.defer()+ await select_interaction.response.defer()- reasoning_select.callback = codex_reasoning_callback- self.add_item(reasoning_select)+ effort_select.callback = effort_callback+ self.add_item(effort_select)- save_button = discord.ui.Button(- label=self.outer._t("common.save"),- style=discord.ButtonStyle.primary,- )+ save_button = discord.ui.Button(label=t("common.save"), style=discord.ButtonStyle.primary)save_button.callback = self._on_saveself.add_item(save_button)+ async def _refresh(self, select_interaction: discord.Interaction):+ self._render()+ updated_embed = discord.Embed(+ title=self._content(),+ description=self.outer._t("discord.routingSubtitle"),+ )+ await select_interaction.response.edit_message(embed=updated_embed, view=self)+def _content(self) -> str:return f"🤖 {self.outer._t('modal.routing.title')}"async def _on_save(self, interaction: discord.Interaction):- def _normalize(value: Optional[str]) -> Optional[str]:- if value in (None, "__default__"):- return None- return value-try:await interaction.response.defer()# Re-check auth before saving (defense-in-depth)@@ -2110,19 +1722,14 @@ class DiscordBot(BaseIMClient):returnif hasattr(self.outer, "_on_routing_update"):+ draft = self._draft()await self.outer._on_routing_update(user_id=str(interaction.user.id),channel_id=channel_id,backend=self.selected_backend,- opencode_agent=_normalize(self.oc_agent),- opencode_model=_normalize(self.oc_model),- opencode_reasoning_effort=_normalize(self.oc_reasoning),- claude_agent=_normalize(self.claude_agent),- claude_model=_normalize(self.claude_model),- claude_reasoning_effort=_normalize(self.claude_reasoning),- codex_agent=_normalize(self.codex_agent),- codex_model=_normalize(self.codex_model),- codex_reasoning_effort=_normalize(self.codex_reasoning),+ variant=draft.variant,+ model=draft.model,+ reasoning_effort=draft.reasoning_effort,notify_user=True,is_dm=interaction.guild is None,)diff --git a/modules/im/feishu.py b/modules/im/feishu.pyindex 97fbc7a3d..b74c7cbe5 100644--- a/modules/im/feishu.py+++ b/modules/im/feishu.py@@ -1,13 +1,14 @@"""Feishu/Lark implementation of the IM client using lark-oapi SDK."""import asyncio-from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS, display_name_for_backend+from modules.agents.catalog import NATIVE_CLI_BACKENDS, display_name_for_backendimport ioimport jsonimport loggingimport osimport threadingimport time+from dataclasses import replacefrom typing import Any, Callable, Dict, List, Optionalimport aiohttp@@ -31,16 +32,7 @@ from config.v2_config import LarkConfigfrom core.citations import spell_destinationfrom core.reply_enhancer import inline_linksfrom vibe.i18n import get_supported_languages, t as i18n_t-from modules.agents.opencode.utils import (- build_claude_reasoning_options,- build_codex_reasoning_options,- format_claude_model_label,- build_opencode_model_option_items,- build_reasoning_effort_options,- resolve_model_reasoning_options,- resolve_opencode_allowed_providers,- resolve_opencode_provider_preferences,-)+from core.modals import DEFAULT_OPTION_VALUE, RouteDraft, RouteOption, RoutingModalData, route_option_labelfrom modules.agents.native_sessions.display import format_display_summary, format_display_timefrom modules.agents.native_sessions.types import NativeResumeSession@@ -117,6 +109,9 @@ def _normalize_emoji(emoji: str) -> str:class FeishuBot(BaseIMClient):"""Feishu/Lark implementation of the IM client using lark-oapi SDK."""+ # Bounds a routing card's select to the size OpenCode's model list always used.+ route_option_limit = 100+def __init__(self, config: LarkConfig):super().__init__(config)self.config = config@@ -2005,8 +2000,8 @@ class FeishuBot(BaseIMClient):await self._handle_settings_form_submit(context, form_value)elif button_name == "routing_backend_select":await self._handle_routing_backend_select(context, form_value)- elif button_name == "routing_submit":- await self._handle_routing_form_submit(context, form_value)+ elif button_name.startswith("routing_submit"):+ await self._handle_routing_form_submit(context, form_value, button_name)elif button_name.startswith("resume_submit"):await self._handle_resume_form_submit(context, form_value, button_name)elif button_name.startswith("question_submit"):@@ -2098,51 +2093,35 @@ class FeishuBot(BaseIMClient):returncache_key = f"{context.channel_id}:{context.user_id}"- cached = self._routing_cache.get(cache_key)- if not cached:+ if cache_key not in self._routing_cache:logger.warning("No cached routing data for %s", cache_key)return- await self._send_routing_backend_options_card(- channel_id=context.channel_id,- selected_backend=selected_backend,- _user_id=context.user_id,- **cached,- )+ await self._send_routing_backend_options_card(context.channel_id, selected_backend, context.user_id)@staticmethoddef _normalize_routing_field_value(value: Any) -> Optional[str]:- if value in (None, "", "__default__"):+ if value in (None, "", DEFAULT_OPTION_VALUE):return Nonereturn str(value)+ # A routing card's select names (``<prefix>:<backend>``) and the draft field each sets. The backend is in+ # every name, so a card acts on its own backend even after the step-1 card opened another one.+ _ROUTE_FIELDS = {"route_variant": "variant", "route_model": "model", "route_effort": "reasoning_effort"}++ @classmethod+ def _route_field(cls, name: object) -> tuple[Optional[str], str]:+ """A routing control's draft field and backend, from its name."""+ prefix, _, backend = str(name or "").partition(":")+ return cls._ROUTE_FIELDS.get(prefix), backend+@staticmethod- def _routing_draft_from_current(- current_routing: Any,- selected_backend: Optional[str] = None,- ) -> Dict[str, Optional[str]]:- fields = (- "opencode_agent",- "opencode_model",- "opencode_reasoning_effort",- "claude_agent",- "claude_model",- "claude_reasoning_effort",- "codex_agent",- "codex_model",- "codex_reasoning_effort",- )- draft: Dict[str, Optional[str]] = {}- for field_name in fields:- draft[field_name] = getattr(current_routing, field_name, None) if current_routing else None- if selected_backend in AGENT_BACKENDS and current_routing:- model = getattr(current_routing, "model", None)- reasoning_effort = getattr(current_routing, "reasoning_effort", None)- draft[f"{selected_backend}_model"] = draft.get(f"{selected_backend}_model") or model- draft[f"{selected_backend}_reasoning_effort"] = (- draft.get(f"{selected_backend}_reasoning_effort") or reasoning_effort- )- return draft+ def _routing_draft(cache: Dict[str, Any], backend: str) -> RouteDraft:+ """The backend's choices on this card; one not yet shown starts from the stored route."""+ drafts = cache.setdefault("drafts", {})+ if backend not in drafts:+ drafts[backend] = cache["routing"].stored_draft(backend)+ return drafts[backend]@staticmethoddef _extract_select_action_value(action: Dict[str, Any]) -> Optional[str]:@@ -2183,103 +2162,50 @@ class FeishuBot(BaseIMClient):raise RuntimeError(f"Feishu patch card failed: {response.msg}")async def _handle_routing_select_change(self, context: MessageContext, action: Dict[str, Any]) -> bool:- field_name = action.get("name", "")- if not field_name:+ draft_field, backend = self._route_field(action.get("name"))+ if not draft_field:return False-- routing_field_map = {- "opencode_agent": "opencode_agent",- "opencode_model": "opencode_model",- "opencode_reasoning": "opencode_reasoning_effort",- "claude_agent": "claude_agent",- "claude_model": "claude_model",- "claude_reasoning": "claude_reasoning_effort",- "codex_agent": "codex_agent",- "codex_model": "codex_model",- "codex_reasoning": "codex_reasoning_effort",- }- routing_field = routing_field_map.get(field_name)- if not routing_field:- return False-- cache_key = f"{context.channel_id}:{context.user_id}"- cache = self._routing_cache.get(cache_key)- if not cache:+ cache = self._routing_cache.get(f"{context.channel_id}:{context.user_id}")+ if not cache or not backend or "routing" not in cache:return False- draft_routing = dict(- cache.get("draft_routing")- or self._routing_draft_from_current(cache.get("current_routing"), cache.get("_selected_backend"))+ draft = self._routing_draft(cache, backend)+ value = cache["routing"].menu(backend).chosen(+ draft_field, self._normalize_routing_field_value(self._extract_select_action_value(action)))- selected_value = self._normalize_routing_field_value(self._extract_select_action_value(action))- draft_routing[routing_field] = selected_value-- if routing_field == "claude_model":- draft_routing["claude_reasoning_effort"] = None-- cache["draft_routing"] = draft_routing- self._routing_cache[cache_key] = cache-- if routing_field != "claude_model" or cache.get("_selected_backend") != "claude":+ if draft_field != "model":+ cache["drafts"][backend] = replace(draft, **{draft_field: value})return True-- card = self._build_routing_backend_options_card(- channel_id=context.channel_id,- selected_backend="claude",- _user_id=context.user_id,- **cache,- )+ # A model change offers that model's efforts afresh, so the card is rebuilt around it.+ cache["drafts"][backend] = draft.with_model(value)+ card = self._build_routing_backend_options_card(context.channel_id, backend, context.user_id)await self._patch_card_message(context.message_id, card)return True- async def _handle_routing_form_submit(self, context: MessageContext, form_value: Dict[str, Any]):- """Handle step 2 routing form submission (backend-specific options)."""- # Backend is embedded in form as a disabled select or retrieved from cache- cache_key = f"{context.channel_id}:{context.user_id}"- cached = self._routing_cache.get(cache_key, {})- backend = form_value.get("backend", "")- if not backend:- # Fallback: get from cache- backend = cached.get("_selected_backend", "")-- if not backend:- logger.warning("Routing form submitted with empty backend, ignoring")+ async def _handle_routing_form_submit(self, context: MessageContext, form_value: Dict[str, Any], button_name: str):+ """Handle step 2 routing form submission: the options card of the backend its button names."""+ cached = self._routing_cache.get(f"{context.channel_id}:{context.user_id}", {})+ backend = button_name.partition(":")[2]+ if not backend or "routing" not in cached:+ logger.warning("Routing form submitted without a backend or cached routing, ignoring")return- draft_routing = cached.get("draft_routing") or self._routing_draft_from_current(- cached.get("current_routing"),- backend,- )-- def _val(form_key: str, routing_field: str) -> Optional[str]:- if form_key in form_value:- return self._normalize_routing_field_value(form_value.get(form_key))- return draft_routing.get(routing_field)-- opencode_agent = _val("opencode_agent", "opencode_agent")- opencode_model = _val("opencode_model", "opencode_model")- opencode_reasoning = _val("opencode_reasoning", "opencode_reasoning_effort")- claude_agent = _val("claude_agent", "claude_agent")- claude_model = _val("claude_model", "claude_model")- claude_reasoning = _val("claude_reasoning", "claude_reasoning_effort")- codex_agent = _val("codex_agent", "codex_agent")- codex_model = _val("codex_model", "codex_model")- codex_reasoning = _val("codex_reasoning", "codex_reasoning_effort")-+ # The form carries what its selects show; a field it omits keeps the card's draft.+ menu = cached["routing"].menu(backend)+ changes = {}+ for name, value in form_value.items():+ draft_field, field_backend = self._route_field(name)+ if draft_field and field_backend == backend:+ changes[draft_field] = menu.chosen(draft_field, self._normalize_routing_field_value(value))+ draft = replace(self._routing_draft(cached, backend), **changes)if self._on_routing_update:await self._on_routing_update(user_id=context.user_id,channel_id=context.channel_id,backend=backend,- opencode_agent=opencode_agent,- opencode_model=opencode_model,- opencode_reasoning_effort=opencode_reasoning,- claude_agent=claude_agent,- claude_model=claude_model,- claude_reasoning_effort=claude_reasoning,- codex_agent=codex_agent,- codex_model=codex_model,- codex_reasoning_effort=codex_reasoning,+ variant=draft.variant,+ model=draft.model,+ reasoning_effort=draft.reasoning_effort,is_dm=context.platform_specific.get("is_dm", False),)@@ -2620,61 +2546,30 @@ class FeishuBot(BaseIMClient):except Exception as exc:logger.error("Failed to send CWD card: %s", exc)- async def open_routing_modal(- self,- trigger_id: Any,- channel_id: str = None,- current_backend: str = None,- **kwargs,- ):+ async def open_routing_modal(self, trigger_id: Any, channel_id: str = None, routing: RoutingModalData = None):"""Step 1: send a card with only the backend selector.- All backend/model/agent data is cached so that step 2- (``_send_routing_backend_options_card``) can render the- backend-specific options without re-fetching.+ The route menus are cached so that step 2 (``_send_routing_backend_options_card``) renders the selected+ backend's options without re-fetching."""t = lambda key, **kw: self._t(key, channel_id, **kw)+ registered_backends = routing.registered_backends- registered_backends = kwargs.get("registered_backends", [])-- # Cache everything for step 2, keyed by channel+user to avoid crosstalk- # when multiple users open routing in the same channel concurrently.+ # Cache per channel+user, so users opening routing in one channel concurrently do not cross.cache_user_id = trigger_id.user_id if isinstance(trigger_id, MessageContext) else "unknown"- cache_key = f"{channel_id or ''}:{cache_user_id}"- self._routing_cache[cache_key] = {- "current_routing": kwargs.get("current_routing"),- "draft_routing": self._routing_draft_from_current(kwargs.get("current_routing"), current_backend),- "registered_backends": registered_backends,- "opencode_agents": kwargs.get("opencode_agents", []),- "opencode_models": kwargs.get("opencode_models", {}),- "opencode_default_config": kwargs.get("opencode_default_config", {}),- "claude_agents": kwargs.get("claude_agents", []),- "claude_models": kwargs.get("claude_models", []),- "codex_agents": kwargs.get("codex_agents", []),- "codex_models": kwargs.get("codex_models", []),- "backend_reasoning_options": kwargs.get("backend_reasoning_options", {}),- }-- # --- Backend selector options ---- backend_options = []- for b in registered_backends:- backend_options.append(- {- "text": {"tag": "plain_text", "content": display_name_for_backend(b)},- "value": b,- }- )- backend_initial = (- current_backend- if current_backend and current_backend in registered_backends- else (registered_backends[0] if registered_backends else None)- )+ self._routing_cache[f"{channel_id or ''}:{cache_user_id}"] = {"routing": routing, "drafts": {}}+ backend_options = [+ {"text": {"tag": "plain_text", "content": display_name_for_backend(b)}, "value": b}+ for b in registered_backends+ ]if not backend_options:- # No backends — just show infoctx = MessageContext(user_id="system", channel_id=channel_id or "")await self.send_message(ctx, "No agent backends available.")return+ backend_initial = (+ routing.current_backend if routing.current_backend in registered_backends else registered_backends[0]+ )form_elements: list = [{"tag": "markdown", "content": f"**{t('modal.routing.backend')}**"},@@ -2683,21 +2578,17 @@ class FeishuBot(BaseIMClient):"name": "backend","placeholder": {"tag": "plain_text", "content": t("modal.routing.selectBackend")},"options": backend_options,- **({"initial_option": backend_initial} if backend_initial else {}),+ "initial_option": backend_initial,},{"tag": "markdown", "content": t("modal.routing.tip")},{"tag": "button",- "text": {- "tag": "plain_text",- "content": t("common.next"),- },+ "text": {"tag": "plain_text", "content": t("common.next")},"type": "primary","action_type": "form_submit","name": "routing_backend_select",},]-card = {"schema": "2.0","header": {@@ -2706,297 +2597,92 @@ class FeishuBot(BaseIMClient):},"body": {"direction": "vertical",- "elements": [- {- "tag": "form",- "name": "routing_backend_form",- "elements": form_elements,- },- ],+ "elements": [{"tag": "form", "name": "routing_backend_form", "elements": form_elements}],},}-ctx = MessageContext(user_id="system", channel_id=channel_id or "")try:await self._send_card_to_channel(ctx, card)except Exception as exc:logger.error("Failed to send routing backend card: %s", exc)- def _build_routing_backend_options_card(- self,- channel_id: str,- selected_backend: str,- **kwargs,- ) -> Dict[str, Any]:- """Build the step-2 routing card for a selected backend."""+ def _build_routing_backend_options_card(self, channel_id: str, selected_backend: str, user_id: str) -> Dict[str, Any]:+ """Build the step-2 routing card: the selected backend's route fields."""t = lambda key, **kw: self._t(key, channel_id, **kw)-- current_routing = kwargs.get("current_routing")- draft_routing = kwargs.get("draft_routing") or {}- opencode_agents = kwargs.get("opencode_agents", [])- opencode_models = kwargs.get("opencode_models", {})- opencode_default_config = kwargs.get("opencode_default_config", {})- claude_agents = kwargs.get("claude_agents", [])- claude_models = kwargs.get("claude_models", [])- codex_agents = kwargs.get("codex_agents", [])- codex_models = kwargs.get("codex_models", [])- backend_reasoning_options = kwargs.get("backend_reasoning_options", {})-- def _routing_value(field_name: str) -> Optional[str]:- if field_name in draft_routing:- return draft_routing[field_name]- return getattr(current_routing, field_name, None) if current_routing else None-- # Store selected backend for the final submit handler- user_id = kwargs.get("_user_id", "unknown")- cache_key = f"{channel_id}:{user_id}"- cache = self._routing_cache.get(cache_key, {})- cache["_selected_backend"] = selected_backend- cache.setdefault("draft_routing", self._routing_draft_from_current(current_routing, selected_backend))- self._routing_cache[cache_key] = cache-- form_elements: list = [- # Show selected backend (read-only display)- {"tag": "markdown", "content": f"**{t('modal.routing.backend')}**: `{selected_backend}`"},- ]-- # ---- OpenCode section ----- if selected_backend == "opencode":- # OpenCode agent selector- if opencode_agents:- oc_agent_options = [{"text": {"tag": "plain_text", "content": "(Default)"}, "value": "__default__"}]- for agent_info in opencode_agents:- name = agent_info if isinstance(agent_info, str) else agent_info.get("name", str(agent_info))- oc_agent_options.append({"text": {"tag": "plain_text", "content": name}, "value": name})- oc_current_agent = _routing_value("opencode_agent")- form_elements.append({"tag": "markdown", "content": t("modal.routing.opencodeAgent")})- form_elements.append(- {- "tag": "select_static",- "name": "opencode_agent",- "placeholder": {"tag": "plain_text", "content": t("modal.routing.selectOpencodeAgent")},- "options": oc_agent_options,- "initial_option": oc_current_agent if oc_current_agent else "__default__",- }- )-- # OpenCode model selector (using shared utility)- oc_current_model = _routing_value("opencode_model")- preferred_providers = resolve_opencode_provider_preferences(- opencode_default_config,- oc_current_model,- )- allowed_providers = resolve_opencode_allowed_providers(- opencode_default_config,- opencode_models,- )- model_entries = build_opencode_model_option_items(- opencode_models,- max_total=99,- preferred_providers=preferred_providers,- allowed_providers=allowed_providers,- )- if model_entries:- oc_model_options = [{"text": {"tag": "plain_text", "content": "(Default)"}, "value": "__default__"}]- for entry in model_entries:- label = entry.get("label", "")- value = entry.get("value", "")- if not label or not value:- continue- oc_model_options.append({"text": {"tag": "plain_text", "content": label[:60]}, "value": value})- form_elements.append({"tag": "markdown", "content": t("modal.routing.model")})- form_elements.append(- {- "tag": "select_static",- "name": "opencode_model",- "placeholder": {"tag": "plain_text", "content": t("modal.routing.selectModel")},- "options": oc_model_options,- "initial_option": oc_current_model if oc_current_model else "__default__",- }- )-- # OpenCode reasoning effort (using shared utility)- re_entries = build_reasoning_effort_options(opencode_models, oc_current_model)- re_options = []- for entry in re_entries:- label = entry.get("label", "")- value = entry.get("value", "")- if not label or not value:- continue- re_options.append({"text": {"tag": "plain_text", "content": label}, "value": value})- oc_current_re = _routing_value("opencode_reasoning_effort")- if re_options:- form_elements.append({"tag": "markdown", "content": t("modal.routing.reasoningEffort")})- form_elements.append(- {- "tag": "select_static",- "name": "opencode_reasoning",- "placeholder": {"tag": "plain_text", "content": t("modal.routing.selectReasoningEffort")},- "options": re_options,- "initial_option": oc_current_re if oc_current_re else "__default__",- }- )-- # ---- Claude section ----- elif selected_backend == "claude":- cl_current_model = _routing_value("claude_model")- # Claude agent selector- if claude_agents:- cl_agent_options = [{"text": {"tag": "plain_text", "content": "(Default)"}, "value": "__default__"}]- for agent_info in claude_agents:- name = agent_info if isinstance(agent_info, str) else agent_info.get("name", str(agent_info))- cl_agent_options.append({"text": {"tag": "plain_text", "content": name}, "value": name})- cl_current_agent = _routing_value("claude_agent")- form_elements.append({"tag": "markdown", "content": t("modal.routing.claudeAgent")})- form_elements.append(- {- "tag": "select_static",- "name": "claude_agent",- "placeholder": {"tag": "plain_text", "content": t("modal.routing.selectClaudeAgent")},- "options": cl_agent_options,- "initial_option": cl_current_agent if cl_current_agent else "__default__",- }- )-- # Claude model selector- if claude_models:- cl_model_options = [{"text": {"tag": "plain_text", "content": "(Default)"}, "value": "__default__"}]- for m in claude_models:- mid = m if isinstance(m, str) else m.get("id", str(m))- cl_model_options.append(- {"text": {"tag": "plain_text", "content": format_claude_model_label(mid)}, "value": mid}- )- form_elements.append({"tag": "markdown", "content": t("modal.routing.model")})- form_elements.append(- {- "tag": "select_static",- "name": "claude_model",- "placeholder": {"tag": "plain_text", "content": t("modal.routing.selectModel")},- "options": cl_model_options,- "initial_option": cl_current_model if cl_current_model else "__default__",- }- )-- cl_current_re = _routing_value("claude_reasoning_effort")- cl_re_defs = resolve_model_reasoning_options(- backend_reasoning_options.get("claude"),- cl_current_model,- build_claude_reasoning_options(cl_current_model),- )- if cl_current_re not in {item["value"] for item in cl_re_defs}:- cl_current_re = None- cl_re_options = []- for item in cl_re_defs:- cl_re_options.append({"text": {"tag": "plain_text", "content": item["label"]}, "value": item["value"]})- form_elements.append({"tag": "markdown", "content": t("modal.routing.reasoningEffort")})+ cache = self._routing_cache.setdefault(f"{channel_id}:{user_id}", {})+ cache.setdefault("routing", RoutingModalData(registered_backends=[], current_backend="", current_routing=None))+ menu = cache["routing"].menu(selected_backend)+ draft = self._routing_draft(cache, selected_backend)+ backend_name = display_name_for_backend(selected_backend)+ default = RouteOption(DEFAULT_OPTION_VALUE, "")+ form_elements: list = [{"tag": "markdown", "content": f"**{t('modal.routing.backend')}**: {backend_name}"}]++ def _select(name: str, label: str, placeholder: str, options, current, *, effort: bool = False) -> None:+ form_elements.append({"tag": "markdown", "content": label})form_elements.append({"tag": "select_static",- "name": "claude_reasoning",- "placeholder": {"tag": "plain_text", "content": t("modal.routing.selectReasoningEffort")},- "options": cl_re_options,- "initial_option": cl_current_re if cl_current_re else "__default__",+ "name": name,+ "placeholder": {"tag": "plain_text", "content": placeholder},+ "options": [+ {+ "text": {"tag": "plain_text", "content": route_option_label(t, option, effort=effort)[:60]},+ "value": option.value,+ }+ for option in [default, *options]+ ],+ "initial_option": menu.shown_value(current),})- # ---- Codex section ----- elif selected_backend == "codex":- if codex_agents:- cx_agent_options = [{"text": {"tag": "plain_text", "content": "(Default)"}, "value": "__default__"}]- for agent_info in codex_agents:- name = agent_info if isinstance(agent_info, str) else agent_info.get("name", str(agent_info))- cx_agent_options.append({"text": {"tag": "plain_text", "content": name}, "value": name})- cx_current_agent = _routing_value("codex_agent")- form_elements.append({"tag": "markdown", "content": t("modal.routing.codexAgent")})- form_elements.append(- {- "tag": "select_static",- "name": "codex_agent",- "placeholder": {"tag": "plain_text", "content": t("modal.routing.selectCodexAgent")},- "options": cx_agent_options,- "initial_option": cx_current_agent if cx_current_agent else "__default__",- }- )-- # Codex model selector- if codex_models:- cx_model_options = [{"text": {"tag": "plain_text", "content": "(Default)"}, "value": "__default__"}]- for m in codex_models:- mid = m if isinstance(m, str) else m.get("id", str(m))- cx_model_options.append({"text": {"tag": "plain_text", "content": mid}, "value": mid})- cx_current_model = _routing_value("codex_model")- form_elements.append({"tag": "markdown", "content": t("modal.routing.model")})- form_elements.append(- {- "tag": "select_static",- "name": "codex_model",- "placeholder": {"tag": "plain_text", "content": t("modal.routing.selectModel")},- "options": cx_model_options,- "initial_option": cx_current_model if cx_current_model else "__default__",- }- )-- cx_current_model = _routing_value("codex_model")- codex_re_defs = resolve_model_reasoning_options(- backend_reasoning_options.get("codex"),- cx_current_model,- build_codex_reasoning_options(),+ variants = menu.variant_options(draft.variant)+ if variants:+ _select(+ f"route_variant:{selected_backend}",+ t("modal.routing.backendAgent", backend=backend_name),+ t("modal.routing.selectBackendAgent", backend=backend_name),+ variants,+ draft.variant,)- cx_re_options = []- for item in codex_re_defs:- cx_re_options.append({"text": {"tag": "plain_text", "content": item["label"]}, "value": item["value"]})- cx_current_re = _routing_value("codex_reasoning_effort")- if cx_current_re not in {item["value"] for item in codex_re_defs}:- cx_current_re = None- form_elements.append({"tag": "markdown", "content": t("modal.routing.codexReasoningEffort")})- form_elements.append(- {- "tag": "select_static",- "name": "codex_reasoning",- "placeholder": {"tag": "plain_text", "content": t("modal.routing.selectReasoningEffort")},- "options": cx_re_options,- "initial_option": cx_current_re if cx_current_re else "__default__",- }- )-- # Submit button+ _select(+ f"route_model:{selected_backend}",+ t("modal.routing.model"),+ t("modal.routing.selectModel"),+ menu.model_options(draft.model),+ draft.model,+ )+ _select(+ f"route_effort:{selected_backend}",+ t("modal.routing.reasoningEffort"),+ t("modal.routing.selectReasoningEffort"),+ menu.effort_options(draft.model, draft.reasoning_effort),+ draft.reasoning_effort,+ effort=True,+ )form_elements.append({"tag": "button","text": {"tag": "plain_text", "content": t("common.save")},"type": "primary","action_type": "form_submit",- "name": "routing_submit",+ "name": f"routing_submit:{selected_backend}",})-return {"schema": "2.0","header": {- "title": {"tag": "plain_text", "content": f"{t('modal.routing.title')} — {selected_backend}"},+ "title": {"tag": "plain_text", "content": f"{t('modal.routing.title')} — {backend_name}"},"template": "blue",},"body": {"direction": "vertical",- "elements": [- {- "tag": "form",- "name": "routing_options_form",- "elements": form_elements,- },- ],+ "elements": [{"tag": "form", "name": "routing_options_form", "elements": form_elements}],},}- async def _send_routing_backend_options_card(- self,- channel_id: str,- selected_backend: str,- **kwargs,- ):+ async def _send_routing_backend_options_card(self, channel_id: str, selected_backend: str, user_id: str):"""Step 2: send a card with options specific to the selected backend."""- card = self._build_routing_backend_options_card(channel_id, selected_backend, **kwargs)-+ card = self._build_routing_backend_options_card(channel_id, selected_backend, user_id)ctx = MessageContext(user_id="system", channel_id=channel_id or "")try:await self._send_card_to_channel(ctx, card)diff --git a/modules/im/slack.py b/modules/im/slack.pyindex 4d4ebeaee..ecbc437a0 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -1,5 +1,5 @@import asyncio-from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS, display_name_for_backend+from modules.agents.catalog import NATIVE_CLI_BACKENDS, display_name_for_backendimport hashlibimport jsonimport logging@@ -42,22 +42,19 @@ from .formatters import (from .slack_modal import parse_routing_modal_selectionfrom vibe.i18n import get_supported_languages, t as i18n_tfrom vibe.proxy import resolve_proxy-from modules.agents.opencode.utils import (- build_claude_reasoning_options,- build_opencode_model_option_items,- build_codex_reasoning_options,- format_claude_model_label,- build_reasoning_effort_options,- resolve_model_reasoning_options,- resolve_opencode_allowed_providers,- resolve_opencode_provider_preferences,+from core.modals import (+ DEFAULT_OPTION_VALUE,+ BackendRouteMenu,+ RouteDraft,+ RouteOption,+ RoutingModalData,+ route_option_label,)from modules.agents.native_sessions.display import format_display_summary, format_display_timefrom modules.agents.native_sessions.types import NativeResumeSessionlogger = logging.getLogger(__name__)-_UNSET = object()_SLACK_SECTION_TEXT_LIMIT = 3000_SLACK_MARKDOWN_TEXT_LIMIT = 12000_BARE_HTTP_URL_RE = re.compile(r"https?://[^\s<>\|]+")@@ -93,6 +90,10 @@ def _shown_in_mrkdwn(character: str) -> str:class SlackBot(BaseIMClient):"""Slack implementation of the IM client"""+ # A static select holds at most 100 options, each value at most 150 characters.+ route_option_limit = 100+ route_option_value_limit = 150+def __init__(self, config: SlackConfig):super().__init__(config)self.config = config@@ -2538,31 +2539,17 @@ class SlackBot(BaseIMClient):await self.on_callback_query_callback(context, callback_data)elif action_type in {"static_select", "external_select"}:- action_id = action.get("action_id")- # Trigger modal update for backend selection and all backend-specific selectors- routing_modal_actions = {- "backend_select",- "opencode_agent_select",- "opencode_model_select",- "claude_agent_select",- "claude_model_select",- "codex_model_select",- }- # Also check for prefixed action IDs (reasoning selects have unique suffixes)- should_update = (- action_id in routing_modal_actions- or (action_id and action_id.startswith("opencode_reasoning_select"))- or (action_id and action_id.startswith("codex_reasoning_select"))+ # A routing form refreshes when the backend or the model changes: each decides what the+ # fields below it offer.+ should_update = view.get("callback_id") == "routing_modal" and (+ action.get("action_id") == "backend_select"+ or str(action.get("block_id") or "").startswith("route_model:"))if should_update:if hasattr(self, "_on_routing_modal_update"):channel_from_view = view.get("private_metadata")effective_channel = channel_from_view or channel_id- selection = parse_routing_modal_selection(- view=view,- action=action,- fallback_selected_backend="",- )+ selection = parse_routing_modal_selection(view=view, action=action)await self._on_routing_modal_update(user_id=user.get("id"),channel_id=effective_channel,@@ -2759,115 +2746,18 @@ class SlackBot(BaseIMClient):)elif callback_id == "routing_modal":- # Handle routing modal submissionuser_id = payload.get("user", {}).get("id")- values = view.get("state", {}).get("values", {})channel_id = view.get("private_metadata")-- # Extract backend- backend_data = values.get("backend_block", {}).get("backend_select", {})- backend = backend_data.get("selected_option", {}).get("value")-- # Extract OpenCode agent (optional)- oc_agent_data = values.get("opencode_agent_block", {}).get("opencode_agent_select", {})- oc_agent = oc_agent_data.get("selected_option", {}).get("value")- if oc_agent == "__default__":- oc_agent = None-- # Extract OpenCode model (optional)- oc_model_data = values.get("opencode_model_block", {}).get("opencode_model_select", {})- oc_model = oc_model_data.get("selected_option", {}).get("value")- if oc_model == "__default__":- oc_model = None-- # Extract OpenCode reasoning effort (optional)- oc_reasoning = None- reasoning_block = values.get("opencode_reasoning_block", {})- if isinstance(reasoning_block, dict):- for action_id, action_data in reasoning_block.items():- if (- isinstance(action_id, str)- and action_id.startswith("opencode_reasoning_select")- and isinstance(action_data, dict)- ):- oc_reasoning = action_data.get("selected_option", {}).get("value")- break- if oc_reasoning == "__default__":- oc_reasoning = None-- # Extract require_mention (optional)- require_mention_data = values.get("require_mention_block", {}).get("require_mention_select", {})- require_mention_value = require_mention_data.get("selected_option", {}).get("value")- # Convert to Optional[bool]: "__default__" -> None, "true" -> True, "false" -> False- if require_mention_value == "__default__":- require_mention = None- elif require_mention_value == "true":- require_mention = True- elif require_mention_value == "false":- require_mention = False- else:- require_mention = None-- # Extract Claude agent (optional)- claude_agent_data = values.get("claude_agent_block", {}).get("claude_agent_select", {})- claude_agent = claude_agent_data.get("selected_option", {}).get("value")- if claude_agent == "__default__":- claude_agent = None-- # Extract Claude model (optional)- claude_model_data = values.get("claude_model_block", {}).get("claude_model_select", {})- claude_model = claude_model_data.get("selected_option", {}).get("value")- if claude_model == "__default__":- claude_model = None-- # Extract Claude reasoning effort (optional)- claude_reasoning_data = values.get("claude_reasoning_block", {}).get("claude_reasoning_select", {})- claude_reasoning = claude_reasoning_data.get("selected_option", {}).get("value")- if claude_reasoning == "__default__":- claude_reasoning = None-- # Extract Codex model (optional)- codex_agent_data = values.get("codex_agent_block", {}).get("codex_agent_select", {})- codex_agent = codex_agent_data.get("selected_option", {}).get("value")- if codex_agent == "__default__":- codex_agent = None-- # Extract Codex model (optional)- codex_model_data = values.get("codex_model_block", {}).get("codex_model_select", {})- codex_model = codex_model_data.get("selected_option", {}).get("value")- if codex_model == "__default__":- codex_model = None-- # Extract Codex reasoning effort (optional)- codex_reasoning = None- codex_reasoning_block = values.get("codex_reasoning_block", {})- if isinstance(codex_reasoning_block, dict):- for action_id, action_data in codex_reasoning_block.items():- if (- isinstance(action_id, str)- and action_id.startswith("codex_reasoning_select")- and isinstance(action_data, dict)- ):- codex_reasoning = action_data.get("selected_option", {}).get("value")- break- if codex_reasoning == "__default__":- codex_reasoning = None-- # Update routing via callback+ selection = parse_routing_modal_selection(view=view, action={})+ draft = selection.draft or RouteDraft()if hasattr(self, "_on_routing_update"):await self._on_routing_update(user_id=user_id,channel_id=channel_id,- backend=backend,- opencode_agent=oc_agent,- opencode_model=oc_model,- opencode_reasoning_effort=oc_reasoning,- claude_agent=claude_agent,- claude_model=claude_model,- claude_reasoning_effort=claude_reasoning,- codex_agent=codex_agent,- codex_model=codex_model,- codex_reasoning_effort=codex_reasoning,+ backend=selection.selected_backend,+ variant=draft.variant,+ model=draft.model,+ reasoning_effort=draft.reasoning_effort,is_dm=isinstance(channel_id, str) and channel_id.startswith("D"),)@@ -3553,68 +3443,39 @@ class SlackBot(BaseIMClient):def _build_routing_modal_view(self,channel_id: str,- registered_backends: list,- current_backend: str,- current_routing,- opencode_agents: list,- opencode_models: dict,- opencode_default_config: dict,- claude_agents: list = None,- claude_models: list = None,- codex_agents: list = None,- codex_models: list = None,- backend_reasoning_options: dict = None,- selected_backend: object = _UNSET,- selected_opencode_agent: object = _UNSET,- selected_opencode_model: object = _UNSET,- selected_opencode_reasoning: object = _UNSET,- selected_claude_agent: object = _UNSET,- selected_claude_model: object = _UNSET,- selected_claude_reasoning: object = _UNSET,- selected_codex_agent: object = _UNSET,- selected_codex_model: object = _UNSET,- selected_codex_reasoning: object = _UNSET,+ routing: RoutingModalData,+ selected_backend: Optional[str] = None,+ draft: Optional[RouteDraft] = None,) -> dict:- """Build modal view for agent/model routing settings."""- # Build backend options- backend_display_names = {- backend: display_name_for_backend(backend) for backend in AGENT_BACKENDS- }- backend_options = []- for backend in registered_backends:- display_name = backend_display_names.get(backend, backend.capitalize())- backend_options.append(- {- "text": {"type": "plain_text", "text": display_name},- "value": backend,- }- )-- # Find initial backend option- selected_backend_value = current_backend if selected_backend is _UNSET else selected_backend- initial_backend = None- for option in backend_options:- if option["value"] == selected_backend_value:- initial_backend = option- break- if initial_backend is None and backend_options:- initial_backend = backend_options[0]+ """Build the routing modal: the backend select, then the shown backend's route section.+ ``draft`` is the shown backend's choices; without one the section shows the stored route.+ """+ registered_backends = routing.registered_backends+ current_backend = routing.current_backend+ backend_options = [+ {"text": {"type": "plain_text", "text": display_name_for_backend(backend)}, "value": backend}+ for backend in registered_backends+ ]+ shown_backend = selected_backend if selected_backend in registered_backends else current_backend+ if shown_backend not in registered_backends:+ shown_backend = registered_backends[0] if registered_backends else Nonebackend_select = {"type": "static_select","action_id": "backend_select","placeholder": {"type": "plain_text", "text": self._t("modal.routing.selectBackend")},"options": backend_options,- "initial_option": initial_backend,}+ initial_backend = next((option for option in backend_options if option["value"] == shown_backend), None)+ if initial_backend is not None:+ backend_select["initial_option"] = initial_backend- # Build modal blocksblocks = [{"type": "section","text": {"type": "mrkdwn",- "text": f"*{self._t('modal.routing.currentBackend')}* {backend_display_names.get(current_backend, current_backend)}",+ "text": f"*{self._t('modal.routing.currentBackend')}* {display_name_for_backend(current_backend)}",},},{"type": "divider"},@@ -3626,563 +3487,20 @@ class SlackBot(BaseIMClient):"label": {"type": "plain_text", "text": self._t("modal.routing.backend")},},]-- # Determine effective backend for showing backend-specific options- effective_backend = selected_backend_value or current_backend or "opencode"- canonical_model = getattr(current_routing, "model", None) if current_routing else None- canonical_reasoning = getattr(current_routing, "reasoning_effort", None) if current_routing else None-- def _canonical_applies_to_backend(backend: str) -> bool:- return backend == (current_backend or "opencode")-- def _current_model_for_backend(field_name: str, backend: str) -> Optional[str]:- value = getattr(current_routing, field_name, None) if current_routing else None- if value is not None:- return value- if effective_backend == backend and _canonical_applies_to_backend(backend):- return canonical_model- return None-- def _current_reasoning_for_backend(field_name: str, backend: str) -> Optional[str]:- value = getattr(current_routing, field_name, None) if current_routing else None- if value is not None:- return value- if effective_backend == backend and _canonical_applies_to_backend(backend):- return canonical_reasoning- return None-- # OpenCode-specific options (only if opencode is selected)- if effective_backend == "opencode" and "opencode" in registered_backends:- # Get current opencode settings- if selected_opencode_agent is _UNSET:- current_oc_agent = current_routing.opencode_agent if current_routing else None- else:- current_oc_agent = selected_opencode_agent-- if selected_opencode_model is _UNSET:- current_oc_model = _current_model_for_backend("opencode_model", "opencode")- else:- current_oc_model = selected_opencode_model-- if selected_opencode_reasoning is _UNSET:- current_oc_reasoning = _current_reasoning_for_backend("opencode_reasoning_effort", "opencode")- else:- current_oc_reasoning = selected_opencode_reasoning-- # Build agent options- agent_options = [- {"text": {"type": "plain_text", "text": self._t("common.default")}, "value": "__default__"}- ]- for agent in opencode_agents:- agent_name = agent.get("name", "")- if agent_name:- agent_options.append(- {- "text": {"type": "plain_text", "text": agent_name},- "value": agent_name,- }- )-- # Find initial agent- initial_agent = agent_options[0] # Default- if current_oc_agent:- for opt in agent_options:- if opt["value"] == current_oc_agent:- initial_agent = opt- break-- agent_select = {- "type": "static_select",- "action_id": "opencode_agent_select",- "placeholder": {"type": "plain_text", "text": self._t("modal.routing.selectOpencodeAgent")},- "options": agent_options,- "initial_option": initial_agent,- }-- # Build model options- default_label = self._t("common.default")- model_options = [{"text": {"type": "plain_text", "text": default_label}, "value": "__default__"}]-- # Add models from providers (sorted, filtered, truncated)- preferred_providers = resolve_opencode_provider_preferences(- opencode_default_config,- current_oc_model,- )- allowed_providers = resolve_opencode_allowed_providers(- opencode_default_config,- opencode_models,- )- model_entries = build_opencode_model_option_items(- opencode_models,- max_total=99,- preferred_providers=preferred_providers,- allowed_providers=allowed_providers,- )- for entry in model_entries:- label = entry.get("label", "")- value = entry.get("value", "")- if not label or not value:- continue- model_options.append(- {- "text": {"type": "plain_text", "text": label[:75]}, # Slack limit- "value": value,- }- )-- # Find initial model- initial_model = model_options[0] # Default- if current_oc_model:- for opt in model_options:- if opt["value"] == current_oc_model:- initial_model = opt- break-- model_select = {- "type": "static_select",- "action_id": "opencode_model_select",- "placeholder": {"type": "plain_text", "text": self._t("modal.routing.selectModel")},- "options": model_options,- "initial_option": initial_model,- }-- # Build reasoning effort options dynamically based on model variants- target_model = current_oc_model-- reasoning_model_key = target_model or "__default__"- reasoning_action_id = (- "opencode_reasoning_select__" + hashlib.sha1(reasoning_model_key.encode("utf-8")).hexdigest()[:8]- )-- reasoning_entries = build_reasoning_effort_options(opencode_models, target_model)- reasoning_effort_options = []- for entry in reasoning_entries:- value = entry.get("value")- if not value:- continue- if value == "__default__":- label = self._t("common.default")- else:- translated = self._t(f"reasoning.{value}")- label = translated if translated != f"reasoning.{value}" else entry.get("label", value)- reasoning_effort_options.append(- {- "text": {"type": "plain_text", "text": label},- "value": value,- }- )-- # Find initial reasoning effort- initial_reasoning = reasoning_effort_options[0] # Default- if current_oc_reasoning:- for opt in reasoning_effort_options:- if opt["value"] == current_oc_reasoning:- initial_reasoning = opt- break-- reasoning_select = {- "type": "static_select",- "action_id": reasoning_action_id,- "placeholder": {"type": "plain_text", "text": self._t("modal.routing.selectReasoningEffort")},- "options": reasoning_effort_options,- "initial_option": initial_reasoning,- }-- # Add OpenCode section+ if shown_backend:blocks.extend(- [- {"type": "divider"},- {- "type": "section",- "text": {- "type": "mrkdwn",- "text": f"*{self._t('modal.routing.opencodeSettings')}*",- },- },- {- "type": "input",- "block_id": "opencode_agent_block",- "optional": True,- "dispatch_action": True,- "element": agent_select,- "label": {"type": "plain_text", "text": self._t("modal.routing.opencodeAgent")},- },- {- "type": "input",- "block_id": "opencode_model_block",- "optional": True,- "dispatch_action": True,- "element": model_select,- "label": {"type": "plain_text", "text": self._t("modal.routing.model")},- },- {- "type": "input",- "block_id": "opencode_reasoning_block",- "optional": True,- "element": reasoning_select,- "label": {"type": "plain_text", "text": self._t("modal.routing.reasoningEffort")},- },- ]- )-- # Claude-specific options (only if claude is selected)- if effective_backend == "claude" and "claude" in registered_backends:- claude_agents = claude_agents or []- claude_models = claude_models or []-- # Get current claude settings- if selected_claude_agent is _UNSET:- current_cl_agent = current_routing.claude_agent if current_routing else None- else:- current_cl_agent = selected_claude_agent-- if selected_claude_model is _UNSET:- current_cl_model = _current_model_for_backend("claude_model", "claude")- else:- current_cl_model = selected_claude_model-- if selected_claude_reasoning is _UNSET:- current_cl_reasoning = _current_reasoning_for_backend("claude_reasoning_effort", "claude")- else:- current_cl_reasoning = selected_claude_reasoning-- # Build agent options- cl_agent_options = [- {"text": {"type": "plain_text", "text": self._t("common.default")}, "value": "__default__"}- ]- for agent in claude_agents:- agent_id = agent.get("id", "")- agent_name = agent.get("name", agent_id)- if agent_id:- cl_agent_options.append(- {- "text": {"type": "plain_text", "text": agent_name[:75]},- "value": agent_id,- }- )-- # Find initial agent- initial_cl_agent = cl_agent_options[0]- if current_cl_agent:- for opt in cl_agent_options:- if opt["value"] == current_cl_agent:- initial_cl_agent = opt- break-- cl_agent_select = {- "type": "static_select",- "action_id": "claude_agent_select",- "placeholder": {"type": "plain_text", "text": self._t("modal.routing.selectClaudeAgent")},- "options": cl_agent_options,- "initial_option": initial_cl_agent,- }-- # Build model options- cl_model_options = [- {"text": {"type": "plain_text", "text": self._t("common.default")}, "value": "__default__"}- ]- for model in claude_models:- if model:- model_label = format_claude_model_label(model)- cl_model_options.append(- {- "text": {"type": "plain_text", "text": model_label[:75]},- "value": model,- }- )-- # Add current model if not in list (preserve custom models)- if current_cl_model and not any(opt["value"] == current_cl_model for opt in cl_model_options):- model_label = format_claude_model_label(current_cl_model)- cl_model_options.append(- {- "text": {"type": "plain_text", "text": model_label[:75]},- "value": current_cl_model,- }- )-- # Limit to 100 options- if len(cl_model_options) > 100:- cl_model_options = cl_model_options[:100]-- # Find initial model- initial_cl_model = cl_model_options[0]- if current_cl_model:- for opt in cl_model_options:- if opt["value"] == current_cl_model:- initial_cl_model = opt- break-- cl_model_select = {- "type": "static_select",- "action_id": "claude_model_select",- "placeholder": {"type": "plain_text", "text": self._t("modal.routing.selectModel")},- "options": cl_model_options,- "initial_option": initial_cl_model,- }-- cl_reasoning_entries = resolve_model_reasoning_options(- (backend_reasoning_options or {}).get("claude"),- current_cl_model,- build_claude_reasoning_options(current_cl_model),- )- selected_cl_reasoning = (- current_cl_reasoning if current_cl_reasoning not in (None, "__default__") else "__default__"- )- available_cl_reasoning = {entry.get("value") for entry in cl_reasoning_entries}- if selected_cl_reasoning not in available_cl_reasoning:- selected_cl_reasoning = "__default__"-- cl_reasoning_options = []- for entry in cl_reasoning_entries:- value = entry.get("value")- if not value:- continue- if value == "__default__":- label = self._t("common.default")- else:- translated = self._t(f"reasoning.{value}")- label = translated if translated != f"reasoning.{value}" else entry.get("label", value)- cl_reasoning_options.append(- {- "text": {"type": "plain_text", "text": label},- "value": value,- }+ self._route_section_blocks(+ shown_backend,+ routing.menu(shown_backend),+ draft if draft is not None else routing.stored_draft(shown_backend),)-- initial_cl_reasoning = next(- (opt for opt in cl_reasoning_options if opt["value"] == selected_cl_reasoning),- cl_reasoning_options[0],)-- cl_reasoning_select = {- "type": "static_select",- "action_id": "claude_reasoning_select",- "placeholder": {"type": "plain_text", "text": self._t("modal.routing.selectReasoningEffort")},- "options": cl_reasoning_options,- "initial_option": initial_cl_reasoning,- }-- # Add Claude section- blocks.extend(- [- {"type": "divider"},- {- "type": "section",- "text": {- "type": "mrkdwn",- "text": f"*{self._t('modal.routing.claudeSettings')}*",- },- },- {- "type": "input",- "block_id": "claude_agent_block",- "optional": True,- "element": cl_agent_select,- "label": {"type": "plain_text", "text": self._t("modal.routing.claudeAgent")},- },- {- "type": "input",- "block_id": "claude_model_block",- "optional": True,- "dispatch_action": True,- "element": cl_model_select,- "label": {"type": "plain_text", "text": self._t("modal.routing.model")},- },- {- "type": "input",- "block_id": "claude_reasoning_block",- "optional": True,- "element": cl_reasoning_select,- "label": {"type": "plain_text", "text": self._t("modal.routing.reasoningEffort")},- },- ]- )-- # Codex-specific options (only if codex is selected)- if effective_backend == "codex" and "codex" in registered_backends:- codex_agents = codex_agents or []- codex_models = codex_models or []-- # Get current codex settings- if selected_codex_agent is _UNSET:- current_cx_agent = getattr(current_routing, "codex_agent", None) if current_routing else None- else:- current_cx_agent = selected_codex_agent-- if selected_codex_model is _UNSET:- current_cx_model = _current_model_for_backend("codex_model", "codex")- else:- current_cx_model = selected_codex_model-- if selected_codex_reasoning is _UNSET:- current_cx_reasoning = _current_reasoning_for_backend("codex_reasoning_effort", "codex")- else:- current_cx_reasoning = selected_codex_reasoning-- cx_agent_options = [- {"text": {"type": "plain_text", "text": self._t("common.default")}, "value": "__default__"}- ]- for agent in codex_agents:- agent_id = agent.get("id", "")- agent_name = agent.get("name", agent_id)- if agent_id:- cx_agent_options.append(- {- "text": {"type": "plain_text", "text": agent_name[:75]},- "value": agent_id,- }- )-- initial_cx_agent = cx_agent_options[0]- if current_cx_agent:- for opt in cx_agent_options:- if opt["value"] == current_cx_agent:- initial_cx_agent = opt- break-- cx_agent_select = {- "type": "static_select",- "action_id": "codex_agent_select",- "placeholder": {"type": "plain_text", "text": self._t("modal.routing.selectCodexAgent")},- "options": cx_agent_options,- "initial_option": initial_cx_agent,- }-- # Build model options- cx_model_options = [- {"text": {"type": "plain_text", "text": self._t("common.default")}, "value": "__default__"}- ]- for model in codex_models:- if model:- cx_model_options.append(- {- "text": {"type": "plain_text", "text": model[:75]},- "value": model,- }- )-- # Add current model if not in list (preserve custom models)- if current_cx_model and not any(opt["value"] == current_cx_model for opt in cx_model_options):- cx_model_options.append(- {- "text": {"type": "plain_text", "text": current_cx_model[:75]},- "value": current_cx_model,- }- )-- # Limit to 100 options- if len(cx_model_options) > 100:- cx_model_options = cx_model_options[:100]-- # Find initial model- initial_cx_model = cx_model_options[0]- if current_cx_model:- for opt in cx_model_options:- if opt["value"] == current_cx_model:- initial_cx_model = opt- break-- cx_model_select = {- "type": "static_select",- "action_id": "codex_model_select",- "placeholder": {"type": "plain_text", "text": self._t("modal.routing.selectModel")},- "options": cx_model_options,- "initial_option": initial_cx_model,- }-- # Build reasoning effort options from centralized Codex definition- codex_reasoning_entries = resolve_model_reasoning_options(- (backend_reasoning_options or {}).get("codex"),- current_cx_model,- build_codex_reasoning_options(),- )- selected_cx_reasoning = (- current_cx_reasoning if current_cx_reasoning not in (None, "__default__") else "__default__"- )- available_cx_reasoning = {entry.get("value") for entry in codex_reasoning_entries}- if selected_cx_reasoning not in available_cx_reasoning:- selected_cx_reasoning = "__default__"-- cx_reasoning_options = []- for entry in codex_reasoning_entries:- value = entry.get("value")- if not value:- continue- if value == "__default__":- label = self._t("common.default")- else:- translated = self._t(f"reasoning.{value}")- label = translated if translated != f"reasoning.{value}" else entry.get("label", value)- cx_reasoning_options.append(- {- "text": {"type": "plain_text", "text": label},- "value": value,- }- )-- # Find initial reasoning- initial_cx_reasoning = next(- (opt for opt in cx_reasoning_options if opt["value"] == selected_cx_reasoning),- cx_reasoning_options[0],- )-- cx_reasoning_select = {- "type": "static_select",- "action_id": "codex_reasoning_select",- "placeholder": {"type": "plain_text", "text": self._t("modal.routing.selectReasoningEffort")},- "options": cx_reasoning_options,- "initial_option": initial_cx_reasoning,- }-- # Add Codex section- blocks.extend(- [- {"type": "divider"},- {- "type": "section",- "text": {- "type": "mrkdwn",- "text": f"*{self._t('modal.routing.codexSettings')}*",- },- },- {- "type": "input",- "block_id": "codex_agent_block",- "optional": True,- "element": cx_agent_select,- "label": {"type": "plain_text", "text": self._t("modal.routing.codexAgent")},- },- {- "type": "input",- "block_id": "codex_model_block",- "optional": True,- "element": cx_model_select,- "label": {"type": "plain_text", "text": self._t("modal.routing.model")},- },- {- "type": "input",- "block_id": "codex_reasoning_block",- "optional": True,- "element": cx_reasoning_select,- "label": {"type": "plain_text", "text": self._t("modal.routing.codexReasoningEffort")},- },- ]- )-- # Add tipblocks.append({"type": "context",- "elements": [- {- "type": "mrkdwn",- "text": f"_💡 {self._t('modal.routing.tip')}_",- }- ],+ "elements": [{"type": "mrkdwn", "text": f"_💡 {self._t('modal.routing.tip')}_"}],})-return {"type": "modal","callback_id": "routing_modal",@@ -4193,6 +3511,87 @@ class SlackBot(BaseIMClient):"blocks": blocks,}+ def _route_section_blocks(self, backend: str, menu: BackendRouteMenu, draft: RouteDraft) -> list[dict]:+ """One backend's route fields, keyed by backend so a backend switch never carries another's input.++ Slack keeps an input's state across ``views.update`` while its block stays the same, so the effort block+ is also keyed by model: a model change then offers that model's efforts afresh.+ """+ backend_name = display_name_for_backend(backend)+ default = RouteOption(DEFAULT_OPTION_VALUE, "")++ def _select(block_id, label, placeholder, options, current, *, effort=False, dispatch=False) -> dict:+ slack_options = [+ {+ "text": {"type": "plain_text", "text": route_option_label(self._t, option, effort=effort)[:75]},+ "value": option.value,+ }+ for option in [default, *options]+ ]+ block = {+ "type": "input",+ "block_id": block_id,+ "optional": True,+ "element": {+ "type": "static_select",+ "action_id": block_id.split(":", 1)[0],+ "placeholder": {"type": "plain_text", "text": placeholder},+ "options": slack_options,+ "initial_option": next(+ (option for option in slack_options if option["value"] == menu.shown_value(current)),+ slack_options[0],+ ),+ },+ "label": {"type": "plain_text", "text": label},+ }+ if dispatch:+ block["dispatch_action"] = True+ return block++ blocks: list[dict] = [+ {"type": "divider"},+ {+ "type": "section",+ "text": {+ "type": "mrkdwn",+ "text": f"*{self._t('modal.routing.backendSettings', backend=backend_name)}*",+ },+ },+ ]+ variants = menu.variant_options(draft.variant)+ if variants:+ blocks.append(+ _select(+ f"route_variant:{backend}",+ self._t("modal.routing.backendAgent", backend=backend_name),+ self._t("modal.routing.selectBackendAgent", backend=backend_name),+ variants,+ draft.variant,+ )+ )+ blocks.append(+ _select(+ f"route_model:{backend}",+ self._t("modal.routing.model"),+ self._t("modal.routing.selectModel"),+ menu.model_options(draft.model),+ draft.model,+ dispatch=True,+ )+ )+ effort_key = hashlib.sha256((draft.model or DEFAULT_OPTION_VALUE).encode("utf-8")).hexdigest()+ blocks.append(+ _select(+ f"route_effort:{backend}:{effort_key}",+ self._t("modal.routing.reasoningEffort"),+ self._t("modal.routing.selectReasoningEffort"),+ menu.effort_options(draft.model, draft.reasoning_effort),+ draft.reasoning_effort,+ effort=True,+ )+ )+ return blocks+async def open_question_modal(self,trigger_id: str,@@ -4335,40 +3734,10 @@ class SlackBot(BaseIMClient):await self.web_client.views_open(trigger_id=trigger_id, view=view)- async def open_routing_modal(- self,- trigger_id: str,- channel_id: str,- registered_backends: list,- current_backend: str,- current_routing, # Optional[ChannelRouting]- opencode_agents: list,- opencode_models: dict,- opencode_default_config: dict,- claude_agents: list = None,- claude_models: list = None,- codex_agents: list = None,- codex_models: list = None,- backend_reasoning_options: dict = None,- ):+ async def open_routing_modal(self, trigger_id: str, channel_id: str, routing: RoutingModalData):"""Open a modal dialog for agent/model routing settings"""self._ensure_clients()-- view = self._build_routing_modal_view(- channel_id=channel_id,- registered_backends=registered_backends,- current_backend=current_backend,- current_routing=current_routing,- opencode_agents=opencode_agents,- opencode_models=opencode_models,- opencode_default_config=opencode_default_config,- claude_agents=claude_agents,- claude_models=claude_models,- codex_agents=codex_agents,- codex_models=codex_models,- backend_reasoning_options=backend_reasoning_options,- )-+ view = self._build_routing_modal_view(channel_id=channel_id, routing=routing)try:await self.web_client.views_open(trigger_id=trigger_id, view=view)except SlackApiError as e:@@ -4380,56 +3749,15 @@ class SlackBot(BaseIMClient):view_id: str,view_hash: str,channel_id: str,- registered_backends: list,- current_backend: str,- current_routing,- opencode_agents: list,- opencode_models: dict,- opencode_default_config: dict,- claude_agents: list = None,- claude_models: list = None,- codex_agents: list = None,- codex_models: list = None,- backend_reasoning_options: dict = None,+ routing: RoutingModalData,selected_backend: Optional[str] = None,- selected_opencode_agent: Optional[str] = None,- selected_opencode_model: Optional[str] = None,- selected_opencode_reasoning: Optional[str] = None,- selected_claude_agent: Optional[str] = None,- selected_claude_model: Optional[str] = None,- selected_claude_reasoning: Optional[str] = None,- selected_codex_agent: Optional[str] = None,- selected_codex_model: Optional[str] = None,- selected_codex_reasoning: Optional[str] = None,+ draft: Optional[RouteDraft] = None,) -> None:"""Update routing modal when selections change."""self._ensure_clients()-view = self._build_routing_modal_view(- channel_id=channel_id,- registered_backends=registered_backends,- current_backend=current_backend,- current_routing=current_routing,- opencode_agents=opencode_agents,- opencode_models=opencode_models,- opencode_default_config=opencode_default_config,- claude_agents=claude_agents,- claude_models=claude_models,- codex_agents=codex_agents,- codex_models=codex_models,- backend_reasoning_options=backend_reasoning_options,- selected_backend=selected_backend,- selected_opencode_agent=selected_opencode_agent,- selected_opencode_model=selected_opencode_model,- selected_opencode_reasoning=selected_opencode_reasoning,- selected_claude_agent=selected_claude_agent,- selected_claude_model=selected_claude_model,- selected_claude_reasoning=selected_claude_reasoning,- selected_codex_agent=selected_codex_agent,- selected_codex_model=selected_codex_model,- selected_codex_reasoning=selected_codex_reasoning,+ channel_id=channel_id, routing=routing, selected_backend=selected_backend, draft=draft)-try:await self.web_client.views_update(view_id=view_id, hash=view_hash, view=view)except SlackApiError as e:diff --git a/modules/im/slack_modal.py b/modules/im/slack_modal.pyindex e73f37670..7681c71a2 100644--- a/modules/im/slack_modal.py+++ b/modules/im/slack_modal.py@@ -2,93 +2,66 @@from __future__ import annotations+from dataclasses import replacefrom typing import Optional-from core.modals import RoutingModalSelection+from core.modals import DEFAULT_OPTION_VALUE, RouteDraft, RoutingModalSelection-def _extract_selected_value(values: dict, block_id: str, action_id: str) -> Optional[str]:- data = values.get(block_id, {}).get(action_id, {})- return data.get("selected_option", {}).get("value")---def _extract_prefixed_selected_value(values: dict, block_id: str, action_prefix: str) -> Optional[str]:- block = values.get(block_id, {})+def _selected_value(block: object) -> Optional[str]:if not isinstance(block, dict):return None- for dynamic_action_id, action_data in block.items():- if (- isinstance(dynamic_action_id, str)- and dynamic_action_id.startswith(action_prefix)- and isinstance(action_data, dict)- ):- return action_data.get("selected_option", {}).get("value")+ for action_data in block.values():+ if isinstance(action_data, dict):+ value = (action_data.get("selected_option") or {}).get("value")+ if isinstance(value, str):+ return valuereturn None-def _normalize_default(value: Optional[str]) -> Optional[str]:- if value == "__default__":- return None- return value---def parse_routing_modal_selection(- *,- view: dict,- action: dict,- fallback_selected_backend: str,-) -> RoutingModalSelection:- """Parse Slack routing modal state into normalized selection model."""- values = view.get("state", {}).get("values", {})-- selected_backend = _extract_selected_value(values, "backend_block", "backend_select") or fallback_selected_backend- selected_action_id = action.get("action_id")-- selected_value = None- selected_option = action.get("selected_option")- if isinstance(selected_option, dict):- selected_value = selected_option.get("value")+def _choice(value: Optional[str]) -> Optional[str]:+ return None if value in (None, DEFAULT_OPTION_VALUE) else value- oc_agent = _extract_selected_value(values, "opencode_agent_block", "opencode_agent_select")- oc_model = _extract_selected_value(values, "opencode_model_block", "opencode_model_select")- oc_reasoning = _extract_prefixed_selected_value(values, "opencode_reasoning_block", "opencode_reasoning_select")- claude_agent = _extract_selected_value(values, "claude_agent_block", "claude_agent_select")- claude_model = _extract_selected_value(values, "claude_model_block", "claude_model_select")- claude_reasoning = _extract_selected_value(values, "claude_reasoning_block", "claude_reasoning_select")- codex_agent = _extract_selected_value(values, "codex_agent_block", "codex_agent_select")- codex_model = _extract_selected_value(values, "codex_model_block", "codex_model_select")- codex_reasoning = _extract_prefixed_selected_value(values, "codex_reasoning_block", "codex_reasoning_select")+def parse_routing_modal_selection(*, view: dict, action: dict) -> RoutingModalSelection:+ """Parse the routing modal's state into the shown backend and its route choices.- if isinstance(selected_action_id, str) and isinstance(selected_value, str):- if selected_action_id == "opencode_agent_select":- oc_agent = selected_value- elif selected_action_id == "opencode_model_select":- oc_model = selected_value- elif selected_action_id.startswith("opencode_reasoning_select"):- oc_reasoning = selected_value- elif selected_action_id == "claude_agent_select":- claude_agent = selected_value- elif selected_action_id == "claude_model_select":- claude_model = selected_value- elif selected_action_id == "claude_reasoning_select":- claude_reasoning = selected_value- elif selected_action_id == "codex_agent_select":- codex_agent = selected_value- elif selected_action_id == "codex_model_select":- codex_model = selected_value- elif selected_action_id.startswith("codex_reasoning_select"):- codex_reasoning = selected_value-- return RoutingModalSelection(- selected_backend=selected_backend,- selected_opencode_agent=_normalize_default(oc_agent),- selected_opencode_model=_normalize_default(oc_model),- selected_opencode_reasoning=_normalize_default(oc_reasoning),- selected_claude_agent=_normalize_default(claude_agent),- selected_claude_model=_normalize_default(claude_model),- selected_claude_reasoning=_normalize_default(claude_reasoning),- selected_codex_agent=_normalize_default(codex_agent),- selected_codex_model=_normalize_default(codex_model),- selected_codex_reasoning=_normalize_default(codex_reasoning),+ Route blocks are ``route_<field>:<backend>[:...]`` (see ``SlackBot._route_section_blocks``). The draft is+ ``None`` when the section on screen is not the selected backend's, as right after a backend switch.+ """+ values = view.get("state", {}).get("values", {})+ selected_backend = _selected_value(values.get("backend_block")) or ""+ fields: dict[str, Optional[str]] = {}+ section_backend = None+ for block_id, block in values.items():+ if not isinstance(block_id, str) or not block_id.startswith("route_"):+ continue+ field, _, rest = block_id.partition(":")+ section_backend = rest.split(":", 1)[0]+ fields[field] = _choice(_selected_value(block))++ block_id = str(action.get("block_id") or "")+ value = (action.get("selected_option") or {}).get("value") if isinstance(action, dict) else None+ if action.get("action_id") == "backend_select" and isinstance(value, str):+ selected_backend = value+ if not selected_backend or section_backend != selected_backend:+ return RoutingModalSelection(selected_backend=selected_backend)++ draft = RouteDraft(+ variant=fields.get("route_variant"),+ model=fields.get("route_model"),+ reasoning_effort=fields.get("route_effort"),)+ if block_id.startswith("route_model:") and isinstance(value, str):+ # The state already holds the new model, so the model shown before the change is the one the view was+ # rendered with; only a different model clears the effort.+ shown = next(+ (+ (block.get("element") or {}).get("initial_option", {}).get("value")+ for block in view.get("blocks", [])+ if str(block.get("block_id") or "").startswith("route_model:")+ ),+ None,+ )+ draft = replace(draft, model=_choice(shown)).with_model(_choice(value))+ return RoutingModalSelection(selected_backend=selected_backend, draft=draft)diff --git a/modules/im/telegram.py b/modules/im/telegram.pyindex a39ecacf6..c7d2a1d6d 100644--- a/modules/im/telegram.py+++ b/modules/im/telegram.py@@ -6,7 +6,7 @@ import loggingimport reimport tempfileimport threading-from dataclasses import dataclass+from dataclasses import dataclass, field, replacefrom datetime import datetimefrom pathlib import Pathfrom typing import Any, Callable, Dict, Optional@@ -18,7 +18,7 @@ from core.message_context import resolve_context_scope_settings_key, resolve_confrom vibe.i18n import get_supported_languages, t as i18n_tfrom vibe.proxy import resolve_proxyfrom modules.agents.native_sessions import AgentNativeSessionService, NativeResumeSession-from modules.agents.opencode.utils import format_claude_model_label+from core.modals import RouteDraft, RoutingModalData, route_option_labelfrom .base import (BaseIMClient,@@ -70,26 +70,22 @@ class _TelegramRoutingState:thread_id: Optional[str]user_id: stris_dm: bool- registered_backends: list[str]- opencode_agents: list[Any]- opencode_models: dict[str, Any]- opencode_default_config: dict[str, Any]- claude_agents: list[Any]- claude_models: list[Any]- codex_models: list[Any]- backend_reasoning_options: dict[str, dict[str, list[dict[str, str]]]]+ routing: RoutingModalDatabackend: str- opencode_agent: Optional[str] = None- opencode_model: Optional[str] = None- opencode_reasoning_effort: Optional[str] = None- claude_agent: Optional[str] = None- claude_model: Optional[str] = None- claude_reasoning_effort: Optional[str] = None- codex_model: Optional[str] = None- codex_reasoning_effort: Optional[str] = None+ # Each backend keeps its own choices while the form is open; one not yet shown starts from the stored route.+ drafts: dict[str, RouteDraft] = field(default_factory=dict)picker_field: Optional[str] = Nonepicker_page: int = 0+ @property+ def registered_backends(self) -> list[str]:+ return self.routing.registered_backends++ def draft(self) -> RouteDraft:+ if self.backend not in self.drafts:+ self.drafts[self.backend] = self.routing.stored_draft(self.backend)+ return self.drafts[self.backend]+@dataclassclass _TelegramQuestionState:@@ -121,6 +117,7 @@ class TelegramBot(BaseIMClient):"""Telegram adapter using Bot API long polling."""_MAX_IN_FLIGHT_UPDATE_TASKS = 100+ # The routing picker pages its options, so a route menu offers its whole list here (no ``route_option_limit``)._MAX_IN_FLIGHT_MESSAGE_CALLBACK_TASKS = 100_COMMAND_MENU = (("start", "telegram.commandMenu.start"),@@ -1712,63 +1709,24 @@ class TelegramBot(BaseIMClient):platform="telegram",)- async def open_routing_modal(self, trigger_id: Any, channel_id: str, **kwargs):+ async def open_routing_modal(self, trigger_id: Any, channel_id: str, routing: RoutingModalData):context = trigger_id if isinstance(trigger_id, MessageContext) else Noneif context is None:raise ValueError("Telegram routing flow requires a message context")- current_routing = kwargs.get("current_routing")- current_backend = kwargs.get("current_backend") or "opencode"- backend = current_backend or "opencode"- current_model = getattr(current_routing, "model", None)- current_effort = getattr(current_routing, "reasoning_effort", None)+ registered = routing.registered_backendsstate = _TelegramRoutingState(message_id="",channel_id=channel_id,thread_id=resolve_context_thread_id(context),user_id=context.user_id,is_dm=bool((context.platform_specific or {}).get("is_dm")),- registered_backends=list(kwargs.get("registered_backends") or []),- opencode_agents=list(kwargs.get("opencode_agents") or []),- opencode_models=dict(kwargs.get("opencode_models") or {}),- opencode_default_config=dict(kwargs.get("opencode_default_config") or {}),- claude_agents=list(kwargs.get("claude_agents") or []),- claude_models=list(kwargs.get("claude_models") or []),- codex_models=list(kwargs.get("codex_models") or []),- backend_reasoning_options=dict(kwargs.get("backend_reasoning_options") or {}),- backend=backend,- opencode_agent=getattr(current_routing, "opencode_agent", None),- opencode_model=current_model if backend == "opencode" else None,- opencode_reasoning_effort=current_effort if backend == "opencode" else None,- claude_agent=getattr(current_routing, "claude_agent", None),- claude_model=current_model if backend == "claude" else None,- claude_reasoning_effort=current_effort if backend == "claude" else None,- codex_model=current_model if backend == "codex" else None,- codex_reasoning_effort=current_effort if backend == "codex" else None,+ routing=routing,+ backend=(+ routing.current_backend+ if routing.current_backend in registered+ else (registered[0] if registered else routing.current_backend)+ ),)- if backend in {"claude", "codex"}:- from modules.agents.opencode.utils import (- build_claude_reasoning_options,- build_codex_reasoning_options,- resolve_model_reasoning_options,- )-- target_model = state.claude_model if backend == "claude" else state.codex_model- fallback = (- build_claude_reasoning_options(target_model)- if backend == "claude"- else build_codex_reasoning_options()- )- available_efforts = {- entry.get("value")- for entry in resolve_model_reasoning_options(- state.backend_reasoning_options.get(backend),- target_model,- fallback,- )- }- effort_field = f"{backend}_reasoning_effort"- if getattr(state, effort_field) not in available_efforts:- setattr(state, effort_field, None)text, keyboard = self._render_routing_state(state)message_id = await self.send_message_with_buttons(context, text, keyboard)state.message_id = message_id@@ -1802,29 +1760,6 @@ class TelegramBot(BaseIMClient):def _get_backend_label(self, backend: str) -> str:return display_name_for_backend(backend)- def _option_label(self, value: Optional[str], default_label: Optional[str] = None) -> str:- if not value:- return self._t("common.default")- if value in {"none", "minimal", "low", "medium", "high", "xhigh", "max"}:- translated = self._t(f"reasoning.{value}")- if translated != f"reasoning.{value}":- return translated- return default_label or value-- def _routing_field_label(self, field: Optional[str]) -> str:- mapping = {- "backend": self._t("routing.label.backend"),- "opencode_agent": self._t("routing.label.agent"),- "opencode_model": self._t("routing.label.model"),- "opencode_reasoning_effort": self._t("routing.label.reasoningEffort"),- "claude_agent": self._t("routing.label.agent"),- "claude_model": self._t("routing.label.model"),- "claude_reasoning_effort": self._t("routing.label.reasoningEffort"),- "codex_model": self._t("routing.label.model"),- "codex_reasoning_effort": self._t("routing.label.reasoningEffort"),- }- return mapping.get(field or "", field or "")-def _question_definition(self, question: Any) -> tuple[str, str, list[tuple[str, str]], bool]:if isinstance(question, dict):header = str(question.get("header") or "").strip()@@ -1955,146 +1890,71 @@ class TelegramBot(BaseIMClient):synthetic_payload = f"{state.callback_prefix}:modal:{json.dumps(answers_payload, ensure_ascii=True)}"await self.on_callback_query_callback(context, synthetic_payload)+ def _routing_field_label(self, field: Optional[str]) -> str:+ mapping = {+ "backend": self._t("routing.label.backend"),+ "variant": self._t("routing.label.agent"),+ "model": self._t("routing.label.model"),+ "reasoning_effort": self._t("routing.label.reasoningEffort"),+ }+ return mapping.get(field or "", field or "")++ def _routing_fields(self, state: _TelegramRoutingState) -> list[tuple[str, str]]:+ """The shown backend's fields as ``(field, current value's text)``; the agent only where it has one."""+ draft = state.draft()+ menu = state.routing.menu(state.backend)+ fields = [("model", draft.model), ("reasoning_effort", draft.reasoning_effort)]+ if menu.variant_options(draft.variant):+ fields.insert(0, ("variant", draft.variant))+ shown = []+ for name, value in fields:+ target = menu.shown_value(value) if value else None+ options = self._routing_picker_options(state, name)+ text = next((text for text, option in options if option == target), value or "")+ # Catalog labels and stored ids are unbounded, and a Telegram message holds 4096 characters.+ shown.append((name, text if len(text) <= 100 else f"{text[:99]}…"))+ return shown+def _routing_summary_lines(self, state: _TelegramRoutingState) -> list[str]:lines = [f"🤖 {self._t('telegram.routingTitle')}","",f"{self._t('routing.label.backend')}: {self._get_backend_label(state.backend)}",]- if state.backend == "opencode":- lines.append(- f"{self._t('routing.label.agent')}: {self._option_label(state.opencode_agent)}"- )- lines.append(- f"{self._t('routing.label.model')}: {self._option_label(state.opencode_model)}"- )- lines.append(- f"{self._t('routing.label.reasoningEffort')}: {self._option_label(state.opencode_reasoning_effort)}"- )- elif state.backend == "claude":- lines.append(- f"{self._t('routing.label.agent')}: {self._option_label(state.claude_agent)}"- )- lines.append(- f"{self._t('routing.label.model')}: {self._option_label(state.claude_model)}"- )- lines.append(- f"{self._t('routing.label.reasoningEffort')}: {self._option_label(state.claude_reasoning_effort)}"- )- elif state.backend == "codex":- lines.append(- f"{self._t('routing.label.model')}: {self._option_label(state.codex_model)}"- )- lines.append(- f"{self._t('routing.label.reasoningEffort')}: {self._option_label(state.codex_reasoning_effort)}"- )+ lines.extend(f"{self._routing_field_label(name)}: {text}" for name, text in self._routing_fields(state))return lines- def _routing_picker_options(self, state: _TelegramRoutingState) -> list[tuple[str, Optional[str]]]:- from modules.agents.opencode.utils import (- build_claude_reasoning_options,- build_codex_reasoning_options,- build_opencode_model_option_items,- build_reasoning_effort_options,- resolve_model_reasoning_options,- resolve_opencode_allowed_providers,- resolve_opencode_provider_preferences,- )-- field = state.picker_field- if field == "backend":+ def _routing_picker_options(+ self, state: _TelegramRoutingState, field_name: Optional[str] = None+ ) -> list[tuple[str, Optional[str]]]:+ field_name = field_name or state.picker_field+ if field_name == "backend":return [(self._get_backend_label(backend), backend) for backend in state.registered_backends]- if field == "opencode_agent":- names = []- for item in state.opencode_agents:- if isinstance(item, dict):- name = str(item.get("name") or "").strip()- else:- name = str(item).strip()- if name and name not in names:- names.append(name)- return [(self._t("common.default"), None)] + [(name, name) for name in names]- if field == "opencode_model":- target_model = state.opencode_model- preferred = resolve_opencode_provider_preferences(state.opencode_default_config, target_model)- allowed = resolve_opencode_allowed_providers(state.opencode_default_config, state.opencode_models)- entries = build_opencode_model_option_items(- state.opencode_models,- max_total=24,- preferred_providers=preferred,- allowed_providers=allowed,- )- options = [(self._t("common.default"), None)]- options.extend((str(entry.get("label")), str(entry.get("value"))) for entry in entries if entry.get("value"))- return options- if field == "opencode_reasoning_effort":- target_model = state.opencode_model- return [- (- self._option_label(None if entry.get("value") == "__default__" else str(entry.get("value"))),- None if entry.get("value") == "__default__" else str(entry.get("value")),- )- for entry in build_reasoning_effort_options(state.opencode_models, target_model)- if entry.get("value")- ]- if field == "claude_agent":- names = []- for item in state.claude_agents:- if isinstance(item, dict):- name = str(item.get("name") or "").strip()- else:- name = str(item).strip()- if name and name not in names:- names.append(name)- return [(self._t("common.default"), None)] + [(name, name) for name in names]- if field == "claude_model":- return [(self._t("common.default"), None)] + [- (format_claude_model_label(model), str(model)) for model in state.claude_models- ]- if field == "claude_reasoning_effort":- return [- (- self._option_label(None if entry.get("value") == "__default__" else str(entry.get("value"))),- None if entry.get("value") == "__default__" else str(entry.get("value")),- )- for entry in resolve_model_reasoning_options(- state.backend_reasoning_options.get("claude"),- state.claude_model,- build_claude_reasoning_options(state.claude_model),- )- if entry.get("value")- ]- if field == "codex_model":- return [(self._t("common.default"), None)] + [(str(model), str(model)) for model in state.codex_models]- if field == "codex_reasoning_effort":- return [- (- self._option_label(- None if entry.get("value") == "__default__" else str(entry.get("value")),- str(entry.get("label") or entry.get("value") or ""),- ),- None if entry.get("value") == "__default__" else str(entry.get("value")),- )- for entry in resolve_model_reasoning_options(- state.backend_reasoning_options.get("codex"),- state.codex_model,- build_codex_reasoning_options(),- )- if entry.get("value")- ]- return []+ menu = state.routing.menu(state.backend)+ draft = state.draft()+ if field_name == "variant":+ options = menu.variant_options(draft.variant)+ elif field_name == "model":+ options = menu.model_options(draft.model)+ elif field_name == "reasoning_effort":+ options = menu.effort_options(draft.model, draft.reasoning_effort)+ else:+ return []+ effort = field_name == "reasoning_effort"+ return [(self._t("common.default"), None)] + [+ (route_option_label(self._t, option, effort=effort), option.value) for option in options+ ]def _apply_routing_option(self, state: _TelegramRoutingState, value: Optional[str]) -> None:- field = state.picker_field- if not field:- return- setattr(state, field, value)- if field == "claude_model" and value is None:- state.claude_reasoning_effort = None- if field == "claude_model" and value is not None:- state.claude_reasoning_effort = None- if field == "codex_model":- state.codex_reasoning_effort = None+ draft = state.draft()+ if state.picker_field in ("variant", "model", "reasoning_effort"):+ value = state.routing.menu(state.backend).chosen(state.picker_field, value)+ if state.picker_field == "model":+ state.drafts[state.backend] = draft.with_model(value)+ elif state.picker_field == "variant":+ state.drafts[state.backend] = replace(draft, variant=value)+ elif state.picker_field == "reasoning_effort":+ state.drafts[state.backend] = replace(draft, reasoning_effort=value)state.picker_field = Nonestate.picker_page = 0@@ -2124,81 +1984,15 @@ class TelegramBot(BaseIMClient):)])-- if state.backend == "opencode":- rows.append(- [- InlineButton(- text=f"{self._t('routing.label.agent')}: {self._option_label(state.opencode_agent)}"[:40],- callback_data="tg_route:field:opencode_agent",- )- ]- )- rows.append(- [- InlineButton(- text=f"{self._t('routing.label.model')}: {self._option_label(state.opencode_model)}"[:40],- callback_data="tg_route:field:opencode_model",- )- ]- )- rows.append(- [- InlineButton(- text=f"{self._t('routing.label.reasoningEffort')}: {self._option_label(state.opencode_reasoning_effort)}"[- :40- ],- callback_data="tg_route:field:opencode_reasoning_effort",- )- ]- )- elif state.backend == "claude":- rows.append(- [- InlineButton(- text=f"{self._t('routing.label.agent')}: {self._option_label(state.claude_agent)}"[:40],- callback_data="tg_route:field:claude_agent",- )- ]- )- rows.append(- [- InlineButton(- text=f"{self._t('routing.label.model')}: {self._option_label(state.claude_model)}"[:40],- callback_data="tg_route:field:claude_model",- )- ]- )- rows.append(- [- InlineButton(- text=f"{self._t('routing.label.reasoningEffort')}: {self._option_label(state.claude_reasoning_effort)}"[- :40- ],- callback_data="tg_route:field:claude_reasoning_effort",- )- ]- )- elif state.backend == "codex":- rows.append(- [- InlineButton(- text=f"{self._t('routing.label.model')}: {self._option_label(state.codex_model)}"[:40],- callback_data="tg_route:field:codex_model",- )- ]- )- rows.append(- [- InlineButton(- text=f"{self._t('routing.label.reasoningEffort')}: {self._option_label(state.codex_reasoning_effort)}"[- :40- ],- callback_data="tg_route:field:codex_reasoning_effort",- )- ]- )-+ rows.extend(+ [+ InlineButton(+ text=f"{self._routing_field_label(name)}: {value_text}"[:40],+ callback_data=f"tg_route:field:{name}",+ )+ ]+ for name, value_text in self._routing_fields(state)+ )rows.append([InlineButton(text=f"💾 {self._t('common.save')}", callback_data="tg_route:save"),@@ -2254,18 +2048,14 @@ class TelegramBot(BaseIMClient):await self.send_message(context, f"❌ {self._t('error.routingModalFailed')}")returnawait self._delete_interaction_message(context, state.message_id)+ draft = state.draft()routing_update = {"user_id": state.user_id,"channel_id": state.channel_id,"backend": state.backend,- "opencode_agent": state.opencode_agent,- "opencode_model": state.opencode_model,- "opencode_reasoning_effort": state.opencode_reasoning_effort,- "claude_agent": state.claude_agent,- "claude_model": state.claude_model,- "claude_reasoning_effort": state.claude_reasoning_effort,- "codex_model": state.codex_model,- "codex_reasoning_effort": state.codex_reasoning_effort,+ "variant": draft.variant,+ "model": draft.model,+ "reasoning_effort": draft.reasoning_effort,"is_dm": state.is_dm,"platform": "telegram",}diff --git a/tests/test_auth_pipeline.py b/tests/test_auth_pipeline.pyindex c41378cc5..98bd2041b 100644--- a/tests/test_auth_pipeline.py+++ b/tests/test_auth_pipeline.py@@ -2,6 +2,8 @@ from types import SimpleNamespaceimport sysfrom pathlib import Path+import pytest+ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT))@@ -232,7 +234,8 @@ def test_require_bind_null_allows_any_member_regardless_of_platform_default():assert result.allowed is True-def test_admin_guard_denies_non_admin_for_auth_setup_callback():[email protected]("action", ["auth_setup:codex", "routing_submit:claude"])+def test_admin_guard_denies_non_admin_for_a_protected_action_with_a_suffix(action):store = _Store()store.settings.channels["C1"] = SimpleNamespace(enabled=True)store._bound_users.add("U5")@@ -242,7 +245,7 @@ def test_admin_guard_denies_non_admin_for_auth_setup_callback():user_id="U5",channel_id="C1",is_dm=False,- action="auth_setup:codex",+ action=action,store=store,)diff --git a/tests/test_backend_registration_contract.py b/tests/test_backend_registration_contract.pyindex d0be908eb..49538edf1 100644--- a/tests/test_backend_registration_contract.py+++ b/tests/test_backend_registration_contract.py@@ -42,6 +42,7 @@ PYTHON_DECLARATIONS = {("core/backend_restart.py", "Dict", frozenset({"claude", "codex"})): (1, "native_subset", "Vendor-to-native-custody mapping."),("core/handlers/command_handlers.py", "Dict", NATIVE): (1, "native", "Native resume command aliases."),("core/handlers/message_handler.py", "Set", frozenset({"claude", "codex"})): (3, "native_subset", "Native subagent names and prompt injection."),+ ("core/handlers/settings_handler.py", "Dict", AGENTS): (1, "agent", "IM route menu loaders: where each backend's agents, models and efforts come from; the routing form itself is backend-neutral."),("core/handlers/model_hub/migration.py", "Dict", frozenset({"claude", "codex"})): (2, "native_subset", "Vendor credential and native environment maps."),("core/handlers/model_hub/migration.py", "Dict", NATIVE): (1, "native", "Native migration vendor descriptors."),("core/handlers/model_hub/migration.py", "Set", frozenset({"claude", "codex"})): (1, "native_subset", "First-party subscription import."),@@ -55,7 +56,6 @@ PYTHON_DECLARATIONS = {("core/services/skills.py", "Dict", NATIVE): (1, "native", "askill native CLI ids."),("core/session_turns.py", "Set", frozenset({"claude", "codex", "vibey"})): (1, "agent_subset", "Runtimes whose accepted turns cannot survive a service restart (process-bound, including Avibe's in-process loop)."),("core/vibe_agents.py", "Dict", NATIVE): (1, "native", "Native recommendations; Avibe uses its configured Hub catalog."),- ("modules/im/telegram.py", "Set", frozenset({"claude", "codex"})): (1, "native_subset", "Native subagent routing controls."),("scripts/incus_tenant.py", "Dict", NATIVE): (1, "native", "Bootstrap config with backend-specific fields."),("scripts/prepare_regression.py", "Dict", NATIVE): (2, "native", "Regression config with backend-specific fields; known legacy CLI executable paths."),("vibe/api.py", "Dict", NATIVE): (1, "native", "Public runtime config plus the avault tool; the built-in backend has no section."),diff --git a/tests/test_discord_model_picker.py b/tests/test_discord_model_picker.pydeleted file mode 100644index 5752bf914..000000000--- a/tests/test_discord_model_picker.py+++ /dev/null@@ -1,105 +0,0 @@-from __future__ import annotations--import asyncio-import sys-from pathlib import Path-from types import SimpleNamespace-from unittest.mock import AsyncMock, patch--sys.path.insert(0, str(Path(__file__).resolve().parents[1]))--from config.v2_config import DiscordConfig-from modules.im.discord import DiscordBot, _prioritize_claude_model_choices---def test_prioritize_pulls_aliases_ahead_of_catalog_tail():- # claude_models() appends the bare aliases after the full catalog.- models = ["claude-fable-5", "claude-opus-4-8", "opus", "sonnet", "haiku"]- result = _prioritize_claude_model_choices(models, None)-- assert result[:3] == ["opus", "sonnet", "haiku"]- # No entries gained or lost — only reordered.- assert sorted(result) == sorted(models)---def test_prioritize_puts_current_selection_first():- models = ["claude-fable-5", "claude-opus-4-8", "opus", "sonnet", "haiku"]- result = _prioritize_claude_model_choices(models, "claude-opus-4-8")-- assert result[0] == "claude-opus-4-8"- assert result[1:4] == ["opus", "sonnet", "haiku"]- assert sorted(result) == sorted(models)---def test_prioritize_ignores_missing_or_default_selection():- models = ["claude-fable-5", "opus"]-- # __default__ / None / unknown ids are not real catalog entries and must not- # be injected into the option list.- assert _prioritize_claude_model_choices(models, "__default__") == ["opus", "claude-fable-5"]- assert _prioritize_claude_model_choices(models, None) == ["opus", "claude-fable-5"]---def test_prioritized_aliases_survive_discord_25_cap():- # Regression for the P2: 24 catalog ids plus the 3 bare aliases appended last.- # The Claude modal prepends one default option then slices model_options to 25,- # so only the first 24 model entries survive. Prioritization must keep the- # always-valid aliases inside that window.- catalog = [f"claude-catalog-{i}" for i in range(24)]- models = catalog + ["opus", "sonnet", "haiku"]-- result = _prioritize_claude_model_choices(models, None)-- assert {"opus", "sonnet", "haiku"} <= set(result[:24])---def test_codex_routing_uses_shared_catalog_reasoning_options():- bot = DiscordBot(DiscordConfig(bot_token="test-token"))- channel = SimpleNamespace(send=AsyncMock())- current_routing = SimpleNamespace(- model="gpt-5.6-terra",- reasoning_effort=None,- opencode_agent=None,- opencode_model=None,- opencode_reasoning_effort=None,- claude_agent=None,- claude_model=None,- claude_reasoning_effort=None,- codex_agent=None,- codex_model=None,- codex_reasoning_effort=None,- )-- with patch.object(bot, "_fetch_channel", new=AsyncMock(return_value=channel)):- asyncio.run(- bot.open_routing_modal(- trigger_id=None,- channel_id="C123",- registered_backends=["codex"],- current_backend="codex",- current_routing=current_routing,- opencode_agents=[],- opencode_models={},- opencode_default_config={},- claude_agents=[],- claude_models=[],- codex_agents=[],- codex_models=["gpt-5.6-terra"],- backend_reasoning_options={- "codex": {- "gpt-5.6-terra": [- {"value": "__default__", "label": "(Default)"},- {"value": "ultra", "label": "Ultra"},- ]- }- },- )- )-- view = channel.send.await_args.kwargs["view"]- option_sets = [- [option.value for option in child.options]- for child in view.children- if getattr(child, "options", None)- ]- assert ["__default__", "ultra"] in option_setsdiff --git a/tests/test_feishu_routing_card.py b/tests/test_feishu_routing_card.pyindex b0e017b2a..b42f73063 100644--- a/tests/test_feishu_routing_card.py+++ b/tests/test_feishu_routing_card.py@@ -3,6 +3,8 @@ from types import SimpleNamespacefrom unittest.mock import AsyncMockfrom config.v2_config import LarkConfig+from config.v2_settings import RoutingSettings+from core.modals import BackendRouteMenu, RouteOption, RoutingModalDatafrom core.auth import AuthResultfrom modules.im.base import MessageContextfrom modules.im.feishu import FeishuBot@@ -20,216 +22,93 @@ class FeishuRoutingCardTests(unittest.IsolatedAsyncioTestCase):return elementraise AssertionError(f"select_static {field_name} not found")- async def test_codex_reasoning_uses_shared_catalog_options(self):- bot = self._make_bot()- current_routing = SimpleNamespace(- codex_agent=None,- codex_model="gpt-5.6-terra",- codex_reasoning_effort=None,- )- card = bot._build_routing_backend_options_card(- "chat",- "codex",- current_routing=current_routing,- draft_routing=bot._routing_draft_from_current(current_routing, "codex"),- codex_agents=[],- codex_models=["gpt-5.6-terra"],- backend_reasoning_options={- "codex": {- "gpt-5.6-terra": [- {"value": "__default__", "label": "(Default)"},- {"value": "ultra", "label": "Ultra"},- ]- }+ @staticmethod+ def _claude_routing() -> RoutingModalData:+ efforts = [RouteOption("high", "High"), RouteOption("max", "Max")]+ return RoutingModalData(+ registered_backends=["claude", "codex"],+ current_backend="claude",+ current_routing=RoutingSettings(agent_name="claude", model="claude-sonnet-4-5", claude_agent="helper"),+ menus={+ "claude": BackendRouteMenu(+ "claude",+ models=[RouteOption(m, m) for m in ("claude-sonnet-4-5", "claude-sonnet-4-6", "claude-opus-4-6")],+ efforts={"claude-sonnet-4-5": efforts[:1], "claude-opus-4-6": efforts},+ ),+ "codex": BackendRouteMenu("codex", models=[RouteOption("gpt-5.4", "gpt-5.4")]),},- _user_id="user",- )-- reasoning_select = self._find_select(card, "codex_reasoning")- self.assertEqual(- [option["value"] for option in reasoning_select["options"]],- ["__default__", "ultra"],- )-- async def test_claude_model_change_refreshes_reasoning_options(self):- bot = self._make_bot()- bot._patch_card_message = AsyncMock()-- current_routing = SimpleNamespace(- claude_agent="helper",- claude_model="claude-sonnet-4-5",- claude_reasoning_effort="high",- opencode_agent=None,- opencode_model=None,- opencode_reasoning_effort=None,- codex_agent=None,- codex_model=None,- codex_reasoning_effort=None,- )- bot._routing_cache["chat:user"] = {- "current_routing": current_routing,- "draft_routing": bot._routing_draft_from_current(current_routing),- "_selected_backend": "claude",- "claude_agents": ["helper", "reviewer"],- "claude_models": ["claude-sonnet-4-5", "claude-opus-4-6"],- "opencode_agents": [],- "opencode_models": {},- "opencode_default_config": {},- "codex_agents": [],- "codex_models": [],- }-- context = MessageContext(user_id="user", channel_id="chat", message_id="om_123")-- handled = await bot._handle_routing_select_change(- context,- {"tag": "select_static", "name": "claude_model", "option": {"value": "claude-opus-4-6"}},)- self.assertTrue(handled)- bot._patch_card_message.assert_awaited_once()- first_call = bot._patch_card_message.await_args- assert first_call is not None- _, card = first_call.args-- reasoning_select = self._find_select(card, "claude_reasoning")- reasoning_values = [option["value"] for option in reasoning_select["options"]]- self.assertIn("max", reasoning_values)- self.assertEqual(reasoning_select.get("initial_option"), "__default__")-- agent_select = self._find_select(card, "claude_agent")- self.assertEqual(agent_select.get("initial_option"), "helper")-- draft = bot._routing_cache["chat:user"]["draft_routing"]- self.assertEqual(draft["claude_model"], "claude-opus-4-6")- self.assertIsNone(draft["claude_reasoning_effort"])-async def test_select_changes_with_different_options_are_not_deduped(self):bot = self._make_bot()bot._patch_card_message = AsyncMock()bot.check_authorization = lambda **kwargs: AuthResult(allowed=True)+ bot._routing_cache["chat:user"] = {"routing": self._claude_routing(), "drafts": {}}- current_routing = SimpleNamespace(- claude_agent="helper",- claude_model="claude-sonnet-4-5",- claude_reasoning_effort="high",- opencode_agent=None,- opencode_model=None,- opencode_reasoning_effort=None,- codex_agent=None,- codex_model=None,- codex_reasoning_effort=None,- )- bot._routing_cache["chat:user"] = {- "current_routing": current_routing,- "draft_routing": bot._routing_draft_from_current(current_routing),- "_selected_backend": "claude",- "claude_agents": ["helper", "reviewer"],- "claude_models": ["claude-sonnet-4-5", "claude-sonnet-4-6", "claude-opus-4-6"],- "opencode_agents": [],- "opencode_models": {},- "opencode_default_config": {},- "codex_agents": [],- "codex_models": [],- }+ def _event(model):+ return {+ "operator": {"open_id": "user"},+ "context": {"open_message_id": "om_123", "open_chat_id": "chat"},+ "action": {"tag": "select_static", "name": "route_model:claude", "option": {"value": model}},+ }- first_event = {- "operator": {"open_id": "user"},- "context": {"open_message_id": "om_123", "open_chat_id": "chat"},- "action": {- "tag": "select_static",- "name": "claude_model",- "option": {"value": "claude-sonnet-4-6"},- },- }- second_event = {- "operator": {"open_id": "user"},- "context": {"open_message_id": "om_123", "open_chat_id": "chat"},- "action": {- "tag": "select_static",- "name": "claude_model",- "option": {"value": "claude-opus-4-6"},- },- }-- await bot._async_handle_card_action(first_event)- await bot._async_handle_card_action(second_event)+ await bot._async_handle_card_action(_event("claude-sonnet-4-6"))+ await bot._async_handle_card_action(_event("claude-opus-4-6"))self.assertEqual(bot._patch_card_message.await_count, 2)- draft = bot._routing_cache["chat:user"]["draft_routing"]- self.assertEqual(draft["claude_model"], "claude-opus-4-6")- latest_call = bot._patch_card_message.await_args- assert latest_call is not None- _, latest_card = latest_call.args- reasoning_select = self._find_select(latest_card, "claude_reasoning")- reasoning_values = [option["value"] for option in reasoning_select["options"]]+ self.assertEqual(bot._routing_cache["chat:user"]["drafts"]["claude"].model, "claude-opus-4-6")+ _, latest_card = bot._patch_card_message.await_args.args+ reasoning_values = [+ option["value"] for option in self._find_select(latest_card, "route_effort:claude")["options"]+ ]self.assertIn("max", reasoning_values)- async def test_routing_submit_preserves_cached_codex_agent_when_field_missing(self):+ async def test_routing_submit_keeps_the_drafts_native_agent_when_the_form_omits_it(self):bot = self._make_bot()bot._on_routing_update = AsyncMock()+ routing = RoutingModalData(+ registered_backends=["codex"],+ current_backend="codex",+ current_routing=RoutingSettings(agent_name="codex", model="gpt-5.1", codex_agent="reviewer"),+ )+ bot._routing_cache["chat:user"] = {"routing": routing, "drafts": {}}+ context = MessageContext(user_id="user", channel_id="chat", platform="lark", platform_specific={"is_dm": False})- current_routing = SimpleNamespace(- claude_agent=None,- claude_model=None,- claude_reasoning_effort=None,- opencode_agent=None,- opencode_model=None,- opencode_reasoning_effort=None,- codex_agent="reviewer",- codex_model="gpt-5.1",- codex_reasoning_effort="medium",+ await bot._handle_routing_form_submit(+ context, {"route_model:codex": "gpt-5.4", "route_effort:codex": "high"}, "routing_submit:codex")- bot._routing_cache["chat:user"] = {- "current_routing": current_routing,- "draft_routing": bot._routing_draft_from_current(current_routing),- "_selected_backend": "codex",- "claude_agents": [],- "claude_models": [],- "opencode_agents": [],- "opencode_models": {},- "opencode_default_config": {},- "codex_agents": [],- "codex_models": ["gpt-5.1", "gpt-5.4"],- }- context = MessageContext(+ bot._on_routing_update.assert_awaited_once_with(user_id="user",channel_id="chat",- platform="lark",- platform_specific={"is_dm": False},+ backend="codex",+ variant="reviewer",+ model="gpt-5.4",+ reasoning_effort="high",+ is_dm=False,)+ async def test_an_options_card_saves_its_own_backend_after_another_was_opened(self):+ bot = self._make_bot()+ bot._send_card_to_channel = AsyncMock()+ bot._on_routing_update = AsyncMock()+ context = MessageContext(user_id="user", channel_id="chat", platform="lark", platform_specific={"is_dm": False})+ await bot.open_routing_modal(trigger_id=context, channel_id="chat", routing=self._claude_routing())+ # The step-1 card stays active, so it can open a second backend's card before the first is submitted.+ await bot._handle_routing_backend_select(context, {"backend": "claude"})+ claude_card = bot._send_card_to_channel.await_args.args[1]+ await bot._handle_routing_backend_select(context, {"backend": "codex"})++ elements = claude_card["body"]["elements"][0]["elements"]+ button = next(element for element in elements if element["tag"] == "button")await bot._handle_routing_form_submit(context,- {- "backend": "codex",- "codex_model": "gpt-5.4",- "codex_reasoning": "high",- },+ {e["name"]: e["initial_option"] for e in elements if e["tag"] == "select_static"},+ button["name"],)- bot._on_routing_update.assert_awaited_once()- call = bot._on_routing_update.await_args- self.assertEqual(call.args, ())- self.assertEqual(- call.kwargs,- {- "user_id": "user",- "channel_id": "chat",- "backend": "codex",- "opencode_agent": None,- "opencode_model": None,- "opencode_reasoning_effort": None,- "claude_agent": None,- "claude_model": None,- "claude_reasoning_effort": None,- "codex_agent": "reviewer",- "codex_model": "gpt-5.4",- "codex_reasoning_effort": "high",- "is_dm": False,- },- )+ kwargs = bot._on_routing_update.await_args.kwargs+ self.assertEqual((kwargs["backend"], kwargs["model"]), ("claude", "claude-sonnet-4-5"))async def test_settings_submit_binds_optional_fields_by_name(self):bot = self._make_bot()@@ -265,30 +144,6 @@ class FeishuRoutingCardTests(unittest.IsolatedAsyncioTestCase):},)- async def test_routing_draft_populates_selected_backend_from_current_selection(self):- bot = self._make_bot()-- current_routing = SimpleNamespace(- model="claude-sonnet-4-6",- reasoning_effort="high",- claude_agent="helper",- claude_model=None,- claude_reasoning_effort=None,- opencode_agent=None,- opencode_model=None,- opencode_reasoning_effort=None,- codex_agent=None,- codex_model=None,- codex_reasoning_effort=None,- )-- draft = bot._routing_draft_from_current(current_routing, "claude")-- self.assertEqual(draft["claude_model"], "claude-sonnet-4-6")- self.assertEqual(draft["claude_reasoning_effort"], "high")- self.assertIsNone(draft["opencode_model"])- self.assertIsNone(draft["codex_model"])-async def test_quick_reply_card_action_sets_lark_platform(self):bot = self._make_bot()bot.check_authorization = lambda **kwargs: AuthResult(allowed=True)diff --git a/tests/test_im_backend_registration.py b/tests/test_im_backend_registration.pyindex ded8d2c4c..0d6faf09d 100644--- a/tests/test_im_backend_registration.py+++ b/tests/test_im_backend_registration.py@@ -10,10 +10,16 @@ from unittest.mock import AsyncMock, Mockimport pytest-from config.v2_config import DiscordConfig, LarkConfig, SlackConfig+from config.v2_config import DiscordConfig, LarkConfig, SlackConfig, TelegramConfig+from config.v2_settings import RoutingSettings+from core.modals import STORED_OPTION_VALUE, BackendRouteMenu, RouteOption, RoutingModalData+from modules.agents.catalog import display_name_for_backend+from modules.im import MessageContextfrom modules.im.discord import DiscordBotfrom modules.im.feishu import FeishuBotfrom modules.im.slack import SlackBot+from modules.im.slack_modal import parse_routing_modal_selection+from modules.im.telegram import TelegramBotdef _options(payload):@@ -32,10 +38,8 @@ def _options(payload):@pytest.mark.parametrize("platform", ["slack", "discord", "feishu"])async def test_agent_picker_includes_vibey_but_native_resume_excludes_it(platform):routing = dict(- channel_id="fixture-channel", registered_backends=["codex", "vibey"],- current_backend="vibey", current_routing=None,- opencode_agents=[], opencode_models={}, opencode_default_config={},- claude_agents=[], claude_models=[], codex_agents=[], codex_models=[],+ channel_id="fixture-channel",+ routing=RoutingModalData(registered_backends=["codex", "vibey"], current_backend="vibey", current_routing=None),)if platform == "slack":bot = SlackBot(SlackConfig(bot_token="fixture-token"))@@ -74,3 +78,216 @@ async def test_agent_picker_includes_vibey_but_native_resume_excludes_it(platforvalues = [option["value"] for option in _options(bot._send_card_to_channel.await_args.args[1])]assert "codex" in valuesassert "vibey" not in values+++PLATFORMS = ["slack", "discord", "telegram", "feishu"]+++def _efforts(*values):+ return [RouteOption(value, value.title()) for value in values]+++def _route(bot, backend, stored_model="model-b"):+ """A channel routed to ``backend``: its stored model sits past every platform's option cap, and its stored+ effort is one the menu no longer offers. Saving unchanged must keep both, on every platform."""+ long_id = "vendor/" + "x" * 160 # longer than a Slack or Discord option value may be+ menu = BackendRouteMenu(+ backend,+ variants=_efforts("builder", "reviewer") if backend == "codex" else [],+ models=[+ RouteOption("model-a", "Model A"),+ *(RouteOption(f"filler-{i}", f"Filler {i}") for i in range(120)),+ RouteOption(long_id, "Long"),+ RouteOption("model-b", "Model B"),+ ],+ efforts={"model-a": _efforts("low"), "model-b": _efforts("high")},+ # What the platform declares, which the settings handler reads into every menu it builds.+ option_limit=getattr(bot, "route_option_limit", None),+ value_limit=getattr(bot, "route_option_value_limit", None),+ )+ stored = RoutingSettings(+ agent_name=backend, model=stored_model, reasoning_effort="max",+ codex_agent="reviewer" if backend == "codex" else None,+ )+ data = RoutingModalData(+ registered_backends=[backend, "opencode"], current_backend=backend, current_routing=stored,+ menus={backend: menu},+ )+ menu.stored = data.stored_draft(backend) # as the settings handler sets it+ return data, long_id+++class _Form:+ """Drive one platform's routing form through its own entry points: open, change the model, save."""++ def __init__(self, platform, backend, stored_model="model-b"):+ self.platform = platform+ self.backend = backend+ self.context = MessageContext(user_id="42", channel_id="fixture-channel", message_id="88",+ platform=platform, platform_specific={"is_dm": False})+ self.saved = AsyncMock()+ if platform == "slack":+ self.bot = SlackBot(SlackConfig(bot_token="fixture-token"))+ elif platform == "discord":+ self.bot = DiscordBot(DiscordConfig(bot_token="fixture-token"))+ elif platform == "telegram":+ self.bot = TelegramBot(TelegramConfig(bot_token="123456:fixture-token"))+ else:+ self.bot = FeishuBot(LarkConfig(app_id="fixture-app", app_secret="fixture-secret"))+ self.data, self.long_id = _route(self.bot, backend, stored_model)++ async def open(self):+ bot, context = self.bot, self.context+ if self.platform == "slack":+ self.view = bot._build_routing_modal_view(channel_id=context.channel_id, routing=self.data)+ elif self.platform == "discord":+ channel = SimpleNamespace(send=AsyncMock())+ bot._fetch_channel = AsyncMock(return_value=channel)+ await bot.open_routing_modal(trigger_id=None, channel_id=context.channel_id, routing=self.data)+ self.view = channel.send.await_args.kwargs["view"]+ elif self.platform == "telegram":+ bot.send_message_with_buttons = AsyncMock(return_value="88")+ bot.edit_message = AsyncMock(return_value=True)+ await bot.open_routing_modal(context, context.channel_id, routing=self.data)+ keyboard = bot.send_message_with_buttons.await_args.args[2]+ fields = {button.callback_data for row in keyboard.buttons for button in row}+ assert {"tg_route:field:model", "tg_route:field:reasoning_effort"} <= fields+ else:+ bot._send_card_to_channel = AsyncMock()+ await bot.open_routing_modal(trigger_id=context, channel_id=context.channel_id, routing=self.data)+ await bot._handle_routing_backend_select(context, {"backend": self.backend})+ self.card = bot._send_card_to_channel.await_args.args[1]++ def offered(self, field):+ """The option values the form offers for ``field`` (variant, model or effort) right now."""+ if self.platform == "slack":+ block = next(b for b in self.view["blocks"] if str(b.get("block_id", "")).startswith(f"route_{field}:"))+ return [option["value"] for option in block["element"]["options"]]+ if self.platform == "discord":+ key = {"variant": "selectBackendAgent", "model": "selectModel", "effort": "selectReasoningEffort"}[field]+ placeholder = self.bot._t(f"modal.routing.{key}", backend=display_name_for_backend(self.backend))+ select = next(c for c in self.view.children if getattr(c, "placeholder", None) == placeholder)+ return [option.value for option in select.options]+ if self.platform == "telegram":+ state = self.bot._routing_states[self.bot._interaction_scope_key(self.context)]+ name = {"effort": "reasoning_effort"}.get(field, field)+ return [value or "__default__" for _, value in self.bot._routing_picker_options(state, name)]+ name = f"route_{field}:{self.backend}"+ select = next(e for e in self.card["body"]["elements"][0]["elements"] if e.get("name") == name)+ return [option["value"] for option in select["options"]]++ async def change_model(self, model):+ bot, context = self.bot, self.context+ if self.platform == "slack":+ # A block_actions payload's state already holds the newly selected model.+ self.view["state"] = _shown_state(self.view)+ model_block = next(key for key in self.view["state"]["values"] if key.startswith("route_model:"))+ self.view["state"]["values"][model_block]["route_model"] = {"selected_option": {"value": model}}+ selection = parse_routing_modal_selection(view=self.view, action={+ "action_id": "route_model", "block_id": f"route_model:{self.backend}",+ "selected_option": {"value": model},+ })+ self.view = bot._build_routing_modal_view(+ channel_id=context.channel_id, routing=self.data,+ selected_backend=selection.selected_backend, draft=selection.draft,+ )+ elif self.platform == "discord":+ prefix = bot._t("modal.routing.selectModel")+ select = next(c for c in self.view.children if getattr(c, "placeholder", None) == prefix)+ select._values = [model]+ await select.callback(SimpleNamespace(response=SimpleNamespace(edit_message=AsyncMock())))+ elif self.platform == "telegram":+ await bot._handle_routing_callback(context, "tg_route:field:model")+ state = bot._routing_states[bot._interaction_scope_key(context)]+ index = [value for _, value in bot._routing_picker_options(state)].index(model)+ await bot._handle_routing_callback(context, f"tg_route:option:{index}")+ else:+ bot._patch_card_message = AsyncMock()+ assert await bot._handle_routing_select_change(+ context, {"name": f"route_model:{self.backend}", "option": model}+ )+ self.card = bot._patch_card_message.await_args.args[1]++ async def save(self):+ bot, context = self.bot, self.context+ if self.platform == "slack":+ self.view["state"] = _shown_state(self.view)+ bot._on_routing_update = self.saved+ await bot._handle_view_submission({"view": self.view, "user": {"id": context.user_id}})+ elif self.platform == "discord":+ bot.check_authorization = Mock(return_value=SimpleNamespace(allowed=True))+ bot._dismiss_interaction_message = AsyncMock()+ bot._on_routing_update = self.saved+ await self.view._on_save(SimpleNamespace(+ response=SimpleNamespace(defer=AsyncMock()), user=SimpleNamespace(id=42), channel_id=None, guild=None,+ ))+ elif self.platform == "telegram":+ bot._delete_interaction_message = AsyncMock()+ bot._controller = SimpleNamespace(settings_handler=SimpleNamespace(handle_routing_update=self.saved))+ await bot._handle_routing_callback(context, "tg_route:save")+ else:+ # A Feishu form submits what each of its selects shows, through its own submit button.+ elements = self.card["body"]["elements"][0]["elements"]+ selects = [e for e in elements if e["tag"] == "select_static"]+ button = next(e for e in elements if e["tag"] == "button")+ bot._on_routing_update = self.saved+ await bot._handle_routing_form_submit(+ context, {e["name"]: e["initial_option"] for e in selects}, button["name"],+ )+ self.saved.assert_awaited_once()+ kwargs = self.saved.await_args.kwargs+ return kwargs["backend"], kwargs["variant"], kwargs["model"], kwargs["reasoning_effort"]+++def _shown_state(view):+ """A Slack view's state as submitted unchanged: each input holds what it shows."""+ return {"values": {+ block["block_id"]: {block["element"]["action_id"]: {"selected_option": block["element"]["initial_option"]}}+ for block in view["blocks"] if block["type"] == "input"+ }}++[email protected]("platform", PLATFORMS)[email protected]("backend", ["vibey", "codex"])+async def test_a_route_offers_its_backends_menu_and_saving_unchanged_keeps_it(platform, backend):+ form = _Form(platform, backend)+ await form.open()++ models, efforts = form.offered("model"), form.offered("effort")+ assert {"model-a", "model-b"} <= set(models)+ if platform == "telegram":+ assert {f"filler-{i}" for i in range(120)} <= set(models) # its picker pages, so nothing is cut+ assert efforts == ["__default__", "high", "max"] # model-b's, plus the stored effort the menu omits+ if platform in {"slack", "discord"}:+ assert form.long_id not in models # one such id must not make the whole form invalid+ if backend == "codex":+ assert form.offered("variant") == ["__default__", "builder", "reviewer"]+ stored_variant = "reviewer" if backend == "codex" else None+ assert await form.save() == (backend, stored_variant, "model-b", "max")++[email protected]("platform", PLATFORMS)+async def test_a_model_change_offers_that_models_efforts_and_clears_the_effort(platform):+ form = _Form(platform, "vibey")+ await form.open()++ await form.change_model("model-a")++ assert form.offered("effort") == ["__default__", "low"]+ assert await form.save() == ("vibey", None, "model-a", None)++[email protected]("platform", PLATFORMS)+async def test_reselecting_a_stored_model_the_platform_cannot_carry_keeps_its_effort(platform):+ long_id = "vendor/" + "x" * 160+ form = _Form(platform, "vibey", stored_model=long_id)+ await form.open()++ await form.change_model(form.data.menu("vibey").shown_value(long_id))++ # Slack hands the stand-in to the settings handler, which resolves it to the stored model.+ saved_model = STORED_OPTION_VALUE if platform == "slack" else long_id+ assert await form.save() == ("vibey", None, saved_model, "max")diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 122e2a792..e98b89f30 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -3253,6 +3253,28 @@ def test_retired_builtins_leave_the_picker_but_stay_routeable(monkeypatch, tmp_p]+def test_read_agent_sources_reads_recovery_state_on_the_owning_loop(tmp_path):+ """Recovery annotations may wake loop-owned waiters, so a loop caller reads them on that loop."""+ service, store, _adapter = _service(tmp_path)+ store.config.agents["vibey"].models = [ModelHubBackendModelConfig(id="vibey-model", origin="user")]+ annotations = service.recovery.annotations+ threads = []++ def recorded(config):+ threads.append(threading.get_ident())+ return annotations(config)++ service.recovery.annotations = recorded++ async def read():+ return threading.get_ident(), await service.read_agent_sources("vibey")++ loop_thread, payload = asyncio.run(read())++ assert threads == [loop_thread]+ assert payload == service.get_agent_sources("vibey")++def test_compatibility_projections_hide_retired_builtins_unless_requested(tmp_path):service, store, _adapter = _service(tmp_path)store.config.agents["claude"].models = [diff --git a/tests/test_route_menu.py b/tests/test_route_menu.pynew file mode 100644index 000000000..40f97e528--- /dev/null+++ b/tests/test_route_menu.py@@ -0,0 +1,73 @@+"""The backend-neutral route menu every IM routing form renders (``core/modals.py``).++These rules used to be re-implemented per backend and per platform, and drifted: a stored choice past a+platform's option cap, missing from a changed catalog, or refused by Model Hub now was dropped by saving a form+unchanged on some surfaces and not others.+"""++from config.v2_settings import RoutingSettings+from core.modals import STORED_OPTION_VALUE, BackendRouteMenu, RouteDraft, RouteOption, RoutingModalData+++def _options(*values):+ return [RouteOption(value, value.upper()) for value in values]+++def _values(options):+ return [option.value for option in options]+++def test_a_select_keeps_the_current_choice_within_its_cap_listed_or_not():+ menu = BackendRouteMenu("any", models=_options(*(f"m{i}" for i in range(30))), option_limit=25)++ assert _values(menu.model_options(None)) == [f"m{i}" for i in range(24)] # Default takes the 25th slot+ past_cap = menu.model_options("m29")+ assert len(past_cap) == 24 and past_cap[-1] == RouteOption("m29", "M29") # keeps its catalog label+ unlisted = menu.model_options("gone-model")+ assert len(unlisted) == 24 and unlisted[-1] == RouteOption("gone-model", "gone-model")+ assert _values(menu.model_options("m3")) == [f"m{i}" for i in range(24)] # already shown: order unchanged+++def test_a_select_carries_only_values_its_platform_can_hold_and_stands_in_for_a_stored_one():+ long_id = "x" * 101+ menu = BackendRouteMenu(+ "any", models=_options("ok", long_id, "__default__"), value_limit=100, stored=RouteDraft(model=long_id)+ )++ assert _values(menu.model_options(None)) == ["ok"]+ # The stored choice stays shown through a stand-in option, named after it; saving that keeps it.+ for current in (long_id, STORED_OPTION_VALUE):+ assert menu.model_options(current) == [RouteOption("ok", "OK"), RouteOption(STORED_OPTION_VALUE, long_id.upper())]+ assert menu.shown_value(current) == STORED_OPTION_VALUE+ assert (menu.shown_value(None), menu.shown_value("ok")) == ("__default__", "ok")+++def test_efforts_follow_the_model_and_keep_a_stored_effort_the_menu_omits():+ menu = BackendRouteMenu(+ "any",+ efforts={"": _options("low", "high"), "reasoner": _options("high"), "plain": []},+ option_limit=3,+ )++ assert _values(menu.effort_options("reasoner", None)) == ["high"]+ assert _values(menu.effort_options("unknown-model", None)) == ["low", "high"] # inherits the Default model's+ assert _values(menu.effort_options("plain", None)) == [] # a model that does not reason does not inherit+ # A model change clears the effort, so an unlisted one is the stored route's (Model Hub may refuse it now).+ assert _values(menu.effort_options("reasoner", "max")) == ["high", "max"]+ assert _values(menu.effort_options(None, "max")) == ["low", "max"] # within the cap+ draft = RouteDraft(variant="v", model="a", reasoning_effort="max")+ assert draft.with_model("b") == RouteDraft("v", "b", None)+ assert draft.with_model("a") == draft # picking the shown model again keeps its effort+++def test_the_stored_route_shows_only_on_its_own_backend():+ routing = RoutingSettings(agent_name="codex", model="gpt-5.4", reasoning_effort="high", claude_agent="helper")+ data = RoutingModalData(registered_backends=["claude", "codex", "vibey"], current_backend="codex", current_routing=routing)++ assert data.stored_draft("codex") == RouteDraft(None, "gpt-5.4", "high")+ # Another backend keeps its own native agent but not the stored backend's model or effort.+ assert data.stored_draft("claude") == RouteDraft("helper", None, None)+ assert data.stored_draft("vibey") == RouteDraft()+ # A route saved by an older release with backend-specific fields reads the same.+ legacy = RoutingSettings(agent_name="codex", codex_model="gpt-5.4", codex_reasoning_effort="high")+ assert RoutingModalData(["codex"], "codex", legacy).stored_draft("codex") == RouteDraft(None, "gpt-5.4", "high")diff --git a/tests/test_routing_modal_selection.py b/tests/test_routing_modal_selection.pydeleted file mode 100644index 68fb41f5e..000000000--- a/tests/test_routing_modal_selection.py+++ /dev/null@@ -1,58 +0,0 @@-from modules.im.slack_modal import parse_routing_modal_selection---def test_parse_routing_modal_selection_uses_action_override():- view = {- "state": {- "values": {- "backend_block": {"backend_select": {"selected_option": {"value": "opencode"}}},- "opencode_model_block": {"opencode_model_select": {"selected_option": {"value": "m1"}}},- }- }- }- action = {"action_id": "opencode_model_select", "selected_option": {"value": "m2"}}-- selection = parse_routing_modal_selection(view=view, action=action, fallback_selected_backend="claude")-- assert selection.selected_backend == "opencode"- assert selection.selected_opencode_model == "m2"---def test_parse_routing_modal_selection_normalizes_default_values():- view = {- "state": {- "values": {- "codex_agent_block": {"codex_agent_select": {"selected_option": {"value": "__default__"}}},- "claude_model_block": {"claude_model_select": {"selected_option": {"value": "__default__"}}},- "claude_reasoning_block": {"claude_reasoning_select": {"selected_option": {"value": "__default__"}}},- "codex_reasoning_block": {"codex_reasoning_select_1": {"selected_option": {"value": "__default__"}}},- }- }- }-- selection = parse_routing_modal_selection(view=view, action={}, fallback_selected_backend="claude")-- assert selection.selected_backend == "claude"- assert selection.selected_codex_agent is None- assert selection.selected_claude_model is None- assert selection.selected_claude_reasoning is None- assert selection.selected_codex_reasoning is None---def test_parse_routing_modal_selection_applies_codex_action_override():- view = {- "state": {- "values": {- "backend_block": {"backend_select": {"selected_option": {"value": "codex"}}},- "codex_agent_block": {"codex_agent_select": {"selected_option": {"value": "__default__"}}},- "codex_model_block": {"codex_model_select": {"selected_option": {"value": "gpt-5.4-mini"}}},- }- }- }- action = {"action_id": "codex_agent_select", "selected_option": {"value": "reviewer"}}-- selection = parse_routing_modal_selection(view=view, action=action, fallback_selected_backend="claude")-- assert selection.selected_backend == "codex"- assert selection.selected_codex_agent == "reviewer"- assert selection.selected_codex_model == "gpt-5.4-mini"diff --git a/tests/test_settings_handler.py b/tests/test_settings_handler.pyindex 904089057..f3e0e96a1 100644--- a/tests/test_settings_handler.py+++ b/tests/test_settings_handler.py@@ -8,11 +8,15 @@ from unittest.mock import patchfrom config.v2_settings import RoutingSettingsfrom core.handlers.settings_handler import SettingsHandler-from core.modals import RoutingModalSelection+from core.modals import STORED_OPTION_VALUE, BackendRouteMenu, RouteOption, RoutingModalData, RoutingModalSelectionfrom modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDSfrom modules.im import MessageContext+def _values(options) -> list[str]:+ return [option.value for option in options]++class _StubSettingsManager:def __init__(self, routing: RoutingSettings | None):self.routing = routing@@ -154,12 +158,8 @@ def test_handle_routing_update_preserves_existing_codex_agent_when_omitted() ->user_id="42",channel_id="-100123",backend="codex",- opencode_agent=None,- opencode_model=None,- claude_agent=None,- claude_model=None,- codex_model="gpt-5.4",- codex_reasoning_effort="high",+ model="gpt-5.4",+ reasoning_effort="high",notify_user=False,platform="telegram",)@@ -190,13 +190,9 @@ def test_handle_routing_update_allows_explicit_codex_agent_clear() -> None:user_id="42",channel_id="-100123",backend="codex",- opencode_agent=None,- opencode_model=None,- claude_agent=None,- claude_model=None,- codex_agent=None,- codex_model="gpt-5.4",- codex_reasoning_effort="high",+ variant=None,+ model="gpt-5.4",+ reasoning_effort="high",notify_user=False,platform="telegram",)@@ -219,12 +215,8 @@ def test_handle_routing_update_handles_first_codex_save_without_existing_routinguser_id="42",channel_id="-100123",backend="codex",- opencode_agent=None,- opencode_model=None,- claude_agent=None,- claude_model=None,- codex_model="gpt-5.4",- codex_reasoning_effort="high",+ model="gpt-5.4",+ reasoning_effort="high",notify_user=False,platform="telegram",)@@ -253,11 +245,9 @@ def test_handle_routing_update_preserves_catalog_claude_effort() -> None:user_id="42",channel_id="-100123",backend="claude",- opencode_agent=None,- opencode_model=None,- claude_agent="reviewer",- claude_model="claude-future-6",- claude_reasoning_effort="ultra",+ variant="reviewer",+ model="claude-future-6",+ reasoning_effort="ultra",notify_user=False,platform="telegram",)@@ -269,6 +259,94 @@ def test_handle_routing_update_preserves_catalog_claude_effort() -> None:send_message.assert_not_awaited()+def test_handle_routing_update_saves_vibey_model_and_effort_on_the_vibey_route() -> None:+ settings_manager = _StubSettingsManager(RoutingSettings(agent_name="opencode", model="openai/gpt-5"))+ handler, send_message = _make_handler(settings_manager)+ handler.controller.vibe_agent_store = SimpleNamespace(routing_name_for_backend=lambda backend: f"{backend}-agent")++ asyncio.run(+ handler.handle_routing_update(+ user_id="42",+ channel_id="-100123",+ backend="vibey",+ model="claude-opus-5-5",+ reasoning_effort="xhigh",+ platform="telegram",+ )+ )++ saved = settings_manager.saved_routing+ assert (saved.agent_name, saved.model, saved.reasoning_effort) == ("vibey-agent", "claude-opus-5-5", "xhigh")+ text = send_message.await_args.args[1]+ assert "claude-opus-5-5" in text and "xhigh" in text++ # An opaque id of any length still yields a confirmation every platform can send.+ asyncio.run(+ handler.handle_routing_update(+ user_id="42", channel_id="-100123", backend="vibey", model="m" * 5000, platform="telegram",+ )+ )+ assert settings_manager.saved_routing.model == "m" * 5000+ assert len(send_message.await_args.args[1]) < 1000+++def test_saving_an_unchanged_slack_form_keeps_a_stored_model_slack_cannot_show() -> None:+ """A Web-set model id past Slack's 150-character option values must survive saving the Slack form."""+ from config.v2_config import SlackConfig+ from modules.im.slack import SlackBot++ long_id = "vendor/" + "x" * 160+ settings_manager = _StubSettingsManager(RoutingSettings(agent_name="vibey", model=long_id, reasoning_effort="high"))+ handler, _ = _make_handler(settings_manager)+ handler.controller.vibe_agent_store = SimpleNamespace(+ routing_name_for_backend=lambda backend: backend, get=lambda name: SimpleNamespace(backend="vibey")+ )+ bot = SlackBot(SlackConfig(bot_token="fixture-token"))+ bot._on_routing_update = handler.handle_routing_update+ data = RoutingModalData(["vibey"], "vibey", settings_manager.routing)+ data.menus["vibey"] = BackendRouteMenu(+ "vibey",+ models=[RouteOption("model-a", "Model A")],+ efforts={"": [RouteOption("high", "High")]},+ option_limit=bot.route_option_limit,+ value_limit=bot.route_option_value_limit,+ stored=data.stored_draft("vibey"),+ )+ view = bot._build_routing_modal_view(channel_id="-100123", routing=data)+ view["state"] = {"values": {+ block["block_id"]: {block["element"]["action_id"]: {"selected_option": block["element"]["initial_option"]}}+ for block in view["blocks"] if block["type"] == "input"+ }}++ with patch.object(handler, "_routing_update_needs_new_session_hint", return_value=False):+ asyncio.run(bot._handle_view_submission({"view": view, "user": {"id": "42"}}))++ saved = settings_manager.saved_routing+ assert (saved.agent_name, saved.model, saved.reasoning_effort) == ("vibey", long_id, "high")+++def test_a_stored_stand_in_resolves_only_against_a_stored_route_on_its_backend() -> None:+ # The form rendered while the route was on Vibey; by the time it saves, the route may be on Codex.+ for stored_agent, expected in (("vibey", ("long-vibey-model", "high")), ("codex", (None, None))):+ stored = RoutingSettings(agent_name=stored_agent, model=f"long-{stored_agent}-model", reasoning_effort="high")+ settings_manager = _StubSettingsManager(stored)+ handler, _ = _make_handler(settings_manager)+ handler.controller.vibe_agent_store = SimpleNamespace(+ routing_name_for_backend=lambda backend: backend, get=lambda name: SimpleNamespace(backend=name)+ )++ asyncio.run(+ handler.handle_routing_update(+ user_id="42", channel_id="-100123", backend="vibey",+ model=STORED_OPTION_VALUE, reasoning_effort=STORED_OPTION_VALUE,+ notify_user=False, platform="telegram",+ )+ )++ saved = settings_manager.saved_routing+ assert (saved.agent_name, saved.model, saved.reasoning_effort) == ("vibey", *expected)++def test_handle_routing_update_warns_flat_scope_with_existing_backend_session() -> None:handler, send_message, sessions = _make_flat_scope_handler(row={"agent_backend": "opencode"})@@ -277,10 +355,8 @@ def test_handle_routing_update_warns_flat_scope_with_existing_backend_session()user_id="58181121",channel_id="58181121",backend="claude",- opencode_agent=None,- opencode_model=None,- claude_agent=None,- claude_model=None,+ variant=None,+ model=None,platform="telegram",is_dm=True,)@@ -300,10 +376,8 @@ def test_handle_routing_update_warns_wechat_flat_scope_with_existing_backend_sesuser_id="58181121",channel_id="58181121",backend="claude",- opencode_agent=None,- opencode_model=None,- claude_agent=None,- claude_model=None,+ variant=None,+ model=None,platform="wechat",is_dm=True,)@@ -330,10 +404,8 @@ def test_handle_routing_update_does_not_warn_flat_scope_same_backend_model_changuser_id="58181121",channel_id="58181121",backend="claude",- opencode_agent=None,- opencode_model=None,- claude_agent=None,- claude_model="claude-opus-4-1",+ variant=None,+ model="claude-opus-4-1",platform="telegram",is_dm=True,)@@ -360,11 +432,9 @@ def test_handle_routing_update_does_not_warn_flat_scope_same_backend_reasoning_cuser_id="58181121",channel_id="58181121",backend="claude",- opencode_agent=None,- opencode_model=None,- claude_agent=None,- claude_model="claude-sonnet-4-5",- claude_reasoning_effort="high",+ variant=None,+ model="claude-sonnet-4-5",+ reasoning_effort="high",platform="telegram",is_dm=True,)@@ -391,10 +461,8 @@ def test_handle_routing_update_does_not_warn_flat_scope_same_session_target() ->user_id="58181121",channel_id="58181121",backend="claude",- opencode_agent=None,- opencode_model=None,- claude_agent=None,- claude_model="claude-sonnet-4-5",+ variant=None,+ model="claude-sonnet-4-5",platform="telegram",is_dm=True,)@@ -413,10 +481,8 @@ def test_handle_routing_update_does_not_warn_when_flat_scope_has_no_session() ->user_id="58181121",channel_id="58181121",backend="claude",- opencode_agent=None,- opencode_model=None,- claude_agent=None,- claude_model=None,+ variant=None,+ model=None,platform="telegram",is_dm=True,)@@ -436,10 +502,8 @@ def test_handle_routing_update_does_not_warn_threaded_scope() -> None:user_id="U123",channel_id="D123",backend="claude",- opencode_agent=None,- opencode_model=None,- claude_agent=None,- claude_model=None,+ variant=None,+ model=None,platform="slack",is_dm=True,)@@ -570,8 +634,8 @@ def test_gather_routing_modal_data_fetches_selected_backend_on_modal_update() ->data = asyncio.run(handler._gather_routing_modal_data(context, selected_backend="claude"))assert data.current_backend == "opencode"- assert data.claude_agents == [{"id": "reviewer"}]- assert data.claude_models == ["claude-sonnet-4-6"]+ assert _values(data.menus["claude"].variants) == ["reviewer"]+ assert _values(data.menus["claude"].models) == ["claude-sonnet-4-6"]assert server.calls == []@@ -583,7 +647,8 @@ def test_gather_routing_modal_data_prefetches_all_backends_when_requested() -> N"vibe.api.claude_models",return_value={"ok": True,- "models": ["claude-sonnet-4-6"],+ # claude_models() appends the bare aliases after the dated catalog.+ "models": ["claude-sonnet-4-6", "opus"],"reasoning_options": {"claude-sonnet-4-6": [{"value": "max", "label": "Max"}]},},), patch("vibe.api.codex_agents", return_value={"ok": True, "agents": [{"id": "builder"}]}), patch(@@ -597,15 +662,16 @@ def test_gather_routing_modal_data_prefetches_all_backends_when_requested() -> Ndata = asyncio.run(handler._gather_routing_modal_data(context, include_all_backend_data=True))assert data.registered_backends == list(AGENT_BACKENDS)- assert data.opencode_agents == [{"name": "build"}]- assert data.claude_agents == [{"id": "reviewer"}]- assert data.claude_models == ["claude-sonnet-4-6"]- assert data.codex_agents == [{"id": "builder"}]- assert data.codex_models == ["gpt-5.4"]- assert data.backend_reasoning_options == {- "claude": {"claude-sonnet-4-6": [{"value": "max", "label": "Max"}]},- "codex": {"gpt-5.4": [{"value": "ultra", "label": "Ultra"}]},+ menus = data.menus+ assert {backend: _values(menu.variants) for backend, menu in menus.items()} == {+ "vibey": [], "opencode": ["build"], "claude": ["reviewer"], "codex": ["builder"],}+ # The always-valid bare aliases lead, so a capped select trims dated snapshots first.+ assert _values(menus["claude"].models) == ["opus", "claude-sonnet-4-6"]+ assert _values(menus["codex"].models) == ["gpt-5.4"]+ # Each model's catalog efforts, not a backend-wide ladder.+ assert _values(menus["claude"].efforts["claude-sonnet-4-6"]) == ["max"]+ assert _values(menus["codex"].efforts["gpt-5.4"]) == ["ultra"]assert server.calls == ["current_server","agents:/tmp/workspace",@@ -614,6 +680,66 @@ def test_gather_routing_modal_data_prefetches_all_backends_when_requested() -> N]+def test_opencode_route_menu_fits_the_platforms_cap_and_is_whole_without_one() -> None:+ handler, server = _make_routing_handler()+ # More providers than the select has slots, each leading (newest first) with ids too long for Discord.+ providers = [+ {+ "id": f"p{p}",+ "name": f"P{p}",+ "models": {+ **{f"{'x' * 120}-{i}": {"name": f"Long {i}", "release_date": "2026-09-01"} for i in range(6)},+ **{f"m{i}": {"name": f"M{i}", "release_date": "2026-01-01"} for i in range(3)},+ },+ }+ for p in range(30)+ ]+ server.get_available_models = AsyncMock(return_value={"providers": providers})+ context = MessageContext(user_id="U1", channel_id="D0APS47LPU2", platform="discord")+ menus = {}+ for limit, value_limit in ((25, 100), (None, None)): # Discord's select; Telegram's paged picker+ handler._get_im_client = lambda context, limit=limit, value_limit=value_limit: SimpleNamespace(+ route_option_limit=limit, route_option_value_limit=value_limit+ )+ menus[limit] = asyncio.run(handler._gather_routing_modal_data(context)).menus["opencode"]++ capped = menus[25].model_options(None)+ assert len(capped) == 24 and all("/m" in option.value for option in capped)+ assert len(menus[None].model_options(None)) == 270+++def test_gather_routing_modal_data_reads_vibey_menu_from_model_hub() -> None:+ handler, server = _make_routing_handler()+ handler.controller.resolve_agent_for_context = lambda context: "vibey"+ catalog = [+ {"id": "model-a", "display_name": "Model A", "routeable": True, "supports_reasoning": True,+ "reasoning_efforts": ["low", "high", "max"], "effort_menu": {"omitted": ["max"], "not_on": {}}},+ {"id": "model-b", "display_name": None, "routeable": True, "supports_reasoning": False,+ "reasoning_efforts": ["low"], "effort_menu": {"omitted": [], "not_on": {}}},+ {"id": "selector", "routeable": False, "reasoning_efforts": []},+ ]+ read_agent_sources = AsyncMock(return_value={"backend": "vibey", "catalog_models": catalog})+ handler.controller.model_hub_service = SimpleNamespace(read_agent_sources=read_agent_sources)+ handler.controller.vibe_agent_store = SimpleNamespace(+ get_builtin_default_agent_for_backend=lambda backend, enabled_only=True: SimpleNamespace(model="model-a"),+ )+ context = MessageContext(user_id="U1", channel_id="D0APS47LPU2", platform="slack")++ data = asyncio.run(handler._gather_routing_modal_data(context))++ read_agent_sources.assert_awaited_once_with("vibey")+ assert data.current_backend == "vibey"+ menu = data.menus["vibey"]+ assert menu.models == [RouteOption("model-a", "Model A"), RouteOption("model-b", "model-b")]+ # Model Hub's omitted efforts are not offered; a route without its own model inherits the Vibey Agent's.+ assert {model: _values(efforts) for model, efforts in menu.efforts.items()} == {+ "model-a": ["low", "high"],+ "model-b": [],+ "": ["low", "high"],+ }+ assert server.calls == []++def test_gather_routing_modal_data_hides_disabled_backends() -> None:handler, server = _make_routing_handler()handler.config.claude.enabled = False@@ -647,7 +773,7 @@ def test_gather_routing_modal_data_falls_back_to_visible_backend_when_current_is# Listed first, the built-in backend is still not the fallback while another is enabled.assert data.current_backend == "opencode"assert data.registered_backends == ["vibey", "opencode", "codex"]- assert data.opencode_agents == [{"name": "build"}]+ assert _values(data.menus["opencode"].variants) == ["build"]assert server.calls == ["current_server","agents:/tmp/workspace",@@ -656,6 +782,58 @@ def test_gather_routing_modal_data_falls_back_to_visible_backend_when_current_is]+def test_slack_backend_switch_back_shows_the_stored_route_not_blanks() -> None:+ """Switching the Slack modal away from the stored backend and back must not blank what saving would persist."""+ from config.v2_config import SlackConfig+ from modules.im.slack import SlackBot+ from modules.im.slack_modal import parse_routing_modal_selection++ handler, _server = _make_routing_handler()+ routing = RoutingSettings(agent_name="vibey", model="model-b", reasoning_effort="high")+ handler.settings_manager = SimpleNamespace(get_channel_routing=lambda settings_key: routing)+ handler.controller.resolve_agent_for_context = lambda context: "vibey"+ catalog = [+ {"id": model_id, "routeable": True, "reasoning_efforts": ["low", "high"], "effort_menu": {"omitted": []}}+ for model_id in ("model-a", "model-b")+ ]+ handler.controller.model_hub_service = SimpleNamespace(+ read_agent_sources=AsyncMock(return_value={"catalog_models": catalog}),+ )+ bot = SlackBot(SlackConfig(bot_token="fixture-token"))+ bot._ensure_clients = lambda: None+ bot.web_client = SimpleNamespace(views_update=AsyncMock())+ handler._get_im_client = lambda context: bot+ # The modal as Slack holds it after a switch to OpenCode: it has no Vibey controls.+ view = bot._build_routing_modal_view(+ channel_id="D0APS47LPU2",+ routing=RoutingModalData(registered_backends=["vibey", "opencode"], current_backend="vibey", current_routing=routing),+ selected_backend="opencode",+ )+ view["state"] = {"values": {+ block["block_id"]: {block["element"]["action_id"]: {"selected_option": block["element"]["initial_option"]}}+ for block in view["blocks"] if block["type"] == "input"+ }}+ view["state"]["values"]["backend_block"]["backend_select"] = {"selected_option": {"value": "vibey"}}+ selection = parse_routing_modal_selection(+ view=view, action={"action_id": "backend_select", "selected_option": {"value": "vibey"}}+ )++ asyncio.run(+ handler.handle_routing_modal_update(+ user_id="U1", channel_id="D0APS47LPU2", view_id="view-1", view_hash="hash-1",+ selection=selection, platform="slack",+ )+ )++ updated = bot.web_client.views_update.await_args.kwargs["view"]+ shown = {+ block["block_id"].rsplit(":", 1)[0] if block["block_id"].startswith("route_effort:") else block["block_id"]:+ block["element"]["initial_option"]["value"]+ for block in updated["blocks"] if block["type"] == "input"+ }+ assert (shown["route_model:vibey"], shown["route_effort:vibey"]) == ("model-b", "high")++def test_handle_routing_modal_update_uses_visible_current_backend() -> None:handler, _server = _make_routing_handler()handler.config.claude.enabled = False@@ -680,5 +858,5 @@ def test_handle_routing_modal_update_uses_visible_current_backend() -> None:)assert len(update_calls) == 1- assert update_calls[0]["current_backend"] == "opencode"+ assert update_calls[0]["routing"].current_backend == "opencode"assert update_calls[0]["selected_backend"] == "opencode"diff --git a/tests/test_slack_app_mention_empty.py b/tests/test_slack_app_mention_empty.pyindex 3a04ead2c..1ae3b0d48 100644--- a/tests/test_slack_app_mention_empty.py+++ b/tests/test_slack_app_mention_empty.py@@ -130,84 +130,5 @@ class SlackFileAttachmentTests(unittest.IsolatedAsyncioTestCase):slack.web_client.files_info.assert_awaited_once_with(file="F123")-class SlackRoutingModalTests(unittest.TestCase):- @staticmethod- def _find_select(view, block_id):- for block in view["blocks"]:- if block.get("block_id") == block_id:- return block["element"]- raise AssertionError(f"block {block_id} not found")-- def test_backend_switch_does_not_reuse_other_backend_canonical_override(self):- slack = SlackBot(SlackConfig(bot_token="xoxb-test"))- current_routing = SimpleNamespace(- agent_backend="codex",- model="gpt-5.4",- reasoning_effort="high",- opencode_agent=None,- opencode_model=None,- opencode_reasoning_effort=None,- claude_agent=None,- claude_model=None,- claude_reasoning_effort=None,- codex_agent=None,- codex_model=None,- codex_reasoning_effort=None,- )-- view = slack._build_routing_modal_view(- channel_id="C123",- registered_backends=["opencode", "codex"],- current_backend="codex",- current_routing=current_routing,- opencode_agents=[],- opencode_models={"openai": {"models": [{"id": "gpt-5.4", "name": "gpt-5.4"}]}},- opencode_default_config={},- codex_models=["gpt-5.4"],- selected_backend="opencode",- )-- model_select = self._find_select(view, "opencode_model_block")- reasoning_select = self._find_select(view, "opencode_reasoning_block")- self.assertEqual(model_select["initial_option"]["value"], "__default__")- self.assertEqual(reasoning_select["initial_option"]["value"], "__default__")-- def test_codex_reasoning_uses_shared_catalog_options(self):- slack = SlackBot(SlackConfig(bot_token="xoxb-test"))- current_routing = SimpleNamespace(- agent_backend="codex",- model="gpt-5.6-terra",- reasoning_effort=None,- codex_agent=None,- codex_model=None,- codex_reasoning_effort=None,- )-- view = slack._build_routing_modal_view(- channel_id="C123",- registered_backends=["codex"],- current_backend="codex",- current_routing=current_routing,- opencode_agents=[],- opencode_models={},- opencode_default_config={},- codex_models=["gpt-5.6-terra"],- backend_reasoning_options={- "codex": {- "gpt-5.6-terra": [- {"value": "__default__", "label": "(Default)"},- {"value": "ultra", "label": "Ultra"},- ]- }- },- )-- reasoning_select = self._find_select(view, "codex_reasoning_block")- self.assertEqual(- [option["value"] for option in reasoning_select["options"]],- ["__default__", "ultra"],- )--if __name__ == "__main__":unittest.main()diff --git a/tests/test_telegram_bot.py b/tests/test_telegram_bot.pyindex db606c560..c1262241e 100644--- a/tests/test_telegram_bot.py+++ b/tests/test_telegram_bot.py@@ -20,6 +20,7 @@ from core.processing_indicator import (STOPPED_REACTION_EMOJI,)from core.message_context import resolve_context_thread_id+from core.modals import RoutingModalDatafrom modules.agents.native_sessions import NativeResumeSessionfrom modules.agents.catalog import AGENT_BACKENDSfrom modules.im import InlineButton, InlineKeyboard, MessageContext@@ -1314,61 +1315,34 @@ def test_resume_callback_submits_selected_session() -> None:)-def test_routing_callback_save_persists_selected_backend() -> None:- bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))- context = MessageContext(- user_id="42",- channel_id="-100123",- message_id="88",- platform="telegram",- platform_specific={"is_dm": False},- )- bot._routing_states[bot._interaction_scope_key(context)] = SimpleNamespace(+def _routing_state(context, registered, backend):+ from modules.im.telegram import _TelegramRoutingState++ return _TelegramRoutingState(message_id="88",channel_id=context.channel_id,+ thread_id=None,user_id=context.user_id,is_dm=False,- backend="codex",- opencode_agent=None,- opencode_model=None,- opencode_reasoning_effort=None,- claude_agent=None,- claude_model=None,- claude_reasoning_effort=None,- codex_model="gpt-5",- codex_reasoning_effort="high",- picker_field=None,- picker_page=0,- )- bot._controller = SimpleNamespace(- settings_handler=SimpleNamespace(handle_routing_update=AsyncMock()),+ routing=RoutingModalData(registered_backends=list(registered), current_backend=backend, current_routing=None),+ backend=backend,)- with patch.object(bot, "_delete_interaction_message", new=AsyncMock()) as delete_mock:- asyncio.run(bot._handle_routing_callback(context, "tg_route:save"))- delete_mock.assert_awaited_once_with(context, "88")- bot._controller.settings_handler.handle_routing_update.assert_awaited_once()+def _routing_context() -> MessageContext:+ return MessageContext(+ user_id="42",+ channel_id="-100123",+ message_id="88",+ platform="telegram",+ platform_specific={"is_dm": False},+ )def test_routing_state_marks_current_backend_in_first_row() -> None:bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))- state = SimpleNamespace(- registered_backends=list(ROUTING_BACKENDS),- backend="claude",- opencode_agent=None,- opencode_model=None,- opencode_reasoning_effort=None,- claude_agent="reviewer",- claude_model="claude-sonnet-4-6",- claude_reasoning_effort="high",- codex_model=None,- codex_reasoning_effort=None,- picker_field=None,- picker_page=0,- )- _, keyboard = bot._render_routing_state(state)+ _, keyboard = bot._render_routing_state(_routing_state(_routing_context(), ROUTING_BACKENDS, "claude"))assert [button.callback_data for button in keyboard.buttons[0]] == ["tg_route:backend:vibey",@@ -1378,93 +1352,25 @@ def test_routing_state_marks_current_backend_in_first_row() -> None:assert keyboard.buttons[0][2].text.startswith("☑️ ")-def test_routing_codex_reasoning_uses_shared_catalog_options() -> None:- bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))- state = SimpleNamespace(- picker_field="codex_reasoning_effort",- codex_model="gpt-5.6-terra",- backend_reasoning_options={- "codex": {- "gpt-5.6-terra": [- {"value": "__default__", "label": "(Default)"},- {"value": "ultra", "label": "Ultra"},- ]- }- },- )-- assert bot._routing_picker_options(state) == [- (bot._t("common.default"), None),- ("Ultra", "ultra"),- ]-+def test_routing_summary_bounds_an_unbounded_model_label() -> None:+ from config.v2_settings import RoutingSettings+ from core.modals import BackendRouteMenu, RouteOption-def test_open_routing_modal_clears_stale_catalog_effort() -> None:bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))- context = MessageContext(- user_id="42",- channel_id="-100123",- message_id="88",- platform="telegram",- platform_specific={"is_dm": False},- )- current_routing = SimpleNamespace(- model="gpt-5.6-terra",- reasoning_effort="minimal",- codex_agent=None,- )+ state = _routing_state(_routing_context(), ["vibey"], "vibey")+ state.routing.current_routing = RoutingSettings(agent_name="vibey", model="m" * 5000)+ state.routing.menus["vibey"] = BackendRouteMenu("vibey", models=[RouteOption("m" * 5000, "Label " * 1000)])- with patch.object(bot, "send_message_with_buttons", new=AsyncMock(return_value="99")):- asyncio.run(- bot.open_routing_modal(- context,- context.channel_id,- current_routing=current_routing,- current_backend="codex",- registered_backends=["codex"],- codex_models=["gpt-5.6-terra"],- backend_reasoning_options={- "codex": {- "gpt-5.6-terra": [- {"value": "__default__", "label": "(Default)"},- {"value": "ultra", "label": "Ultra"},- ]- }- },- )- )+ text, keyboard = bot._render_routing_state(state)- state = bot._routing_states[bot._interaction_scope_key(context)]- assert state.codex_reasoning_effort is None+ assert len(text) < 1000+ assert all(len(button.text) <= 40 for row in keyboard.buttons for button in row)def test_routing_callback_backend_switches_without_nested_picker() -> None:bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))- context = MessageContext(- user_id="42",- channel_id="-100123",- message_id="88",- platform="telegram",- platform_specific={"is_dm": False},- )- bot._routing_states[bot._interaction_scope_key(context)] = SimpleNamespace(- message_id="88",- channel_id=context.channel_id,- user_id=context.user_id,- is_dm=False,- registered_backends=list(ROUTING_BACKENDS),- backend="opencode",- opencode_agent=None,- opencode_model=None,- opencode_reasoning_effort=None,- claude_agent=None,- claude_model=None,- claude_reasoning_effort=None,- codex_model=None,- codex_reasoning_effort=None,- picker_field=None,- picker_page=0,- )+ context = _routing_context()+ bot._routing_states[bot._interaction_scope_key(context)] = _routing_state(context, ROUTING_BACKENDS, "opencode")with patch.object(bot, "edit_message", new=AsyncMock(return_value=True)) as edit_mock:asyncio.run(bot._handle_routing_callback(context, "tg_route:backend:claude"))@@ -1475,25 +1381,15 @@ def test_routing_callback_backend_switches_without_nested_picker() -> None:edit_mock.assert_awaited_once()+def _with_extra(extra_backend):+ return [*ROUTING_BACKENDS, *([] if extra_backend in ROUTING_BACKENDS else [extra_backend])]++@pytest.mark.parametrize("extra_backend", ["vibey", "extra"])def test_routing_state_keeps_backend_picker_entry_for_extra_backends(extra_backend) -> None:bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))- state = SimpleNamespace(- registered_backends=[*ROUTING_BACKENDS, *([] if extra_backend in ROUTING_BACKENDS else [extra_backend])],- backend=extra_backend,- opencode_agent=None,- opencode_model=None,- opencode_reasoning_effort=None,- claude_agent=None,- claude_model=None,- claude_reasoning_effort=None,- codex_model=None,- codex_reasoning_effort=None,- picker_field=None,- picker_page=0,- )- text, keyboard = bot._render_routing_state(state)+ text, keyboard = bot._render_routing_state(_routing_state(_routing_context(), _with_extra(extra_backend), extra_backend))if extra_backend == "vibey":assert "Vibey" in text@@ -1508,30 +1404,9 @@ def test_routing_state_keeps_backend_picker_entry_for_extra_backends(extra_backe@pytest.mark.parametrize("extra_backend", ["vibey", "extra"])def test_routing_callback_backend_picker_can_select_extra_backend(extra_backend) -> None:bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))- context = MessageContext(- user_id="42",- channel_id="-100123",- message_id="88",- platform="telegram",- platform_specific={"is_dm": False},- )- bot._routing_states[bot._interaction_scope_key(context)] = SimpleNamespace(- message_id="88",- channel_id=context.channel_id,- user_id=context.user_id,- is_dm=False,- registered_backends=[*ROUTING_BACKENDS, *([] if extra_backend in ROUTING_BACKENDS else [extra_backend])],- backend="opencode",- opencode_agent=None,- opencode_model=None,- opencode_reasoning_effort=None,- claude_agent=None,- claude_model=None,- claude_reasoning_effort=None,- codex_model=None,- codex_reasoning_effort=None,- picker_field=None,- picker_page=0,+ context = _routing_context()+ bot._routing_states[bot._interaction_scope_key(context)] = _routing_state(+ context, _with_extra(extra_backend), "opencode")with patch.object(bot, "edit_message", new=AsyncMock(return_value=True)) as edit_mock:diff --git a/tests/test_vibey_backend_registration.py b/tests/test_vibey_backend_registration.pyindex cc1f7f9e6..983cc9b91 100644--- a/tests/test_vibey_backend_registration.py+++ b/tests/test_vibey_backend_registration.py@@ -471,7 +471,6 @@ def test_choosing_the_built_in_backend_in_an_im_picker_routes_to_its_agent(tmp_pfor backend, expected in (("vibey", built_in.name), ("claude", "claude")):asyncio.run(handler.handle_routing_update(user_id="U1", channel_id="C-test", backend=backend,- opencode_agent=None, opencode_model=None, claude_agent=None, claude_model=None,notify_user=False, platform="slack",))assert saved["C-test"].agent_name == expecteddiff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 3d395d9b2..a0812e419 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -594,9 +594,7 @@"mentionPolicy": "Mention policy","language": "Language","backend": "Backend",- "opencodeAgent": "OpenCode agent",- "claudeAgent": "Claude agent",- "codexAgent": "Codex agent",+ "backendAgent": "{backend} agent","model": "Model","reasoningEffort": "Reasoning effort"}@@ -679,20 +677,13 @@"currentBackend": "Current Backend:","backend": "Backend","selectBackend": "Select backend",- "opencodeSettings": "OpenCode Settings",- "opencodeAgent": "OpenCode Agent",- "selectOpencodeAgent": "Select OpenCode agent",+ "backendSettings": "{backend} Settings",+ "backendAgent": "{backend} Agent",+ "selectBackendAgent": "Select {backend} agent","model": "Model","selectModel": "Select model","reasoningEffort": "Reasoning Effort (Thinking Mode)","selectReasoningEffort": "Select reasoning effort",- "claudeSettings": "Claude Settings",- "claudeAgent": "Claude Agent",- "selectClaudeAgent": "Select Claude agent",- "codexSettings": "Codex Settings",- "codexAgent": "Codex Agent",- "selectCodexAgent": "Select Codex agent",- "codexReasoningEffort": "Reasoning Effort","tip": "Select (Default) to use the backend's configured defaults."}},diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 44b206171..11edd3311 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -594,9 +594,7 @@"mentionPolicy": "提及策略","language": "语言","backend": "后端",- "opencodeAgent": "OpenCode Agent",- "claudeAgent": "Claude Agent",- "codexAgent": "Codex Agent",+ "backendAgent": "{backend} Agent","model": "模型","reasoningEffort": "推理强度"}@@ -679,20 +677,13 @@"currentBackend": "当前后端:","backend": "后端","selectBackend": "选择后端",- "opencodeSettings": "OpenCode 设置",- "opencodeAgent": "OpenCode Agent",- "selectOpencodeAgent": "选择 OpenCode Agent",+ "backendSettings": "{backend} 设置",+ "backendAgent": "{backend} Agent",+ "selectBackendAgent": "选择 {backend} Agent","model": "模型","selectModel": "选择模型","reasoningEffort": "推理强度(思考模式)","selectReasoningEffort": "选择推理强度",- "claudeSettings": "Claude 设置",- "claudeAgent": "Claude Agent",- "selectClaudeAgent": "选择 Claude Agent",- "codexSettings": "Codex 设置",- "codexAgent": "Codex Agent",- "selectCodexAgent": "选择 Codex Agent",- "codexReasoningEffort": "推理强度","tip": "选择“(默认)”以使用后端的配置默认值。"}},