DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(partners): add provider-first Feishu model picker
Bingxi Zhao (Frank)44a76ed0a922
diff --git a/deeptutor/partners/channels/feishu.py b/deeptutor/partners/channels/feishu.pyindex 53de22a66..60452f31a 100644--- a/deeptutor/partners/channels/feishu.py+++ b/deeptutor/partners/channels/feishu.py@@ -322,10 +322,12 @@ class _ModelPicker:"""Server-owned model choices; card button values contain only an index."""sender_id: str+ providers: list[dict[str, Any]]options: list[dict[str, Any]]current: dict[str, str]created_at: floatpending: bool = False+ pending_index: int | None = Noneclass FeishuChannel(BaseChannel):@@ -1471,27 +1473,105 @@ class FeishuChannel(BaseChannel):model = str(option.get("model_name") or option.get("model") or "model")return f"{provider} · {model}"- def _model_picker_card(self, picker_id: str, picker: _ModelPicker, page: int) -> dict[str, Any]:+ @staticmethod+ def _provider_label(provider: dict[str, Any]) -> str:+ return str(+ provider.get("profile_name")+ or provider.get("provider_label")+ or provider.get("profile_id")+ or "LLM"+ )++ @staticmethod+ def _provider_option_indices(picker: _ModelPicker, provider_index: int) -> list[int]:+ profile_id = picker.providers[provider_index]["profile_id"]+ return [+ index+ for index, option in enumerate(picker.options)+ if option.get("profile_id") == profile_id+ ]++ def _provider_picker_card(self, picker_id: str, picker: _ModelPicker) -> dict[str, Any]:+ elements: list[dict[str, Any]] = [+ {"tag": "div", "text": {"tag": "plain_text", "content": "Choose a provider"}}+ ]+ for index, provider in enumerate(picker.providers):+ current = picker.current.get("profile_id") == provider.get("profile_id")+ elements.append(+ {+ "tag": "action",+ "actions": [+ {+ "tag": "button",+ "text": {+ "tag": "plain_text",+ "content": f"{'✓ ' if current else ''}{self._provider_label(provider)}"[+ :90+ ],+ },+ "type": "primary" if current else "default",+ "value": {+ "picker_id": picker_id,+ "action": "pick_provider",+ "index": index,+ },+ }+ ],+ }+ )+ return {+ "config": {"wide_screen_mode": True},+ "header": {"title": {"tag": "plain_text", "content": "Switch model"}},+ "elements": elements,+ }++ def _model_picker_card(+ self,+ picker_id: str,+ picker: _ModelPicker,+ provider_index: int,+ page: int,+ *,+ status: str = "",+ ) -> dict[str, Any]:+ option_indices = self._provider_option_indices(picker, provider_index)total_pages = max(- 1, (len(picker.options) + self._MODEL_PAGE_SIZE - 1) // self._MODEL_PAGE_SIZE+ 1, (len(option_indices) + self._MODEL_PAGE_SIZE - 1) // self._MODEL_PAGE_SIZE)page = max(0, min(page, total_pages - 1))start = page * self._MODEL_PAGE_SIZE- elements: list[dict[str, Any]] = [+ provider = picker.providers[provider_index]+ name_counts: dict[str, int] = {}+ for index in option_indices:+ option = picker.options[index]+ name = str(option.get("model_name") or option.get("model") or "model").casefold()+ name_counts[name] = name_counts.get(name, 0) + 1+ elements: list[dict[str, Any]] = []+ if status:+ elements.append({"tag": "div", "text": {"tag": "plain_text", "content": status}})+ elements.append({"tag": "div","text": {"tag": "plain_text",- "content": f"Choose a model · Page {page + 1} of {total_pages}",+ "content": (+ f"{self._provider_label(provider)} · Choose a model · "+ f"Page {page + 1} of {total_pages}"+ ),},}- ]- for index in range(start, min(start + self._MODEL_PAGE_SIZE, len(picker.options))):+ )+ for local_index, index in enumerate(+ option_indices[start : start + self._MODEL_PAGE_SIZE], start=start+ ):option = picker.options[index]current = picker.current.get("profile_id") == option.get("profile_id") and picker.current.get("model_id") == option.get("model_id")- label = f"{'✓ ' if current else ''}{index + 1}. {self._model_label(option)}"+ model_name = str(option.get("model_name") or option.get("model") or "model")+ if name_counts[model_name.casefold()] > 1:+ model_name += f" ({option['model']})"+ label = f"{'✓ ' if current else ''}{local_index + 1}. {model_name}"elements.append({"tag": "action",@@ -1500,7 +1580,12 @@ class FeishuChannel(BaseChannel):"tag": "button","text": {"tag": "plain_text", "content": label[:90]},"type": "primary" if current else "default",- "value": {"picker_id": picker_id, "action": "select", "index": index},+ "value": {+ "picker_id": picker_id,+ "action": "select",+ "provider_index": provider_index,+ "index": index,+ },}],}@@ -1513,11 +1598,23 @@ class FeishuChannel(BaseChannel):"tag": "button","text": {"tag": "plain_text", "content": label},"type": "default",- "value": {"picker_id": picker_id, "action": "page", "page": target},+ "value": {+ "picker_id": picker_id,+ "action": "page",+ "provider_index": provider_index,+ "page": target,+ },})- if navigation:- elements.append({"tag": "action", "actions": navigation})+ navigation.append(+ {+ "tag": "button",+ "text": {"tag": "plain_text", "content": "◀ Providers"},+ "type": "default",+ "value": {"picker_id": picker_id, "action": "providers"},+ }+ )+ elements.append({"tag": "action", "actions": navigation})return {"config": {"wide_screen_mode": True},"header": {"title": {"tag": "plain_text", "content": "Switch model"}},@@ -1532,7 +1629,7 @@ class FeishuChannel(BaseChannel):"elements": [{"tag": "div", "text": {"tag": "plain_text", "content": content}}],}- def _patch_model_card_sync(self, message_id: str, content: str) -> bool:+ def _patch_model_card_sync(self, message_id: str, card: dict[str, Any]) -> bool:"""Replace the clicked card after the command finishes."""from lark_oapi.api.im.v1 import PatchMessageRequest, PatchMessageRequestBody@@ -1542,7 +1639,7 @@ class FeishuChannel(BaseChannel):.message_id(message_id).request_body(PatchMessageRequestBody.builder()- .content(json.dumps(self._model_status_card(content), ensure_ascii=False))+ .content(json.dumps(card, ensure_ascii=False)).build()).build()@@ -1561,13 +1658,18 @@ class FeishuChannel(BaseChannel):return Falseasync def _queue_model_choice(- self, *, sender_id: str, message_id: str, option: dict[str, Any]+ self,+ *,+ sender_id: str,+ message_id: str,+ picker_id: str,+ option: dict[str, Any],) -> None:"""Enter the normal Partner command runner after the callback has returned."""command = ("/model "f"{shlex.quote(str(option['profile_id']))} "- f"{shlex.quote(str(option['model_id']))}"+ f"{shlex.quote(str(option.get('model') or option['model_id']))}")await self._handle_message(sender_id=sender_id,@@ -1576,6 +1678,7 @@ class FeishuChannel(BaseChannel):metadata={"chat_type": "p2p","_feishu_model_picker_message_id": message_id,+ "_feishu_model_picker_id": picker_id,},)@@ -1620,17 +1723,34 @@ class FeishuChannel(BaseChannel):if picker.pending:return error_response("A model switch is already in progress.")action = value.get("action")+ if action == "providers":+ return card_response(self._provider_picker_card(picker_id, picker))+ if action == "pick_provider":+ provider_index = value.get("index")+ if (+ type(provider_index) is not int+ or not 0 <= provider_index < len(picker.providers)+ or not self._provider_option_indices(picker, provider_index)+ ):+ return error_response("Invalid model provider.")+ return card_response(self._model_picker_card(picker_id, picker, provider_index, 0))+ provider_index = value.get("provider_index")+ if type(provider_index) is not int or not 0 <= provider_index < len(picker.providers):+ return error_response("Invalid model provider.")+ option_indices = self._provider_option_indices(picker, provider_index)if action == "page":page = value.get("page")if type(page) is not int or not 0 <= page * self._MODEL_PAGE_SIZE < len(- picker.options+ option_indices):return error_response("Invalid model picker page.")- return card_response(self._model_picker_card(picker_id, picker, page))+ return card_response(+ self._model_picker_card(picker_id, picker, provider_index, page)+ )if action != "select":return error_response("Invalid model picker action.")index = value.get("index")- if type(index) is not int or not 0 <= index < len(picker.options):+ if type(index) is not int or index not in option_indices:return error_response("Invalid model choice.")loop = self._loopif loop is None or not loop.is_running():@@ -1646,20 +1766,41 @@ class FeishuChannel(BaseChannel):None,)previous = self._model_label(current) if current else "default"- pending_card = self._model_status_card(- f"⏳ Switching model: {previous} → {self._model_label(option)}…"+ pending_page = option_indices.index(index) // self._MODEL_PAGE_SIZE+ pending_card = self._model_picker_card(+ picker_id,+ picker,+ provider_index,+ pending_page,+ status=f"⏳ Switching model: {previous} → {self._model_label(option)}…",)picker.pending = True+ picker.pending_index = indextry:- asyncio.run_coroutine_threadsafe(+ queued = asyncio.run_coroutine_threadsafe(self._queue_model_choice(- sender_id=sender_id, message_id=message_id, option=option+ sender_id=sender_id,+ message_id=message_id,+ picker_id=picker_id,+ option=option,),loop,)except RuntimeError:picker.pending = False+ picker.pending_index = Nonereturn error_response("The bot is reconnecting. Send /model again.")++ def release_failed_queue(future: Any) -> None:+ if not future.cancelled() and future.exception() is None:+ return+ with self._model_picker_lock:+ live = self._model_pickers.get(picker_id)+ if live is picker and live.pending_index == index:+ live.pending = False+ live.pending_index = None++ queued.add_done_callback(release_failed_queue)return card_response(pending_card)async def send(self, msg: OutboundMessage) -> None:@@ -1679,8 +1820,40 @@ class FeishuChannel(BaseChannel):if picker_message_id:completed = bool(metadata.get("_feishu_model_switch_success"))content = msg.content if completed else f"⚠️ {msg.content}"+ card = self._model_status_card(content)+ picker_id = str(metadata.get("_feishu_model_picker_id") or "")+ with self._model_picker_lock:+ picker = self._model_pickers.get(picker_id)+ if (+ picker is not None+ and picker.sender_id == msg.chat_id+ and picker.pending_index is not None+ ):+ index = picker.pending_index+ option = picker.options[index]+ if completed:+ picker.current = {+ "profile_id": str(option["profile_id"]),+ "model_id": str(option["model_id"]),+ }+ picker.pending = False+ picker.pending_index = None+ provider_index = next(+ (+ i+ for i, provider in enumerate(picker.providers)+ if provider["profile_id"] == option["profile_id"]+ ),+ None,+ )+ if provider_index is not None:+ option_indices = self._provider_option_indices(picker, provider_index)+ page = option_indices.index(index) // self._MODEL_PAGE_SIZE+ card = self._model_picker_card(+ picker_id, picker, provider_index, page, status=content+ )patched = await loop.run_in_executor(- None, self._patch_model_card_sync, picker_message_id, content+ None, self._patch_model_card_sync, picker_message_id, card)if not patched:await loop.run_in_executor(@@ -1693,16 +1866,47 @@ class FeishuChannel(BaseChannel):)return- picker_options = metadata.get("_feishu_model_options")- if (- isinstance(picker_options, list)- and picker_options- and msg.chat_id.startswith("ou_")- ):+ raw_options = metadata.get("_feishu_model_options")+ picker_options = (+ [+ option+ for option in raw_options+ if isinstance(option, dict)+ and option.get("profile_id")+ and option.get("model_id")+ and option.get("model")+ ]+ if isinstance(raw_options, list)+ else []+ )+ if picker_options and msg.chat_id.startswith("ou_"):+ listed_providers = {+ str(row.get("profile_id")): row+ for row in (metadata.get("_feishu_model_providers") or [])+ if isinstance(row, dict) and row.get("profile_id")+ }+ providers: list[dict[str, Any]] = []+ seen_profiles: set[str] = set()+ for option in picker_options:+ profile_id = str(option["profile_id"])+ if profile_id in seen_profiles:+ continue+ seen_profiles.add(profile_id)+ listed = listed_providers.get(profile_id) or {}+ providers.append(+ {+ "profile_id": profile_id,+ "profile_name": listed.get("profile_name")+ or option.get("profile_name"),+ "provider_label": listed.get("provider_label")+ or option.get("provider_label"),+ }+ )picker_id = uuid.uuid4().hex[:16]picker = _ModelPicker(sender_id=msg.chat_id,- options=list(picker_options),+ providers=providers,+ options=picker_options,current=dict(metadata.get("_feishu_model_current") or {}),created_at=time.monotonic(),)@@ -1715,7 +1919,7 @@ class FeishuChannel(BaseChannel):"open_id",msg.chat_id,"interactive",- json.dumps(self._model_picker_card(picker_id, picker, 0), ensure_ascii=False),+ json.dumps(self._provider_picker_card(picker_id, picker), ensure_ascii=False),reply_to_message_id,)if sent:diff --git a/deeptutor/services/partners/commands.py b/deeptutor/services/partners/commands.pyindex 84e0a72ea..07ee07304 100644--- a/deeptutor/services/partners/commands.py+++ b/deeptutor/services/partners/commands.py@@ -288,16 +288,45 @@ class PartnerCommandHandler:),None,)+ name_counts: dict[str, int] = {}+ for row in options:+ key = row["model_name"].casefold()+ name_counts[key] = name_counts.get(key, 0) + 1++ def option_label(row: dict[str, Any]) -> str:+ label = f"{row['provider_label']} · {row['model_name']}"+ if name_counts[row["model_name"].casefold()] > 1:+ label += f" ({row['model']})"+ return label+if not args:if not options:return PartnerCommandResult("No chat models are configured for this account.")lines = ["Available models:"]for index, row in enumerate(options, 1):selected = " (current)" if row is current else ""- lines.append(f"{index}. {row['provider_label']} · {row['model_name']}{selected}")- lines.append("Use /model <number> to switch.")+ lines.append(f"{index}. {option_label(row)}{selected}")+ lines.append("Use /model <number> or /model <wire model name> to switch.")+ providers: list[dict[str, str]] = []+ seen_profiles: set[str] = set()+ for row in options:+ profile_id = row["profile_id"]+ if profile_id in seen_profiles:+ continue+ seen_profiles.add(profile_id)+ providers.append(+ {+ "profile_id": profile_id,+ "provider_label": row["provider_label"],+ "profile_name": row["profile_name"],+ }+ )metadata = (- {"_feishu_model_options": options, "_feishu_model_current": active}+ {+ "_feishu_model_options": options,+ "_feishu_model_providers": providers,+ "_feishu_model_current": active,+ }if msg.channel == "feishu" and (msg.metadata or {}).get("chat_type") == "p2p"else None)@@ -309,26 +338,33 @@ class PartnerCommandHandler:if 0 <= index < len(options):choice = options[index]elif len(args) == 2:- choice = next(- (- row- for row in options- if row["profile_id"] == args[0] and row["model_id"] == args[1]- ),- None,- )+ profile_options = [row for row in options if row["profile_id"] == args[0]]+ wire_matches = [row for row in profile_options if row["model"] == args[1]]+ if len(wire_matches) > 1:+ return PartnerCommandResult(+ "That wire model name is ambiguous. Use its /model number."+ )+ if wire_matches:+ choice = wire_matches[0]+ else:+ choice = next((row for row in profile_options if row["model_id"] == args[1]), None)if choice is None and not (len(args) == 1 and args[0].isdigit()):requested_name = " ".join(args)matches = [- row- for row in options- if requested_name.casefold()- in {row["model_name"].casefold(), row["model"].casefold()}+ row for row in options if row["model"].casefold() == requested_name.casefold()]+ if not matches:+ matches = [+ row+ for row in options+ if row["model_name"].casefold() == requested_name.casefold()+ ]if len(matches) == 1:choice = matches[0]elif len(matches) > 1:- return PartnerCommandResult("That model name is ambiguous. Use its /model number.")+ return PartnerCommandResult(+ "That model name is ambiguous. Use its /model number or wire model name."+ )if choice is None:return PartnerCommandResult("Unknown model. Use /model to see available numbers.")@@ -341,17 +377,13 @@ class PartnerCommandHandler:except (PermissionError, ValueError) as exc:return PartnerCommandResult(str(exc))- selected_label = f"{choice['provider_label']} · {choice['model_name']}"+ selected_label = option_label(choice)if selection == configured_selection and not legacy_model:return PartnerCommandResult(f"✅ Already using {selected_label}.", {"_feishu_model_switch_success": True})previous_label = (- legacy_model- if legacy_model- else f"{current['provider_label']} · {current['model_name']}"- if current- else "default"+ legacy_model if legacy_model else option_label(current) if current else "default")old_selection = getattr(self.config, "llm_selection", None)old_legacy_model = getattr(self.config, "model", None)diff --git a/deeptutor/services/partners/runtime.py b/deeptutor/services/partners/runtime.pyindex 8e5f48514..cba000723 100644--- a/deeptutor/services/partners/runtime.py+++ b/deeptutor/services/partners/runtime.py@@ -116,7 +116,12 @@ def _thread_delivery_meta(msg: InboundMessage) -> dict[str, Any]:"""in_meta = msg.metadata or {}meta: dict[str, Any] = {}- for key in ("message_thread_id", "message_id", "_feishu_model_picker_message_id"):+ for key in (+ "message_thread_id",+ "message_id",+ "_feishu_model_picker_message_id",+ "_feishu_model_picker_id",+ ):value = in_meta.get(key)if value is not None:meta[key] = valuediff --git a/tests/services/partners/test_feishu_model_picker.py b/tests/services/partners/test_feishu_model_picker.pyindex 0687e5367..63425c723 100644--- a/tests/services/partners/test_feishu_model_picker.py+++ b/tests/services/partners/test_feishu_model_picker.py@@ -5,7 +5,7 @@ from __future__ import annotationsimport asyncioimport jsonfrom types import SimpleNamespace-from unittest.mock import MagicMock+from unittest.mock import AsyncMock, MagicMockimport pytest@@ -165,6 +165,16 @@ async def test_runner_carries_picker_result_to_feishu_delivery(monkeypatch, partassert "Link this chat" in deniedassert "_feishu_model_switch_success" not in callback_metadata+ callback = _message("/model profile m1", actor=SimpleNamespace(is_admin=True))+ callback.metadata.update(+ {"_feishu_model_picker_message_id": "om_picker", "_feishu_model_picker_id": "picker"}+ )+ await runner._handle_inbound(callback)+ outbound = await runner.bus.consume_outbound()+ assert outbound.metadata["_feishu_model_picker_message_id"] == "om_picker"+ assert outbound.metadata["_feishu_model_picker_id"] == "picker"+ assert outbound.metadata["_feishu_model_switch_success"] is True+@pytest.mark.asyncioasync def test_private_picker_pages_in_place_and_queues_selection() -> None:@@ -177,10 +187,22 @@ async def test_private_picker_pages_in_place_and_queues_selection() -> None:"profile_id": "profile","model_id": f"model-{index}","provider_label": "OpenAI",+ "profile_name": "Primary","model_name": f"Model {index}",+ "model": f"m{index}",}for index in range(8)+ ] + [+ {+ "profile_id": "second",+ "model_id": "model-b",+ "provider_label": "OpenAI",+ "profile_name": "Backup",+ "model_name": "Model 7",+ "model": "backup-wire",+ }]+ options[6]["model_name"] = "Model 7" # duplicate display name within one profileawait channel.send(OutboundMessage(channel="feishu",@@ -188,6 +210,10 @@ async def test_private_picker_pages_in_place_and_queues_selection() -> None:content="Available models",metadata={"_feishu_model_options": options,+ "_feishu_model_providers": [+ {"profile_id": "profile", "profile_name": "Primary"},+ {"profile_id": "second", "profile_name": "Backup"},+ ],"_feishu_model_current": {"profile_id": "profile", "model_id": "model-0"},},)@@ -196,34 +222,153 @@ async def test_private_picker_pages_in_place_and_queues_selection() -> None:assert send_args[:3] == ("open_id", "ou_owner", "interactive")first = json.loads(send_args[3])first_actions = [e for e in first["elements"] if e["tag"] == "action"]- assert len(first_actions) == 7 # six models and one page action+ assert len(first_actions) == 2 # one button per provider, with no model count+ assert first_actions[0]["actions"][0]["text"]["content"] == "✓ Primary"+ assert first_actions[1]["actions"][0]["text"]["content"] == "Backup"picker_id = first_actions[0]["actions"][0]["value"]["picker_id"]assert len(picker_id) == 16assert "model_id" not in first_actions[0]["actions"][0]["value"]+ provider_response = channel._on_card_action_sync(+ _callback({"picker_id": picker_id, "action": "pick_provider", "index": 0})+ )+ assert provider_response.card.type == "raw"+ provider_card = provider_response.card.data+ assert "Primary · Choose a model" in provider_card["elements"][0]["text"]["content"]+ assert len([e for e in provider_card["elements"] if e["tag"] == "action"]) == 7+page_response = channel._on_card_action_sync(- _callback({"picker_id": picker_id, "action": "page", "page": 1})+ _callback({"picker_id": picker_id, "action": "page", "provider_index": 0, "page": 1}))assert page_response.card.type == "raw"assert "Page 2 of 2" in page_response.card.data["elements"][0]["text"]["content"]assert len([e for e in page_response.card.data["elements"] if e["tag"] == "action"]) == 3+ assert "Model 7 (m6)" in page_response.card.data["elements"][1]["actions"][0]["text"]["content"]+ assert "Model 7 (m7)" in page_response.card.data["elements"][2]["actions"][0]["text"]["content"]assert channel.bus.inbound.empty()channel._send_message_sync.assert_called_once() # page callback sends no messagewrong_user = channel._on_card_action_sync(- _callback({"picker_id": picker_id, "action": "select", "index": 7}, sender="ou_other")+ _callback(+ {"picker_id": picker_id, "action": "select", "provider_index": 0, "index": 7},+ sender="ou_other",+ ))assert wrong_user.toast.type == "error"assert channel.bus.inbound.empty()switching = channel._on_card_action_sync(- _callback({"picker_id": picker_id, "action": "select", "index": 7})+ _callback({"picker_id": picker_id, "action": "select", "provider_index": 0, "index": 7}))assert "⏳ Switching model" in switching.card.data["elements"][0]["text"]["content"]inbound = await asyncio.wait_for(channel.bus.consume_inbound(), timeout=1)- assert inbound.content == "/model profile model-7"+ assert inbound.content == "/model profile m7"assert inbound.chat_id == "ou_owner" # callback context has oc_, send target is ou_assert inbound.metadata["_feishu_model_picker_message_id"] == "om_picker"+ assert inbound.metadata["_feishu_model_picker_id"] == picker_id++ channel._client.im.v1.message.patch.return_value = SimpleNamespace(success=lambda: True)+ await channel.send(+ OutboundMessage(+ channel="feishu",+ chat_id="ou_owner",+ content="✅ Switched model: OpenAI · Model 0 → OpenAI · Model 7.",+ metadata={+ "_feishu_model_picker_message_id": "om_picker",+ "_feishu_model_picker_id": picker_id,+ "_feishu_model_switch_success": True,+ },+ )+ )+ patched = json.loads(channel._client.im.v1.message.patch.call_args.args[0].request_body.content)+ assert "✅ Switched model" in patched["elements"][0]["text"]["content"]+ assert "Page 2 of 2" in patched["elements"][1]["text"]["content"]+ assert channel._model_pickers[picker_id].pending is False+ assert channel._model_pickers[picker_id].current == {+ "profile_id": "profile",+ "model_id": "model-7",+ }++ back = channel._on_card_action_sync(_callback({"picker_id": picker_id, "action": "providers"}))+ assert back.card.data["elements"][0]["text"]["content"] == "Choose a provider"+ scoped = channel._on_card_action_sync(+ _callback({"picker_id": picker_id, "action": "pick_provider", "index": 1})+ )+ scoped_actions = [e for e in scoped.card.data["elements"] if e["tag"] == "action"]+ assert len(scoped_actions) == 2 # one model plus back button+ assert "Model 7" in scoped_actions[0]["actions"][0]["text"]["content"]+ second = channel._on_card_action_sync(+ _callback({"picker_id": picker_id, "action": "select", "provider_index": 1, "index": 8})+ )+ assert second.card.type == "raw" # the first switch released the guard+ second_inbound = await asyncio.wait_for(channel.bus.consume_inbound(), timeout=1)+ assert second_inbound.content == "/model second backup-wire"++ await channel.send(+ OutboundMessage(+ channel="feishu",+ chat_id="ou_owner",+ content="Could not switch model: catalog changed.",+ metadata={+ "_feishu_model_picker_message_id": "om_picker",+ "_feishu_model_picker_id": picker_id,+ },+ )+ )+ failed_card = json.loads(+ channel._client.im.v1.message.patch.call_args.args[0].request_body.content+ )+ assert "⚠️ Could not switch model" in failed_card["elements"][0]["text"]["content"]+ assert channel._model_pickers[picker_id].pending is False+ assert channel._model_pickers[picker_id].current["profile_id"] == "profile"+ retry = channel._on_card_action_sync(+ _callback({"picker_id": picker_id, "action": "select", "provider_index": 1, "index": 8})+ )+ assert retry.card.type == "raw"+ assert (await asyncio.wait_for(channel.bus.consume_inbound(), timeout=1)).content == (+ "/model second backup-wire"+ )+++async def test_picker_releases_guard_if_callback_cannot_queue_command() -> None:+ pytest.importorskip("lark_oapi")+ channel = _channel()+ channel._loop = asyncio.get_running_loop()+ channel._send_message_sync = MagicMock(return_value=True)+ channel._handle_message = AsyncMock(side_effect=RuntimeError("queue unavailable"))+ await channel.send(+ OutboundMessage(+ channel="feishu",+ chat_id="ou_owner",+ content="Available models",+ metadata={+ "_feishu_model_options": [+ {+ "profile_id": "profile",+ "model_id": "model-1",+ "model_name": "Model 1",+ "model": "m1",+ }+ ]+ },+ )+ )+ card = json.loads(channel._send_message_sync.call_args.args[3])+ picker_id = card["elements"][1]["actions"][0]["value"]["picker_id"]+ response = channel._on_card_action_sync(+ _callback({"picker_id": picker_id, "action": "select", "provider_index": 0, "index": 0})+ )+ assert response.card.type == "raw"++ async def guard_released() -> bool:+ for _ in range(20):+ if not channel._model_pickers[picker_id].pending:+ return True+ await asyncio.sleep(0.01)+ return False++ assert await guard_released()@pytest.mark.asynciodiff --git a/tests/services/partners/test_partner_model_commands.py b/tests/services/partners/test_partner_model_commands.pynew file mode 100644index 000000000..7bdaeab7d--- /dev/null+++ b/tests/services/partners/test_partner_model_commands.py@@ -0,0 +1,143 @@+"""Partner /model browse and selection use only visible catalog options."""++from __future__ import annotations++from contextlib import nullcontext+from types import SimpleNamespace+from unittest.mock import MagicMock++from deeptutor.partners.bus.events import InboundMessage+from deeptutor.services.partners import commands as commands_mod+from deeptutor.services.partners.commands import PartnerCommandHandler+from deeptutor.services.partners.manager import PartnerConfig+++def _catalog() -> dict:+ return {+ "services": {+ "llm": {+ "active_profile_id": "alpha",+ "active_model_id": "alpha-one",+ "profiles": [+ {+ "id": "alpha",+ "name": "Alpha account",+ "binding": "openai",+ "models": [+ {"id": "alpha-one", "name": "Shared", "model": "alpha/one"},+ {"id": "alpha-two", "name": "Shared", "model": "alpha/two"},+ ],+ },+ {+ "id": "beta",+ "name": "Beta account",+ "binding": "openai",+ "models": [+ {"id": "beta-one", "name": "Distinct", "model": "beta/one"},+ ],+ },+ ],+ }+ }+ }+++def _message(content: str, *, actor=None, chat_type: str = "p2p") -> InboundMessage:+ return InboundMessage(+ channel="feishu",+ sender_id="owner",+ chat_id="owner" if chat_type == "p2p" else "group",+ content=content,+ metadata={"chat_type": chat_type},+ actor=actor,+ )+++def _handler(monkeypatch, *, config: PartnerConfig | None = None, save=None):+ service = SimpleNamespace(load=MagicMock(return_value=_catalog()), refresh_models=MagicMock())+ monkeypatch.setattr(commands_mod, "get_model_catalog_service", lambda: service)+ monkeypatch.setattr(commands_mod, "can_manage_partner", lambda _partner_id, _actor: True)+ handler = PartnerCommandHandler(+ partner_id="ada",+ config=config or PartnerConfig(name="Ada"),+ store=MagicMock(),+ save_config=save,+ )+ return handler, service+++def test_model_browse_groups_visible_profiles_without_live_refresh(monkeypatch) -> None:+ handler, service = _handler(monkeypatch)+ actor = SimpleNamespace(is_admin=False)+ monkeypatch.setattr(commands_mod, "user_context", lambda _actor: nullcontext())+ monkeypatch.setattr(+ commands_mod,+ "allowed_llm_options",+ lambda: {"options": [{"profile_id": "alpha", "model_id": "alpha-two"}]},+ )++ result = handler.dispatch(_message("/model", actor=actor))++ assert result is not None and result.metadata is not None+ assert [+ (row["profile_id"], row["model_id"]) for row in result.metadata["_feishu_model_options"]+ ] == [("alpha", "alpha-two")]+ assert result.metadata["_feishu_model_providers"] == [+ {+ "profile_id": "alpha",+ "provider_label": "OpenAI",+ "profile_name": "Alpha account",+ }+ ]+ assert "Beta account" not in result.content+ service.load.assert_called_once_with()+ service.refresh_models.assert_not_called()++ group = handler.dispatch(_message("/model", actor=actor, chat_type="group"))+ assert group is not None and group.metadata is None+ unlinked = handler.dispatch(_message("/model"))+ assert unlinked is not None and unlinked.metadata is None+++def test_model_browse_keeps_same_provider_profiles_distinct(monkeypatch) -> None:+ handler, _service = _handler(monkeypatch)++ result = handler.dispatch(_message("/model", actor=SimpleNamespace(is_admin=True)))++ assert result is not None and result.metadata is not None+ assert result.metadata["_feishu_model_providers"] == [+ {"profile_id": "alpha", "provider_label": "OpenAI", "profile_name": "Alpha account"},+ {"profile_id": "beta", "provider_label": "OpenAI", "profile_name": "Beta account"},+ ]+ assert "1. OpenAI · Shared (alpha/one) (current)" in result.content+ assert "2. OpenAI · Shared (alpha/two)" in result.content+++def test_model_switch_prefers_wire_value_and_accepts_model_id(monkeypatch) -> None:+ saved: list[dict[str, str]] = []+ config = PartnerConfig(name="Ada")+ handler, _service = _handler(+ monkeypatch,+ config=config,+ save=lambda _partner_id, value: saved.append(value.llm_selection.copy()),+ )+ actor = SimpleNamespace(is_admin=True)++ ambiguous = handler.dispatch(_message("/model Shared", actor=actor))+ assert ambiguous is not None and "wire model name" in ambiguous.content+ assert saved == []++ selected = handler.dispatch(_message("/model alpha alpha/two", actor=actor))+ assert selected is not None and selected.metadata == {"_feishu_model_switch_success": True}+ assert "OpenAI · Shared (alpha/two)" in selected.content+ assert config.llm_selection == {"profile_id": "alpha", "model_id": "alpha-two"}++ selected_by_id = handler.dispatch(_message("/model alpha alpha-one", actor=actor))+ assert selected_by_id is not None and selected_by_id.metadata == {+ "_feishu_model_switch_success": True+ }+ assert config.llm_selection == {"profile_id": "alpha", "model_id": "alpha-one"}+ assert saved == [+ {"profile_id": "alpha", "model_id": "alpha-two"},+ {"profile_id": "alpha", "model_id": "alpha-one"},+ ]