DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(feishu): keep model picker selectable and avoid callback deadlock
Bingxi Zhao (Frank)8b0ae3891f24
diff --git a/deeptutor/partners/channels/feishu.py b/deeptutor/partners/channels/feishu.pyindex 60452f31a..725d1006f 100644--- a/deeptutor/partners/channels/feishu.py+++ b/deeptutor/partners/channels/feishu.py@@ -1669,7 +1669,7 @@ class FeishuChannel(BaseChannel):command = ("/model "f"{shlex.quote(str(option['profile_id']))} "- f"{shlex.quote(str(option.get('model') or option['model_id']))}"+ f"{shlex.quote(str(option['model_id']))}")await self._handle_message(sender_id=sender_id,@@ -1800,8 +1800,11 @@ class FeishuChannel(BaseChannel):live.pending = Falselive.pending_index = None- queued.add_done_callback(release_failed_queue)- return card_response(pending_card)+ # A completed future runs its callback immediately in this thread.+ # Register it after releasing the picker lock so a fast queue failure+ # can clear the pending state without deadlocking the card callback.+ queued.add_done_callback(release_failed_queue)+ return card_response(pending_card)async def send(self, msg: OutboundMessage) -> None:"""Send a message through Feishu, including media (images/files) if present."""diff --git a/deeptutor/services/partners/commands.py b/deeptutor/services/partners/commands.pyindex 07ee07304..221635209 100644--- a/deeptutor/services/partners/commands.py+++ b/deeptutor/services/partners/commands.py@@ -339,15 +339,23 @@ class PartnerCommandHandler:choice = options[index]elif len(args) == 2: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:+ if msg.channel == "feishu" and (msg.metadata or {}).get("_feishu_model_picker_id"):+ # The callback selected a server-owned option by its stable ID.+ # Recheck that ID against today's visible catalog, since wire+ # names can occur more than once within one profile.choice = next((row for row in profile_options if row["model_id"] == args[1]), None)+ else:+ 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 = [diff --git a/tests/services/partners/test_feishu_model_picker.py b/tests/services/partners/test_feishu_model_picker.pyindex 63425c723..240b95ce0 100644--- a/tests/services/partners/test_feishu_model_picker.py+++ b/tests/services/partners/test_feishu_model_picker.py@@ -3,7 +3,9 @@from __future__ import annotationsimport asyncio+from concurrent.futures import Futureimport json+import threadingfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock@@ -165,7 +167,7 @@ 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 = _message("/model profile model-1", actor=SimpleNamespace(is_admin=True))callback.metadata.update({"_feishu_model_picker_message_id": "om_picker", "_feishu_model_picker_id": "picker"})@@ -262,7 +264,7 @@ async def test_private_picker_pages_in_place_and_queues_selection() -> None:)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 m7"+ assert inbound.content == "/model profile model-7"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@@ -302,7 +304,7 @@ async def test_private_picker_pages_in_place_and_queues_selection() -> None:)assert second.card.type == "raw" # the first switch released the guardsecond_inbound = await asyncio.wait_for(channel.bus.consume_inbound(), timeout=1)- assert second_inbound.content == "/model second backup-wire"+ assert second_inbound.content == "/model second model-b"await channel.send(OutboundMessage(@@ -326,7 +328,7 @@ async def test_private_picker_pages_in_place_and_queues_selection() -> None:)assert retry.card.type == "raw"assert (await asyncio.wait_for(channel.bus.consume_inbound(), timeout=1)).content == (- "/model second backup-wire"+ "/model second model-b")@@ -371,6 +373,57 @@ async def test_picker_releases_guard_if_callback_cannot_queue_command() -> None:assert await guard_released()+async def test_picker_releases_guard_when_queue_future_already_failed(monkeypatch) -> None:+ pytest.importorskip("lark_oapi")+ channel = _channel()+ channel._loop = asyncio.get_running_loop()+ channel._send_message_sync = MagicMock(return_value=True)+ 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": "wire-name",+ }+ ]+ },+ )+ )+ card = json.loads(channel._send_message_sync.call_args.args[3])+ picker_id = card["elements"][1]["actions"][0]["value"]["picker_id"]++ def already_failed(coro, _loop):+ coro.close()+ future = Future()+ future.set_exception(RuntimeError("queue failed"))+ return future++ monkeypatch.setattr(asyncio, "run_coroutine_threadsafe", already_failed)+ responses = []+ worker = threading.Thread(+ target=lambda: responses.append(+ channel._on_card_action_sync(+ _callback(+ {"picker_id": picker_id, "action": "select", "provider_index": 0, "index": 0}+ )+ )+ ),+ daemon=True,+ )+ worker.start()+ worker.join(timeout=1)+ assert not worker.is_alive(), "a completed queue future must not deadlock the callback"+ assert responses[0].card.type == "raw"+ assert channel._model_pickers[picker_id].pending is False++@pytest.mark.asyncioasync def test_model_switch_patches_clicked_card_then_uses_text_fallback_on_failure() -> None:pytest.importorskip("lark_oapi")diff --git a/tests/services/partners/test_partner_model_commands.py b/tests/services/partners/test_partner_model_commands.pyindex 7bdaeab7d..ee8ef1295 100644--- a/tests/services/partners/test_partner_model_commands.py+++ b/tests/services/partners/test_partner_model_commands.py@@ -141,3 +141,21 @@ def test_model_switch_prefers_wire_value_and_accepts_model_id(monkeypatch) -> No{"profile_id": "alpha", "model_id": "alpha-two"},{"profile_id": "alpha", "model_id": "alpha-one"},]+++def test_picker_can_select_model_id_when_profile_has_duplicate_wire_names(monkeypatch) -> None:+ config = PartnerConfig(name="Ada")+ handler, service = _handler(monkeypatch, config=config)+ catalog = service.load.return_value+ catalog["services"]["llm"]["profiles"][0]["models"][1]["model"] = "alpha/one"+ actor = SimpleNamespace(is_admin=True)++ typed = handler.dispatch(_message("/model alpha alpha/one", actor=actor))+ assert typed is not None and "ambiguous" in typed.content++ picker_message = _message("/model alpha alpha-two", actor=actor)+ picker_message.metadata["_feishu_model_picker_id"] = "server-owned-picker"+ selected = handler.dispatch(picker_message)++ assert selected is not None and selected.metadata == {"_feishu_model_switch_success": True}+ assert config.llm_selection == {"profile_id": "alpha", "model_id": "alpha-two"}