Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(feishu): deliver threaded replies and private model picker (#1517)

Bingxi Zhao (Frank)f14e8e065d0e
diff --git a/deeptutor/partners/channels/base.py b/deeptutor/partners/channels/base.py
index 8825949c3..4566aee66 100644
--- a/deeptutor/partners/channels/base.py
+++ b/deeptutor/partners/channels/base.py
@@ -259,3 +259,18 @@ class BaseChannel(ABC):
def is_running(self) -> bool:
"""Check if the channel is running."""
return self._running
+
+
+async def deliver_outbound(channel: BaseChannel, msg: OutboundMessage) -> None:
+ """Apply the shared stream/final delivery contract at either partner router."""
+ metadata = msg.metadata or {}
+ if metadata.get("_stream_delta") or metadata.get("_stream_end"):
+ await channel.send_delta(msg.chat_id, msg.content, metadata)
+ elif metadata.get("_streamed"):
+ # A channel can confirm that its streamed final actually reached the
+ # user. If it could not, give the ordinary final its own send attempt.
+ consume = getattr(channel, "consume_stream_delivery", None)
+ if callable(consume) and not consume(metadata):
+ await channel.send(msg)
+ else:
+ await channel.send(msg)
diff --git a/deeptutor/partners/channels/feishu.py b/deeptutor/partners/channels/feishu.py
index 4edc3931b..f7d06972c 100644
--- a/deeptutor/partners/channels/feishu.py
+++ b/deeptutor/partners/channels/feishu.py
@@ -7,7 +7,9 @@ import importlib.util
import json
import os
import re
+import shlex
import threading
+from threading import Lock
import time
from typing import Any, Literal
import uuid
@@ -261,6 +263,18 @@ class _FeishuStreamBuf:
sequence: int = 0
last_edit: float = 0.0
stream_id: str | None = None
+ reply_to_message_id: str | None = None
+
+
+@dataclass
+class _ModelPicker:
+ """Server-owned model choices; card button values contain only an index."""
+
+ sender_id: str
+ options: list[dict[str, Any]]
+ current: dict[str, str]
+ created_at: float
+ pending: bool = False
class FeishuChannel(BaseChannel):
@@ -279,6 +293,14 @@ class FeishuChannel(BaseChannel):
display_name = "Feishu"
_STREAM_EDIT_INTERVAL = 0.5 # throttle between CardKit streaming updates
+ _MAX_CONFIRMED_STREAMS = 1000
+ _WORKING_REACTION_TTL = 60 * 60
+ _MAX_WORKING_REACTIONS = 1000
+ _REACTION_DELETE_RETRY_DELAYS = (0.15, 0.5)
+ _REACTION_LATE_RETRY_DELAYS = (0, 5, 30, 120)
+ _MODEL_PAGE_SIZE = 6
+ _MODEL_PICKER_TTL = 60 * 60
+ _MAX_MODEL_PICKERS = 100
@classmethod
def default_config(cls) -> dict[str, Any]:
@@ -294,6 +316,11 @@ class FeishuChannel(BaseChannel):
self._ws_thread: threading.Thread | None = None
self._processed_message_ids: OrderedDict[str, None] = OrderedDict() # Ordered dedup cache
self._stream_bufs: dict[str, _FeishuStreamBuf] = {}
+ self._confirmed_streams: OrderedDict[str, None] = OrderedDict()
+ self._working_reactions: OrderedDict[str, tuple[str, float]] = OrderedDict()
+ self._reaction_cleanup_tasks: dict[tuple[str, str], asyncio.Task[None]] = {}
+ self._model_pickers: OrderedDict[str, _ModelPicker] = OrderedDict()
+ self._model_picker_lock = Lock()
self._loop: asyncio.AbstractEventLoop | None = None
@staticmethod
@@ -302,6 +329,20 @@ class FeishuChannel(BaseChannel):
meta = metadata or {}
return str(meta.get("_stream_id") or chat_id)
+ def _confirm_stream_delivery(self, stream_key: str) -> None:
+ self._confirmed_streams[stream_key] = None
+ self._confirmed_streams.move_to_end(stream_key)
+ while len(self._confirmed_streams) > self._MAX_CONFIRMED_STREAMS:
+ self._confirmed_streams.popitem(last=False)
+
+ def consume_stream_delivery(self, metadata: dict[str, Any]) -> bool:
+ """Confirm the final card reached Feishu before suppressing plain text."""
+ stream_id = str(metadata.get("_stream_id") or "")
+ if stream_id and stream_id in self._confirmed_streams:
+ self._confirmed_streams.pop(stream_id)
+ return True
+ return False
+
@staticmethod
def _register_optional_event(builder: Any, method_name: str, handler: Any) -> Any:
"""Register an event handler only when the SDK supports it."""
@@ -360,6 +401,9 @@ class FeishuChannel(BaseChannel):
"register_p2_im_chat_access_event_bot_p2p_chat_entered_v1",
self._on_bot_p2p_chat_entered,
)
+ builder = self._register_optional_event(
+ builder, "register_p2_card_action_trigger", self._on_card_action_sync
+ )
event_handler = builder.build()
# Create WebSocket client for long connection
@@ -424,6 +468,16 @@ class FeishuChannel(BaseChannel):
Reference: https://github.com/larksuite/oapi-sdk-python/blob/v2_main/lark_oapi/ws/client.py#L86
"""
self._running = False
+ self._confirmed_streams.clear()
+ cleanup_tasks = list(self._reaction_cleanup_tasks.values())
+ for task in cleanup_tasks:
+ task.cancel()
+ if cleanup_tasks:
+ await asyncio.gather(*cleanup_tasks, return_exceptions=True)
+ self._reaction_cleanup_tasks.clear()
+ self._working_reactions.clear()
+ with self._model_picker_lock:
+ self._model_pickers.clear()
logger.info("Feishu bot stopped")
def _is_bot_mentioned(self, message: Any) -> bool:
@@ -449,7 +503,7 @@ class FeishuChannel(BaseChannel):
return True
return self._is_bot_mentioned(message)
- def _add_reaction_sync(self, message_id: str, emoji_type: str) -> None:
+ def _add_reaction_sync(self, message_id: str, emoji_type: str) -> str | None:
"""Sync helper for adding reaction (runs in thread pool)."""
from lark_oapi.api.im.v1 import (
CreateMessageReactionRequest,
@@ -477,8 +531,86 @@ class FeishuChannel(BaseChannel):
)
else:
logger.debug("Added {} reaction to message {}", emoji_type, message_id)
+ reaction_id = getattr(getattr(response, "data", None), "reaction_id", None)
+ return reaction_id if isinstance(reaction_id, str) and reaction_id else None
except Exception as e:
logger.warning("Error adding reaction: {}", e)
+ return None
+
+ def _prune_working_reactions(self) -> list[tuple[str, tuple[str, float]]]:
+ """Bound receipts for turns that never produce a deliverable answer."""
+ now = time.monotonic()
+ expired: list[tuple[str, tuple[str, float]]] = []
+ while self._working_reactions:
+ _, (_, created_at) = next(iter(self._working_reactions.items()))
+ if (
+ len(self._working_reactions) <= self._MAX_WORKING_REACTIONS
+ and now - created_at < self._WORKING_REACTION_TTL
+ ):
+ break
+ expired.append(self._working_reactions.popitem(last=False))
+ return expired
+
+ def _remove_reaction_sync(self, message_id: str, reaction_id: str) -> bool:
+ from lark_oapi.api.im.v1 import DeleteMessageReactionRequest
+
+ try:
+ request = (
+ DeleteMessageReactionRequest.builder()
+ .message_id(message_id)
+ .reaction_id(reaction_id)
+ .build()
+ )
+ response = self._client.im.v1.message_reaction.delete(request)
+ if response.success():
+ return True
+ logger.warning(
+ "Failed to remove Feishu working reaction: code={}, msg={}",
+ response.code,
+ response.msg,
+ )
+ except Exception as e:
+ logger.warning("Error removing Feishu working reaction: {}", e)
+ return False
+
+ async def _delete_reaction(self, message_id: str, reaction_id: str) -> bool:
+ loop = asyncio.get_running_loop()
+ return await loop.run_in_executor(None, self._remove_reaction_sync, message_id, reaction_id)
+
+ def _schedule_reaction_cleanup(self, message_id: str, receipt: tuple[str, float]) -> None:
+ key = (message_id, receipt[0])
+ if key in self._reaction_cleanup_tasks:
+ return
+
+ async def retry() -> None:
+ try:
+ for delay in self._REACTION_LATE_RETRY_DELAYS:
+ if delay:
+ await asyncio.sleep(delay)
+ if not self._client:
+ return
+ if await self._delete_reaction(*key):
+ if self._working_reactions.get(message_id) == receipt:
+ self._working_reactions.pop(message_id, None)
+ return
+ finally:
+ self._reaction_cleanup_tasks.pop(key, None)
+
+ self._reaction_cleanup_tasks[key] = asyncio.create_task(retry())
+
+ async def _finish_reaction(self, message_id: str) -> None:
+ receipt = self._working_reactions.get(message_id)
+ if not receipt or not self._client:
+ return
+ reaction_id, _ = receipt
+ for delay in (0, *self._REACTION_DELETE_RETRY_DELAYS):
+ if delay:
+ await asyncio.sleep(delay)
+ if await self._delete_reaction(message_id, reaction_id):
+ if self._working_reactions.get(message_id) == receipt:
+ self._working_reactions.pop(message_id, None)
+ return
+ self._schedule_reaction_cleanup(message_id, receipt)
async def _add_reaction(self, message_id: str, emoji_type: str = "THUMBSUP") -> None:
"""
@@ -490,7 +622,13 @@ class FeishuChannel(BaseChannel):
return
loop = asyncio.get_running_loop()
- await loop.run_in_executor(None, self._add_reaction_sync, message_id, emoji_type)
+ reaction_id = await loop.run_in_executor(
+ None, self._add_reaction_sync, message_id, emoji_type
+ )
+ if reaction_id:
+ self._working_reactions[message_id] = (reaction_id, time.monotonic())
+ for old_message_id, old_receipt in self._prune_working_reactions():
+ self._schedule_reaction_cleanup(old_message_id, old_receipt)
# Regex to match markdown tables (header + separator + data rows)
_TABLE_RE = re.compile(
@@ -909,12 +1047,56 @@ class FeishuChannel(BaseChannel):
return None, f"[{msg_type}: download failed]"
def _send_message_sync(
- self, receive_id_type: str, receive_id: str, msg_type: str, content: str
+ self,
+ receive_id_type: str,
+ receive_id: str,
+ msg_type: str,
+ content: str,
+ reply_to_message_id: str | None = None,
) -> bool:
- """Send a single message (text/image/file/interactive) synchronously."""
- from lark_oapi.api.im.v1 import CreateMessageRequest, CreateMessageRequestBody
+ """Send a message as a real Feishu reply when its source is known."""
+ from lark_oapi.api.im.v1 import (
+ CreateMessageRequest,
+ CreateMessageRequestBody,
+ ReplyMessageRequest,
+ ReplyMessageRequestBody,
+ )
try:
+ if reply_to_message_id:
+ request = (
+ ReplyMessageRequest.builder()
+ .message_id(reply_to_message_id)
+ .request_body(
+ ReplyMessageRequestBody.builder()
+ .msg_type(msg_type)
+ .content(content)
+ .reply_in_thread(True)
+ .build()
+ )
+ .build()
+ )
+ response = self._client.im.v1.message.reply(request)
+ if response.success():
+ logger.debug(
+ "Feishu {} reply sent to {} (message_id={})",
+ msg_type,
+ receive_id,
+ reply_to_message_id,
+ )
+ return True
+ # A rejected reply may be an expired source message or an
+ # unsupported type in a thread. Preserve the answer via the
+ # original create path; a transport exception is different,
+ # because its send outcome is unknown and a fallback may duplicate.
+ logger.warning(
+ "Feishu {} reply rejected (message_id={}, code={}, msg={}); "
+ "falling back to a standalone message",
+ msg_type,
+ reply_to_message_id,
+ response.code,
+ response.msg,
+ )
request = (
CreateMessageRequest.builder()
.receive_id_type(receive_id_type)
@@ -945,7 +1127,9 @@ class FeishuChannel(BaseChannel):
# ── CardKit streaming (send_delta) ───────────────────────────────
- def _create_streaming_card_sync(self, receive_id_type: str, chat_id: str) -> str | None:
+ def _create_streaming_card_sync(
+ self, receive_id_type: str, chat_id: str, reply_to_message_id: str | None = None
+ ) -> str | None:
"""Create a CardKit streaming card, send it to chat, return card_id."""
from lark_oapi.api.cardkit.v1 import CreateCardRequest, CreateCardRequestBody
@@ -980,7 +1164,9 @@ class FeishuChannel(BaseChannel):
card_content = json.dumps(
{"type": "card", "data": {"card_id": card_id}}, ensure_ascii=False
)
- if self._send_message_sync(receive_id_type, chat_id, "interactive", card_content):
+ if self._send_message_sync(
+ receive_id_type, chat_id, "interactive", card_content, reply_to_message_id
+ ):
return card_id
logger.warning(
"Created Feishu streaming card {} but failed to send it to {}",
@@ -1080,11 +1266,13 @@ class FeishuChannel(BaseChannel):
stream_key = self._stream_key(chat_id, meta)
loop = asyncio.get_running_loop()
rid_type = "chat_id" if chat_id.startswith("oc_") else "open_id"
+ inbound_message_id = str(meta.get("message_id") or "").strip() or None
if meta.get("_stream_end"):
buf = self._stream_bufs.pop(stream_key, None)
- if not buf or not buf.text:
+ if not buf or not buf.text.strip():
return
+ reply_to_message_id = buf.reply_to_message_id or inbound_message_id
if buf.card_id:
buf.sequence += 1
ok = await loop.run_in_executor(
@@ -1096,30 +1284,56 @@ class FeishuChannel(BaseChannel):
)
if ok:
buf.sequence += 1
- await loop.run_in_executor(
+ closed = await loop.run_in_executor(
None,
self._close_streaming_mode_sync,
buf.card_id,
buf.sequence,
)
+ if not closed:
+ # The final content update already succeeded. A new
+ # card here would duplicate an answer the user can see.
+ logger.warning(
+ "Feishu streaming card {} displayed its final text but could not close",
+ buf.card_id,
+ )
+ if meta.get("_stream_final"):
+ self._confirm_stream_delivery(stream_key)
+ if reply_to_message_id:
+ await self._finish_reaction(reply_to_message_id)
return
logger.warning(
"Feishu streaming card {} final update failed, falling back to regular card",
buf.card_id,
)
+ delivered = True
for chunk in self._split_elements_by_table_limit(self._build_card_elements(buf.text)):
card = json.dumps(
{"config": {"wide_screen_mode": True}, "elements": chunk},
ensure_ascii=False,
)
- await loop.run_in_executor(
- None, self._send_message_sync, rid_type, chat_id, "interactive", card
+ sent = await loop.run_in_executor(
+ None,
+ self._send_message_sync,
+ rid_type,
+ chat_id,
+ "interactive",
+ card,
+ reply_to_message_id,
)
+ delivered = delivered and sent
+ if delivered and meta.get("_stream_final"):
+ self._confirm_stream_delivery(stream_key)
+ if reply_to_message_id:
+ await self._finish_reaction(reply_to_message_id)
return
buf = self._stream_bufs.get(stream_key)
if buf is None:
- buf = _FeishuStreamBuf(stream_id=meta.get("_stream_id"))
+ buf = _FeishuStreamBuf(
+ stream_id=meta.get("_stream_id"),
+ reply_to_message_id=inbound_message_id,
+ )
self._stream_bufs[stream_key] = buf
buf.text += delta
if not buf.text.strip():
@@ -1128,7 +1342,11 @@ class FeishuChannel(BaseChannel):
now = time.monotonic()
if buf.card_id is None:
card_id = await loop.run_in_executor(
- None, self._create_streaming_card_sync, rid_type, chat_id
+ None,
+ self._create_streaming_card_sync,
+ rid_type,
+ chat_id,
+ buf.reply_to_message_id,
)
if card_id:
buf.card_id = card_id
@@ -1144,6 +1362,212 @@ class FeishuChannel(BaseChannel):
)
buf.last_edit = now
+ def _prune_model_pickers(self) -> None:
+ """Called while the picker lock is held."""
+ now = time.monotonic()
+ for picker_id, picker in list(self._model_pickers.items()):
+ if now - picker.created_at >= self._MODEL_PICKER_TTL:
+ del self._model_pickers[picker_id]
+ while len(self._model_pickers) > self._MAX_MODEL_PICKERS:
+ self._model_pickers.popitem(last=False)
+
+ @staticmethod
+ def _model_label(option: dict[str, Any]) -> str:
+ provider = str(option.get("provider_label") or option.get("profile_name") or "LLM")
+ 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]:
+ total_pages = max(
+ 1, (len(picker.options) + 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]] = [
+ {
+ "tag": "div",
+ "text": {
+ "tag": "plain_text",
+ "content": f"Choose a model · Page {page + 1} of {total_pages}",
+ },
+ }
+ ]
+ for index in range(start, min(start + self._MODEL_PAGE_SIZE, len(picker.options))):
+ 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)}"
+ elements.append(
+ {
+ "tag": "action",
+ "actions": [
+ {
+ "tag": "button",
+ "text": {"tag": "plain_text", "content": label[:90]},
+ "type": "primary" if current else "default",
+ "value": {"picker_id": picker_id, "action": "select", "index": index},
+ }
+ ],
+ }
+ )
+ navigation = []
+ for label, target in (("◀ Previous", page - 1), ("Next ▶", page + 1)):
+ if 0 <= target < total_pages:
+ navigation.append(
+ {
+ "tag": "button",
+ "text": {"tag": "plain_text", "content": label},
+ "type": "default",
+ "value": {"picker_id": picker_id, "action": "page", "page": target},
+ }
+ )
+ if navigation:
+ elements.append({"tag": "action", "actions": navigation})
+ return {
+ "config": {"wide_screen_mode": True},
+ "header": {"title": {"tag": "plain_text", "content": "Switch model"}},
+ "elements": elements,
+ }
+
+ @staticmethod
+ def _model_status_card(content: str) -> dict[str, Any]:
+ return {
+ "config": {"wide_screen_mode": True},
+ "header": {"title": {"tag": "plain_text", "content": "Switch model"}},
+ "elements": [{"tag": "div", "text": {"tag": "plain_text", "content": content}}],
+ }
+
+ def _patch_model_card_sync(self, message_id: str, content: str) -> bool:
+ """Replace the clicked card after the command finishes."""
+ from lark_oapi.api.im.v1 import PatchMessageRequest, PatchMessageRequestBody
+
+ try:
+ request = (
+ PatchMessageRequest.builder()
+ .message_id(message_id)
+ .request_body(
+ PatchMessageRequestBody.builder()
+ .content(json.dumps(self._model_status_card(content), ensure_ascii=False))
+ .build()
+ )
+ .build()
+ )
+ response = self._client.im.v1.message.patch(request)
+ if response.success():
+ return True
+ logger.warning(
+ "Failed to patch Feishu model picker {}: code={}, msg={}",
+ message_id,
+ response.code,
+ response.msg,
+ )
+ except Exception as exc:
+ logger.warning("Error patching Feishu model picker {}: {}", message_id, exc)
+ return False
+
+ async def _queue_model_choice(
+ self, *, sender_id: str, message_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']))}"
+ )
+ await self._handle_message(
+ sender_id=sender_id,
+ chat_id=sender_id,
+ content=command,
+ metadata={
+ "chat_type": "p2p",
+ "_feishu_model_picker_message_id": message_id,
+ },
+ )
+
+ def _on_card_action_sync(self, data: Any) -> Any:
+ """Return page/status cards within Feishu's callback deadline."""
+ from lark_oapi.event.callback.model.p2_card_action_trigger import (
+ CallBackCard,
+ CallBackToast,
+ P2CardActionTriggerResponse,
+ )
+
+ def card_response(card: dict[str, Any]) -> Any:
+ response = P2CardActionTriggerResponse()
+ response.card = CallBackCard()
+ response.card.type = "raw"
+ response.card.data = card
+ return response
+
+ def error_response(message: str) -> Any:
+ response = P2CardActionTriggerResponse()
+ response.toast = CallBackToast()
+ response.toast.type = "error"
+ response.toast.content = message
+ return response
+
+ event = getattr(data, "event", None)
+ value = getattr(getattr(event, "action", None), "value", None)
+ operator = getattr(event, "operator", None)
+ context = getattr(event, "context", None)
+ if not isinstance(value, dict):
+ return error_response("Invalid model picker action.")
+ picker_id = value.get("picker_id")
+ sender_id = str(getattr(operator, "open_id", "") or "")
+ message_id = str(getattr(context, "open_message_id", "") or "")
+ if not isinstance(picker_id, str) or not sender_id or not message_id:
+ return error_response("Invalid model picker action.")
+ with self._model_picker_lock:
+ self._prune_model_pickers()
+ picker = self._model_pickers.get(picker_id)
+ if picker is None or picker.sender_id != sender_id or not self.is_allowed(sender_id):
+ return error_response("This model picker expired. Send /model again.")
+ if picker.pending:
+ return error_response("A model switch is already in progress.")
+ action = value.get("action")
+ if action == "page":
+ page = value.get("page")
+ if type(page) is not int or not 0 <= page * self._MODEL_PAGE_SIZE < len(
+ picker.options
+ ):
+ return error_response("Invalid model picker page.")
+ return card_response(self._model_picker_card(picker_id, picker, 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):
+ return error_response("Invalid model choice.")
+ loop = self._loop
+ if loop is None or not loop.is_running():
+ return error_response("The bot is reconnecting. Send /model again.")
+ option = picker.options[index]
+ current = next(
+ (
+ row
+ for row in picker.options
+ if row.get("profile_id") == picker.current.get("profile_id")
+ and row.get("model_id") == picker.current.get("model_id")
+ ),
+ None,
+ )
+ previous = self._model_label(current) if current else "default"
+ pending_card = self._model_status_card(
+ f"⏳ Switching model: {previous} → {self._model_label(option)}…"
+ )
+ picker.pending = True
+ try:
+ asyncio.run_coroutine_threadsafe(
+ self._queue_model_choice(
+ sender_id=sender_id, message_id=message_id, option=option
+ ),
+ loop,
+ )
+ except RuntimeError:
+ picker.pending = False
+ return error_response("The bot is reconnecting. Send /model again.")
+ return card_response(pending_card)
+
async def send(self, msg: OutboundMessage) -> None:
"""Send a message through Feishu, including media (images/files) if present."""
if not self._client:
@@ -1153,23 +1577,92 @@ class FeishuChannel(BaseChannel):
try:
receive_id_type = "chat_id" if msg.chat_id.startswith("oc_") else "open_id"
loop = asyncio.get_running_loop()
+ metadata = msg.metadata or {}
+ origin_message_id = str(metadata.get("message_id") or "").strip() or None
+ reply_to_message_id = str(msg.reply_to or origin_message_id or "").strip() or None
+
+ picker_message_id = str(metadata.get("_feishu_model_picker_message_id") or "")
+ if picker_message_id:
+ completed = bool(metadata.get("_feishu_model_switch_success"))
+ content = msg.content if completed else f"⚠️ {msg.content}"
+ patched = await loop.run_in_executor(
+ None, self._patch_model_card_sync, picker_message_id, content
+ )
+ if not patched:
+ await loop.run_in_executor(
+ None,
+ self._send_message_sync,
+ "open_id",
+ msg.chat_id,
+ "text",
+ json.dumps({"text": content}, ensure_ascii=False),
+ )
+ return
+
+ picker_options = metadata.get("_feishu_model_options")
+ if (
+ isinstance(picker_options, list)
+ and picker_options
+ and msg.chat_id.startswith("ou_")
+ ):
+ picker_id = uuid.uuid4().hex[:16]
+ picker = _ModelPicker(
+ sender_id=msg.chat_id,
+ options=list(picker_options),
+ current=dict(metadata.get("_feishu_model_current") or {}),
+ created_at=time.monotonic(),
+ )
+ with self._model_picker_lock:
+ self._model_pickers[picker_id] = picker
+ self._prune_model_pickers()
+ sent = await loop.run_in_executor(
+ None,
+ self._send_message_sync,
+ "open_id",
+ msg.chat_id,
+ "interactive",
+ json.dumps(self._model_picker_card(picker_id, picker, 0), ensure_ascii=False),
+ reply_to_message_id,
+ )
+ if sent:
+ if origin_message_id:
+ await self._finish_reaction(origin_message_id)
+ return
+ with self._model_picker_lock:
+ self._model_pickers.pop(picker_id, None)
+
+ delivered = True
+ sent_any = False
+
+ async def send_payload(msg_type: str, content: str) -> None:
+ nonlocal delivered, sent_any
+ sent_any = True
+ sent = await loop.run_in_executor(
+ None,
+ self._send_message_sync,
+ receive_id_type,
+ msg.chat_id,
+ msg_type,
+ content,
+ reply_to_message_id,
+ )
+ delivered = delivered and sent
for file_path in msg.media:
if not os.path.isfile(file_path):
logger.warning("Media file not found: {}", file_path)
+ delivered = False
continue
ext = os.path.splitext(file_path)[1].lower()
if ext in self._IMAGE_EXTS:
key = await loop.run_in_executor(None, self._upload_image_sync, file_path)
if key:
- await loop.run_in_executor(
- None,
- self._send_message_sync,
- receive_id_type,
- msg.chat_id,
+ await send_payload(
"image",
json.dumps({"image_key": key}, ensure_ascii=False),
)
+ else:
+ delivered = False
else:
key = await loop.run_in_executor(None, self._upload_file_sync, file_path)
if key:
@@ -1179,14 +1672,12 @@ class FeishuChannel(BaseChannel):
media_type = "media"
else:
media_type = "file"
- await loop.run_in_executor(
- None,
- self._send_message_sync,
- receive_id_type,
- msg.chat_id,
+ await send_payload(
media_type,
json.dumps({"file_key": key}, ensure_ascii=False),
)
+ else:
+ delivered = False
if msg.content and msg.content.strip():
fmt = self._detect_msg_format(msg.content)
@@ -1194,41 +1685,26 @@ class FeishuChannel(BaseChannel):
if fmt == "text":
# Short plain text – send as simple text message
text_body = json.dumps({"text": msg.content.strip()}, ensure_ascii=False)
- await loop.run_in_executor(
- None,
- self._send_message_sync,
- receive_id_type,
- msg.chat_id,
- "text",
- text_body,
- )
+ await send_payload("text", text_body)
elif fmt == "post":
# Medium content with links – send as rich-text post
post_body = self._markdown_to_post(msg.content)
- await loop.run_in_executor(
- None,
- self._send_message_sync,
- receive_id_type,
- msg.chat_id,
- "post",
- post_body,
- )
+ await send_payload("post", post_body)
else:
# Complex / long content – send as interactive card
elements = self._build_card_elements(msg.content)
for chunk in self._split_elements_by_table_limit(elements):
card = {"config": {"wide_screen_mode": True}, "elements": chunk}
- await loop.run_in_executor(
- None,
- self._send_message_sync,
- receive_id_type,
- msg.chat_id,
+ await send_payload(
"interactive",
json.dumps(card, ensure_ascii=False),
)
+ if sent_any and delivered and origin_message_id and not metadata.get("_progress"):
+ await self._finish_reaction(origin_message_id)
+
except Exception as e:
logger.error("Error sending Feishu message: {}", e)
@@ -1269,9 +1745,8 @@ class FeishuChannel(BaseChannel):
if chat_type == "group" and not self._is_group_message_for_bot(message):
logger.debug("Feishu: skipping group message (not mentioned)")
return
-
- # Add reaction
- await self._add_reaction(message_id, self.config.react_emoji)
+ if not self.is_allowed(sender_id):
+ return
# Parse content
content_parts = []
@@ -1335,6 +1810,10 @@ class FeishuChannel(BaseChannel):
if not content and not media_paths:
return
+ # Only acknowledge a message that can reach the partner runner;
+ # unsupported empty events have no final reply to clear the badge.
+ await self._add_reaction(message_id, self.config.react_emoji)
+
# Forward to message bus
reply_to = chat_id if chat_type == "group" else sender_id
await self._handle_message(
diff --git a/deeptutor/partners/channels/manager.py b/deeptutor/partners/channels/manager.py
index 5b9fcabfd..f4da05101 100644
--- a/deeptutor/partners/channels/manager.py
+++ b/deeptutor/partners/channels/manager.py
@@ -9,7 +9,7 @@ from typing import Any
from deeptutor.partners.bus.events import OutboundMessage
from deeptutor.partners.bus.queue import MessageBus
-from deeptutor.partners.channels.base import BaseChannel, constructing_for
+from deeptutor.partners.channels.base import BaseChannel, constructing_for, deliver_outbound
from deeptutor.partners.config.schema import ChannelsConfig
@@ -299,12 +299,7 @@ class ChannelManager:
@staticmethod
async def _send_once(channel: BaseChannel, msg: OutboundMessage) -> None:
"""Send one outbound message without retry policy."""
- if msg.metadata.get("_stream_delta") or msg.metadata.get("_stream_end"):
- await channel.send_delta(msg.chat_id, msg.content, msg.metadata)
- elif not msg.metadata.get("_streamed"):
- # ``_streamed`` marks a final reply already delivered live via
- # send_delta — skip the plain send to avoid a duplicate message.
- await channel.send(msg)
+ await deliver_outbound(channel, msg)
def _coalesce_stream_deltas(
self, first_msg: OutboundMessage
@@ -339,6 +334,8 @@ class ChannelManager:
combined_content += next_msg.content
if is_end:
final_metadata["_stream_end"] = True
+ if next_meta.get("_stream_final"):
+ final_metadata["_stream_final"] = True
break
else:
# First non-matching message defines the coalescing boundary.
diff --git a/deeptutor/services/partners/commands.py b/deeptutor/services/partners/commands.py
index 260369401..84e0a72ea 100644
--- a/deeptutor/services/partners/commands.py
+++ b/deeptutor/services/partners/commands.py
@@ -7,7 +7,12 @@ import shlex
from typing import Any, Callable
from deeptutor.agents._shared.tool_composition import default_optional_tools
+from deeptutor.multi_user.model_access import allowed_llm_options, apply_allowed_llm_selection
+from deeptutor.multi_user.partner_access import can_manage_partner
+from deeptutor.multi_user.paths import user_context
from deeptutor.partners.bus.events import InboundMessage
+from deeptutor.services.config import get_model_catalog_service
+from deeptutor.services.model_selection import apply_llm_selection_to_catalog, list_llm_options
from deeptutor.services.partners.sessions import PartnerSessionStore
@@ -21,6 +26,7 @@ class PartnerCommandSpec:
@dataclass(frozen=True)
class PartnerCommandResult:
content: str
+ metadata: dict[str, Any] | None = None
BUILTIN_PARTNER_COMMANDS: tuple[PartnerCommandSpec, ...] = (
@@ -32,6 +38,7 @@ BUILTIN_PARTNER_COMMANDS: tuple[PartnerCommandSpec, ...] = (
PartnerCommandSpec("/resume", "Reopen an archived conversation.", "<session ID>"),
PartnerCommandSpec("/delete", "Delete a conversation permanently.", "<session ID>"),
PartnerCommandSpec("/status", "Show partner, session, model, and tool status."),
+ PartnerCommandSpec("/model", "List or switch this partner's model.", "[number|model name]"),
PartnerCommandSpec("/history", "Show recent messages in this conversation.", "[n]"),
PartnerCommandSpec("/tool", "Show or change enabled tools.", "[on|off <name>|reset]"),
PartnerCommandSpec(
@@ -110,6 +117,8 @@ class PartnerCommandHandler:
return self._delete(args)
if command == "/status":
return self._status(msg)
+ if command == "/model":
+ return self._model(msg, args)
if command == "/history":
return self._history(msg, args)
if command == "/tool":
@@ -224,6 +233,141 @@ class PartnerCommandHandler:
]
return PartnerCommandResult("\n".join(lines))
+ def _model(self, msg: InboundMessage, args: list[str]) -> PartnerCommandResult:
+ """List catalog models or persist a validated partner-level selection."""
+ if (msg.metadata or {}).get("is_group") or (msg.metadata or {}).get("chat_type") == "group":
+ return PartnerCommandResult(
+ "Use /model in a linked direct message to manage this partner's model."
+ )
+ # Model names and profile wiring are part of partner configuration,
+ # not the permissions granted to everyone who may chat with it.
+ if msg.actor is None and msg.channel != "web":
+ return PartnerCommandResult(
+ "Link this chat to the partner owner or an admin with /link before managing models."
+ )
+ if not can_manage_partner(self.partner_id, msg.actor):
+ return PartnerCommandResult("You cannot manage this partner's models.")
+
+ try:
+ catalog = get_model_catalog_service().load()
+ all_options = list_llm_options(catalog)
+ options = all_options["options"]
+ if msg.actor is not None and not msg.actor.is_admin:
+ with user_context(msg.actor):
+ allowed = {
+ (row["profile_id"], row["model_id"])
+ for row in allowed_llm_options()["options"]
+ }
+ options = [
+ row for row in options if (row["profile_id"], row["model_id"]) in allowed
+ ]
+ except Exception as exc:
+ return PartnerCommandResult(f"Could not list models: {exc}")
+
+ configured_selection = getattr(self.config, "llm_selection", None)
+ legacy_model = (
+ str(getattr(self.config, "model", "") or "").strip() if not configured_selection else ""
+ )
+ active = configured_selection or all_options["active"] or {}
+ if legacy_model:
+ legacy_option = next((row for row in options if row["model"] == legacy_model), None)
+ active = (
+ {
+ "profile_id": legacy_option["profile_id"],
+ "model_id": legacy_option["model_id"],
+ }
+ if legacy_option
+ else {}
+ )
+ current = next(
+ (
+ row
+ for row in options
+ if row["profile_id"] == active.get("profile_id")
+ and row["model_id"] == active.get("model_id")
+ ),
+ None,
+ )
+ 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.")
+ metadata = (
+ {"_feishu_model_options": options, "_feishu_model_current": active}
+ if msg.channel == "feishu" and (msg.metadata or {}).get("chat_type") == "p2p"
+ else None
+ )
+ return PartnerCommandResult("\n".join(lines), metadata)
+
+ choice: dict[str, Any] | None = None
+ if len(args) == 1 and args[0].isdigit():
+ index = int(args[0]) - 1
+ 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,
+ )
+ 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()}
+ ]
+ if len(matches) == 1:
+ choice = matches[0]
+ elif len(matches) > 1:
+ return PartnerCommandResult("That model name is ambiguous. Use its /model number.")
+ if choice is None:
+ return PartnerCommandResult("Unknown model. Use /model to see available numbers.")
+
+ selection = {"profile_id": choice["profile_id"], "model_id": choice["model_id"]}
+ try:
+ apply_llm_selection_to_catalog(catalog, selection)
+ if msg.actor is not None and not msg.actor.is_admin:
+ with user_context(msg.actor):
+ apply_allowed_llm_selection(selection)
+ except (PermissionError, ValueError) as exc:
+ return PartnerCommandResult(str(exc))
+
+ selected_label = f"{choice['provider_label']} · {choice['model_name']}"
+ 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"
+ )
+ old_selection = getattr(self.config, "llm_selection", None)
+ old_legacy_model = getattr(self.config, "model", None)
+ self.config.llm_selection = selection
+ self.config.model = None
+ try:
+ self._persist_config()
+ except Exception as exc:
+ self.config.llm_selection = old_selection
+ self.config.model = old_legacy_model
+ return PartnerCommandResult(f"Could not switch model: {exc}")
+ return PartnerCommandResult(
+ f"✅ Switched model: {previous_label} → {selected_label}.",
+ {"_feishu_model_switch_success": True},
+ )
+
def _history(self, msg: InboundMessage, args: list[str]) -> PartnerCommandResult:
count = 10
if args:
diff --git a/deeptutor/services/partners/manager.py b/deeptutor/services/partners/manager.py
index a409b29ff..89dad72ea 100644
--- a/deeptutor/services/partners/manager.py
+++ b/deeptutor/services/partners/manager.py
@@ -23,6 +23,7 @@ import yaml
from deeptutor.core.stream import StreamEventType
from deeptutor.multi_user.models import CurrentUser
+from deeptutor.partners.channels.base import deliver_outbound
from deeptutor.partners.config.paths import (
get_data_dir,
get_partner_dir,
@@ -687,13 +688,18 @@ class PartnerManager:
event_bus = get_event_bus()
while True:
msg: _OMsg = await bus.consume_outbound()
- is_progress = bool(msg.metadata and msg.metadata.get("_progress"))
+ metadata = msg.metadata or {}
+ is_progress = bool(
+ metadata.get("_progress")
+ or metadata.get("_stream_delta")
+ or metadata.get("_stream_end")
+ )
if instance.channel_manager:
channel = instance.channel_manager.get_channel(msg.channel)
if channel:
try:
- await channel.send(msg)
+ await deliver_outbound(channel, msg)
except Exception:
logger.exception(
"Failed to send to channel %s for partner %s",
diff --git a/deeptutor/services/partners/runtime.py b/deeptutor/services/partners/runtime.py
index 77c9d5afd..8e5f48514 100644
--- a/deeptutor/services/partners/runtime.py
+++ b/deeptutor/services/partners/runtime.py
@@ -116,7 +116,7 @@ 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"):
+ for key in ("message_thread_id", "message_id", "_feishu_model_picker_message_id"):
value = in_meta.get(key)
if value is not None:
meta[key] = value
@@ -313,6 +313,8 @@ class PartnerRunner:
save_config=self.save_config,
).dispatch(msg)
if command is not None:
+ if delivery_meta is not None and command.metadata:
+ delivery_meta.update(command.metadata)
return command.content
final, turn_events = await self._run_turn(
@@ -624,15 +626,17 @@ class PartnerRunner:
# rounds after a crash) so channels can flush their edit buffers.
for call_id in streamed_rounds:
if call_id not in ended_rounds:
- await self._publish_stream_end(msg, turn_id, call_id)
# The reply is "already delivered" only when the live-streamed
# text matches what the caller is about to send.
- if (
+ is_final_stream = bool(
delivery_meta is not None
and final_text
and streamed_rounds[call_id].strip() == final_text
- ):
+ )
+ await self._publish_stream_end(msg, turn_id, call_id, final_stream=is_final_stream)
+ if is_final_stream:
delivery_meta["_streamed"] = True
+ delivery_meta["_stream_id"] = f"{turn_id}:{call_id}"
return final_text, errors, turn_events
@@ -1090,7 +1094,14 @@ class PartnerRunner:
)
)
- async def _publish_stream_end(self, msg: InboundMessage, turn_id: str, call_id: str) -> None:
+ async def _publish_stream_end(
+ self,
+ msg: InboundMessage,
+ turn_id: str,
+ call_id: str,
+ *,
+ final_stream: bool = False,
+ ) -> None:
await self.bus.publish_outbound(
OutboundMessage(
channel=msg.channel,
@@ -1099,6 +1110,7 @@ class PartnerRunner:
metadata={
"_stream_end": True,
"_stream_id": f"{turn_id}:{call_id}",
+ **({"_stream_final": True} if final_stream else {}),
**_thread_delivery_meta(msg),
},
)
diff --git a/tests/services/partners/test_feishu_final_delivery.py b/tests/services/partners/test_feishu_final_delivery.py
new file mode 100644
index 000000000..2529b3a1a
--- /dev/null
+++ b/tests/services/partners/test_feishu_final_delivery.py
@@ -0,0 +1,98 @@
+"""A streamed Feishu answer must have one confirmed delivery path."""
+
+from __future__ import annotations
+
+import time
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+
+from deeptutor.partners.bus.events import OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels.base import deliver_outbound
+from deeptutor.partners.channels.feishu import FeishuChannel
+
+
+def _channel() -> FeishuChannel:
+ channel = FeishuChannel({"enabled": True, "appId": "app", "appSecret": "secret"}, MessageBus())
+ channel._client = SimpleNamespace()
+ channel._create_streaming_card_sync = MagicMock(return_value="card-1")
+ channel._stream_update_text_sync = MagicMock(return_value=True)
+ channel._close_streaming_mode_sync = MagicMock(return_value=True)
+ channel._send_message_sync = MagicMock(return_value=True)
+ return channel
+
+
+def _message(content: str, **metadata: object) -> OutboundMessage:
+ return OutboundMessage(
+ channel="feishu",
+ chat_id="oc_group",
+ content=content,
+ metadata={"message_id": "om_user", "_stream_id": "turn:finish", **metadata},
+ )
+
+
+async def test_successful_stream_end_suppresses_plain_final() -> None:
+ channel = _channel()
+ await deliver_outbound(channel, _message("Answer", _stream_delta=True))
+ await deliver_outbound(channel, _message("", _stream_end=True, _stream_final=True))
+ await deliver_outbound(channel, _message("Answer", _streamed=True))
+
+ channel._send_message_sync.assert_not_called()
+
+
+async def test_failed_stream_card_falls_back_to_plain_final() -> None:
+ channel = _channel()
+ channel._create_streaming_card_sync.return_value = None
+ channel._send_message_sync.side_effect = [False, True]
+
+ await deliver_outbound(channel, _message("Answer", _stream_delta=True))
+ await deliver_outbound(channel, _message("", _stream_end=True, _stream_final=True))
+ await deliver_outbound(channel, _message("Answer", _streamed=True))
+
+ assert channel._send_message_sync.call_count == 2
+ assert channel._send_message_sync.call_args_list[-1].args[2] == "text"
+
+
+async def test_failed_stream_close_does_not_duplicate_visible_answer() -> None:
+ channel = _channel()
+ channel._close_streaming_mode_sync.return_value = False
+
+ await deliver_outbound(channel, _message("Answer", _stream_delta=True))
+ await deliver_outbound(channel, _message("", _stream_end=True, _stream_final=True))
+ await deliver_outbound(channel, _message("Answer", _streamed=True))
+
+ channel._stream_update_text_sync.assert_called_with("card-1", "Answer", 2)
+ channel._send_message_sync.assert_not_called()
+
+
+async def test_transient_reaction_delete_failure_is_retried() -> None:
+ channel = _channel()
+ channel._working_reactions["om_user"] = ("reaction-1", time.monotonic())
+ channel._remove_reaction_sync = MagicMock(side_effect=[False, True])
+ channel._REACTION_DELETE_RETRY_DELAYS = (0,)
+
+ await channel._finish_reaction("om_user")
+
+ assert channel._remove_reaction_sync.call_count == 2
+ assert "om_user" not in channel._working_reactions
+
+
+async def test_long_turn_still_removes_its_working_reaction() -> None:
+ channel = _channel()
+ channel._working_reactions["om_user"] = (
+ "reaction-1",
+ time.monotonic() - channel._WORKING_REACTION_TTL - 1,
+ )
+ channel._remove_reaction_sync = MagicMock(return_value=True)
+
+ await channel._finish_reaction("om_user")
+
+ channel._remove_reaction_sync.assert_called_once_with("om_user", "reaction-1")
+ assert "om_user" not in channel._working_reactions
diff --git a/tests/services/partners/test_feishu_model_picker.py b/tests/services/partners/test_feishu_model_picker.py
new file mode 100644
index 000000000..0687e5367
--- /dev/null
+++ b/tests/services/partners/test_feishu_model_picker.py
@@ -0,0 +1,256 @@
+"""Feishu /model cards use the same validated Partner command as typed selection."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+
+from deeptutor.partners.bus.events import InboundMessage, OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels.feishu import FeishuChannel
+from deeptutor.services.partners import commands as commands_mod
+from deeptutor.services.partners.commands import PartnerCommandHandler
+from deeptutor.services.partners.manager import PartnerConfig
+from deeptutor.services.partners.runtime import PartnerRunner
+
+
+def _catalog(count: int = 8) -> dict:
+ return {
+ "services": {
+ "llm": {
+ "active_profile_id": "profile",
+ "active_model_id": "model-0",
+ "profiles": [
+ {
+ "id": "profile",
+ "name": "Test profile",
+ "binding": "openai",
+ "models": [
+ {"id": f"model-{index}", "name": f"Model {index}", "model": f"m{index}"}
+ for index in range(count)
+ ],
+ }
+ ],
+ }
+ }
+ }
+
+
+def _message(content: str, *, chat_type: str = "p2p", actor=None) -> InboundMessage:
+ return InboundMessage(
+ channel="feishu",
+ sender_id="ou_owner",
+ chat_id="ou_owner" if chat_type == "p2p" else "oc_group",
+ content=content,
+ metadata={"chat_type": chat_type},
+ actor=actor,
+ )
+
+
+def _handler(monkeypatch, config=None, *, save=None) -> PartnerCommandHandler:
+ monkeypatch.setattr(
+ commands_mod,
+ "get_model_catalog_service",
+ lambda: SimpleNamespace(load=lambda: _catalog()),
+ )
+ return PartnerCommandHandler(
+ partner_id="ada",
+ config=config or PartnerConfig(name="Ada"),
+ store=MagicMock(),
+ save_config=save,
+ )
+
+
+def _channel() -> FeishuChannel:
+ channel = FeishuChannel(
+ {"enabled": True, "appId": "app", "appSecret": "secret", "allowFrom": ["ou_owner"]},
+ MessageBus(),
+ )
+ channel._client = SimpleNamespace(
+ im=SimpleNamespace(v1=SimpleNamespace(message=SimpleNamespace(patch=MagicMock())))
+ )
+ return channel
+
+
+def _callback(value: dict, *, sender: str = "ou_owner", message_id: str = "om_picker"):
+ return SimpleNamespace(
+ event=SimpleNamespace(
+ action=SimpleNamespace(value=value),
+ operator=SimpleNamespace(open_id=sender),
+ context=SimpleNamespace(open_message_id=message_id, open_chat_id="oc_private"),
+ )
+ )
+
+
+def test_model_command_lists_choices_and_keeps_group_text_only(monkeypatch) -> None:
+ handler = _handler(monkeypatch)
+ private = handler.dispatch(_message("/model", actor=SimpleNamespace(is_admin=True)))
+ assert private is not None
+ assert "1. OpenAI · Model 0 (current)" in private.content
+ assert len(private.metadata["_feishu_model_options"]) == 8
+
+ group = handler.dispatch(_message("/model", chat_type="group"))
+ assert group is not None and group.metadata is None
+ assert "linked direct message" in group.content
+
+ unlinked = handler.dispatch(_message("/model"))
+ assert unlinked is not None and "Link this chat" in unlinked.content
+ assert unlinked.metadata is None
+
+
+def test_model_switch_requires_linked_manager_and_persists_valid_pair(monkeypatch) -> None:
+ saved = []
+ config = PartnerConfig(name="Ada", model="legacy-model")
+ handler = _handler(
+ monkeypatch, config, save=lambda partner_id, cfg: saved.append((partner_id, cfg))
+ )
+ monkeypatch.setattr(
+ commands_mod, "can_manage_partner", lambda partner_id, actor: actor.is_admin
+ )
+
+ denied = handler.dispatch(_message("/model 2"))
+ assert denied is not None and "Link this chat" in denied.content
+ assert config.llm_selection is None and saved == []
+
+ actor = SimpleNamespace(is_admin=True)
+ switched = handler.dispatch(_message("/model 2", actor=actor))
+ assert switched is not None and switched.metadata["_feishu_model_switch_success"]
+ assert "legacy-model → OpenAI · Model 1" in switched.content
+ assert config.llm_selection == {"profile_id": "profile", "model_id": "model-1"}
+ assert config.model is None
+ assert saved == [("ada", config)]
+
+ invalid = handler.dispatch(_message("/model missing model-999", actor=actor))
+ assert invalid is not None and "Unknown model" in invalid.content
+ assert len(saved) == 1
+
+
+def test_selecting_catalog_default_clears_legacy_model_override(monkeypatch) -> None:
+ saved = []
+ config = PartnerConfig(name="Ada", model="legacy-model")
+ handler = _handler(monkeypatch, config, save=lambda partner_id, cfg: saved.append(partner_id))
+ monkeypatch.setattr(commands_mod, "can_manage_partner", lambda partner_id, actor: True)
+
+ result = handler.dispatch(_message("/model 1", actor=SimpleNamespace(is_admin=True)))
+ assert result is not None and result.metadata["_feishu_model_switch_success"]
+ assert config.llm_selection == {"profile_id": "profile", "model_id": "model-0"}
+ assert config.model is None
+ assert saved == ["ada"]
+
+
+async def test_runner_carries_picker_result_to_feishu_delivery(monkeypatch, partners_root) -> None:
+ monkeypatch.setattr(
+ commands_mod,
+ "get_model_catalog_service",
+ lambda: SimpleNamespace(load=lambda: _catalog()),
+ )
+ runner = PartnerRunner("ada", PartnerConfig(name="Ada"), MessageBus())
+ outbound_metadata: dict = {}
+ listing = await runner.process_message(
+ _message("/model", actor=SimpleNamespace(is_admin=True)),
+ delivery_meta=outbound_metadata,
+ )
+ assert "Available models" in listing
+ assert len(outbound_metadata["_feishu_model_options"]) == 8
+
+ callback_metadata: dict = {}
+ denied = await runner.process_message(
+ _message("/model profile model-1"), delivery_meta=callback_metadata
+ )
+ assert "Link this chat" in denied
+ assert "_feishu_model_switch_success" not in callback_metadata
+
+
+async def test_private_picker_pages_in_place_and_queues_selection() -> None:
+ pytest.importorskip("lark_oapi")
+ channel = _channel()
+ channel._loop = asyncio.get_running_loop()
+ channel._send_message_sync = MagicMock(return_value=True)
+ options = [
+ {
+ "profile_id": "profile",
+ "model_id": f"model-{index}",
+ "provider_label": "OpenAI",
+ "model_name": f"Model {index}",
+ }
+ for index in range(8)
+ ]
+ await channel.send(
+ OutboundMessage(
+ channel="feishu",
+ chat_id="ou_owner",
+ content="Available models",
+ metadata={
+ "_feishu_model_options": options,
+ "_feishu_model_current": {"profile_id": "profile", "model_id": "model-0"},
+ },
+ )
+ )
+ send_args = channel._send_message_sync.call_args.args
+ 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
+ picker_id = first_actions[0]["actions"][0]["value"]["picker_id"]
+ assert len(picker_id) == 16
+ assert "model_id" not in first_actions[0]["actions"][0]["value"]
+
+ page_response = channel._on_card_action_sync(
+ _callback({"picker_id": picker_id, "action": "page", "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 channel.bus.inbound.empty()
+ channel._send_message_sync.assert_called_once() # page callback sends no message
+
+ wrong_user = channel._on_card_action_sync(
+ _callback({"picker_id": picker_id, "action": "select", "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})
+ )
+ 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.chat_id == "ou_owner" # callback context has oc_, send target is ou_
+ assert inbound.metadata["_feishu_model_picker_message_id"] == "om_picker"
+
+
+async def test_model_switch_patches_clicked_card_then_uses_text_fallback_on_failure() -> None:
+ pytest.importorskip("lark_oapi")
+ channel = _channel()
+ channel._client.im.v1.message.patch.return_value = SimpleNamespace(success=lambda: True)
+ channel._send_message_sync = MagicMock(return_value=True)
+ outbound = OutboundMessage(
+ channel="feishu",
+ chat_id="ou_owner",
+ content="✅ Switched model: Old → New.",
+ metadata={
+ "_feishu_model_picker_message_id": "om_picker",
+ "_feishu_model_switch_success": True,
+ },
+ )
+ await channel.send(outbound)
+ request = channel._client.im.v1.message.patch.call_args.args[0]
+ assert request.paths["message_id"] == "om_picker"
+ assert "✅ Switched model: Old → New." in request.request_body.content
+ channel._send_message_sync.assert_not_called()
+
+ channel._client.im.v1.message.patch.return_value = SimpleNamespace(
+ success=lambda: False, code=500, msg="failed"
+ )
+ await channel.send(outbound)
+ fallback = channel._send_message_sync.call_args.args
+ assert fallback[:3] == ("open_id", "ou_owner", "text")
+ assert "✅ Switched model: Old → New." in json.loads(fallback[3])["text"]
diff --git a/tests/services/partners/test_feishu_reply_delivery.py b/tests/services/partners/test_feishu_reply_delivery.py
new file mode 100644
index 000000000..5e32b63c0
--- /dev/null
+++ b/tests/services/partners/test_feishu_reply_delivery.py
@@ -0,0 +1,223 @@
+"""Feishu replies and working badges follow confirmed final delivery (#1517)."""
+
+from __future__ import annotations
+
+import time
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from deeptutor.partners.bus.events import OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels.feishu import FeishuChannel
+
+
+def _response(*, ok: bool = True, data: object | None = None) -> SimpleNamespace:
+ return SimpleNamespace(
+ success=lambda: ok,
+ data=data,
+ code=0 if ok else 500,
+ msg="ok" if ok else "unavailable",
+ get_log_id=lambda: "log-1",
+ )
+
+
+def _channel() -> FeishuChannel:
+ channel = FeishuChannel({"enabled": True, "appId": "app", "appSecret": "secret"}, MessageBus())
+ message = SimpleNamespace(create=MagicMock(return_value=_response()))
+ message.reply = MagicMock(return_value=_response())
+ reaction = SimpleNamespace(
+ create=MagicMock(return_value=_response(data=SimpleNamespace(reaction_id="reaction-1"))),
+ delete=MagicMock(return_value=_response()),
+ )
+ card = SimpleNamespace(
+ create=MagicMock(return_value=_response(data=SimpleNamespace(card_id="card-1")))
+ )
+ channel._client = SimpleNamespace(
+ im=SimpleNamespace(v1=SimpleNamespace(message=message, message_reaction=reaction)),
+ cardkit=SimpleNamespace(v1=SimpleNamespace(card=card)),
+ )
+ return channel
+
+
+def test_reply_endpoint_uses_inbound_message_id_and_thread_flag() -> None:
+ pytest.importorskip("lark_oapi")
+ channel = _channel()
+
+ assert channel._send_message_sync("chat_id", "oc_group", "text", '{"text":"hi"}', "om_user")
+ request = channel._client.im.v1.message.reply.call_args.args[0]
+ assert request.paths["message_id"] == "om_user"
+ assert request.request_body.reply_in_thread is True
+ assert request.request_body.msg_type == "text"
+ channel._client.im.v1.message.create.assert_not_called()
+
+ assert channel._send_message_sync("chat_id", "oc_group", "text", '{"text":"notice"}')
+ channel._client.im.v1.message.create.assert_called_once()
+
+
+def test_explicit_reply_rejection_falls_back_to_standalone_delivery() -> None:
+ pytest.importorskip("lark_oapi")
+ channel = _channel()
+ channel._client.im.v1.message.reply.return_value = _response(ok=False)
+
+ assert channel._send_message_sync("chat_id", "oc_group", "text", '{"text":"hi"}', "om_old")
+ channel._client.im.v1.message.reply.assert_called_once()
+ channel._client.im.v1.message.create.assert_called_once()
+
+
+def test_uncertain_reply_transport_error_does_not_send_duplicate() -> None:
+ pytest.importorskip("lark_oapi")
+ channel = _channel()
+ channel._client.im.v1.message.reply.side_effect = TimeoutError("response lost")
+
+ assert not channel._send_message_sync("chat_id", "oc_group", "text", '{"text":"hi"}', "om_user")
+ channel._client.im.v1.message.create.assert_not_called()
+
+
+def test_reaction_receipt_is_deleted_by_its_own_id() -> None:
+ pytest.importorskip("lark_oapi")
+ channel = _channel()
+
+ assert channel._add_reaction_sync("om_user", "THUMBSUP") == "reaction-1"
+ assert channel._remove_reaction_sync("om_user", "reaction-1") is True
+ delete_request = channel._client.im.v1.message_reaction.delete.call_args.args[0]
+ assert delete_request.paths == {
+ "message_id": "om_user",
+ "reaction_id": "reaction-1",
+ }
+
+
+async def test_only_successful_final_send_clears_working_reaction() -> None:
+ channel = _channel()
+ channel._working_reactions["om_user"] = ("reaction-1", time.monotonic())
+ channel._send_message_sync = MagicMock(return_value=True)
+ channel._remove_reaction_sync = MagicMock(return_value=True)
+
+ progress = OutboundMessage(
+ channel="feishu",
+ chat_id="oc_group",
+ content="Thinking",
+ metadata={"message_id": "om_user", "_progress": True},
+ )
+ await channel.send(progress)
+ assert "om_user" in channel._working_reactions
+ channel._remove_reaction_sync.assert_not_called()
+
+ channel._send_message_sync.return_value = False
+ final = OutboundMessage(
+ channel="feishu",
+ chat_id="oc_group",
+ content="Answer",
+ metadata={"message_id": "om_user"},
+ )
+ await channel.send(final)
+ assert "om_user" in channel._working_reactions
+
+ channel._send_message_sync.return_value = True
+ await channel.send(final)
+ assert "om_user" not in channel._working_reactions
+ channel._remove_reaction_sync.assert_called_once_with("om_user", "reaction-1")
+ assert channel._send_message_sync.call_args.args[-1] == "om_user"
+
+
+async def test_failed_reaction_delete_retains_receipt_for_retry() -> None:
+ channel = _channel()
+ channel._working_reactions["om_user"] = ("reaction-1", time.monotonic())
+ channel._REACTION_DELETE_RETRY_DELAYS = (0,)
+ channel._REACTION_LATE_RETRY_DELAYS = (0,)
+ channel._remove_reaction_sync = MagicMock(side_effect=[False, False, True])
+
+ await channel._finish_reaction("om_user")
+ assert "om_user" in channel._working_reactions
+ await channel._reaction_cleanup_tasks[("om_user", "reaction-1")]
+ assert "om_user" not in channel._working_reactions
+
+
+async def test_streaming_card_replies_and_cleans_only_finalized_answer() -> None:
+ channel = _channel()
+ channel._working_reactions["om_user"] = ("reaction-1", time.monotonic())
+ channel._stream_update_text_sync = MagicMock(return_value=True)
+ channel._close_streaming_mode_sync = MagicMock(return_value=True)
+ channel._remove_reaction_sync = MagicMock(return_value=True)
+
+ await channel.send_delta("oc_group", "Narration", {"_stream_id": "n", "message_id": "om_user"})
+ card_reply = channel._client.im.v1.message.reply.call_args.args[0]
+ assert card_reply.paths["message_id"] == "om_user"
+ assert card_reply.request_body.msg_type == "interactive"
+ await channel.send_delta(
+ "oc_group", "", {"_stream_id": "n", "_stream_end": True, "message_id": "om_user"}
+ )
+ assert "om_user" in channel._working_reactions
+
+ await channel.send_delta("oc_group", "Answer", {"_stream_id": "f", "message_id": "om_user"})
+ await channel.send_delta(
+ "oc_group",
+ "",
+ {
+ "_stream_id": "f",
+ "_stream_end": True,
+ "_stream_final": True,
+ "message_id": "om_user",
+ },
+ )
+ assert "om_user" not in channel._working_reactions
+ channel._remove_reaction_sync.assert_called_once_with("om_user", "reaction-1")
+
+
+async def test_failed_stream_fallback_keeps_badge_until_reply_delivered() -> None:
+ channel = _channel()
+ channel._working_reactions["om_user"] = ("reaction-1", time.monotonic())
+ channel._create_streaming_card_sync = MagicMock(return_value=None)
+ channel._send_message_sync = MagicMock(return_value=False)
+ channel._remove_reaction_sync = MagicMock(return_value=True)
+
+ await channel.send_delta("ou_user", "Answer", {"_stream_id": "f", "message_id": "om_user"})
+ await channel.send_delta(
+ "ou_user",
+ "",
+ {"_stream_id": "f", "_stream_end": True, "_stream_final": True},
+ )
+ assert channel._send_message_sync.call_args.args[-1] == "om_user"
+ assert "om_user" in channel._working_reactions
+ channel._remove_reaction_sync.assert_not_called()
+
+
+def test_reaction_receipts_expire_and_remain_bounded() -> None:
+ channel = _channel()
+ channel._MAX_WORKING_REACTIONS = 2
+ now = time.monotonic()
+ channel._working_reactions.update(
+ {
+ "expired": ("r0", now - channel._WORKING_REACTION_TTL - 1),
+ "first": ("r1", now - 2),
+ "second": ("r2", now - 1),
+ "third": ("r3", now),
+ }
+ )
+
+ channel._prune_working_reactions()
+ assert list(channel._working_reactions) == ["second", "third"]
+
+
+async def test_disallowed_inbound_message_does_not_get_stuck_working_badge() -> None:
+ channel = _channel() # empty allowFrom denies this sender
+ channel._add_reaction = AsyncMock()
+ event = SimpleNamespace(
+ message=SimpleNamespace(
+ message_id="om_user",
+ chat_id="oc_group",
+ chat_type="p2p",
+ message_type="text",
+ content='{"text":"hello"}',
+ ),
+ sender=SimpleNamespace(sender_type="user", sender_id=SimpleNamespace(open_id="ou_user")),
+ )
+
+ await channel._on_message(SimpleNamespace(event=event))
+ channel._add_reaction.assert_not_awaited()
diff --git a/tests/services/partners/test_partner_outbound_delivery.py b/tests/services/partners/test_partner_outbound_delivery.py
new file mode 100644
index 000000000..84b8412d5
--- /dev/null
+++ b/tests/services/partners/test_partner_outbound_delivery.py
@@ -0,0 +1,65 @@
+"""The live partner router preserves the shared streaming delivery contract."""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from deeptutor.partners.bus.events import OutboundMessage
+from deeptutor.services.partners.manager import PartnerManager
+
+
+class _FiniteBus:
+ def __init__(self, messages: list[OutboundMessage]) -> None:
+ self.messages = list(messages)
+
+ async def consume_outbound(self) -> OutboundMessage:
+ if self.messages:
+ return self.messages.pop(0)
+ raise asyncio.CancelledError
+
+
+async def test_live_router_dispatches_delta_end_and_final_once(monkeypatch) -> None:
+ channel = SimpleNamespace(send=AsyncMock(), send_delta=AsyncMock())
+ event_bus = SimpleNamespace(publish=AsyncMock())
+ monkeypatch.setattr("deeptutor.events.event_bus.get_event_bus", lambda: event_bus)
+ instance = SimpleNamespace(
+ channel_manager=SimpleNamespace(get_channel=lambda _: channel),
+ channel_bindings={},
+ activity_feed=SimpleNamespace(publish=MagicMock()),
+ )
+ messages = [
+ OutboundMessage(
+ channel="feishu",
+ chat_id="oc_group",
+ content="part",
+ metadata={"_stream_delta": True, "_stream_id": "turn:1"},
+ ),
+ OutboundMessage(
+ channel="feishu",
+ chat_id="oc_group",
+ content="",
+ metadata={"_stream_end": True, "_stream_final": True, "_stream_id": "turn:1"},
+ ),
+ OutboundMessage(
+ channel="feishu",
+ chat_id="oc_group",
+ content="part",
+ metadata={"_streamed": True},
+ ),
+ OutboundMessage(channel="telegram", chat_id="42", content="ordinary reply"),
+ ]
+ instance.channel_manager.get_channel = lambda _: channel
+
+ await PartnerManager._outbound_router(None, "partner", _FiniteBus(messages), instance)
+
+ assert channel.send_delta.await_count == 2
+ assert channel.send_delta.await_args_list[1].args[2]["_stream_final"] is True
+ assert channel.send.await_count == 1
+ assert channel.send.await_args.args[0].content == "ordinary reply"
+ assert event_bus.publish.await_count == 2 # streamed final and ordinary final
+ assert instance.activity_feed.publish.call_count == 2
diff --git a/tests/services/partners/test_partner_runtime.py b/tests/services/partners/test_partner_runtime.py
index fbd96e16a..e5d8b5f23 100644
--- a/tests/services/partners/test_partner_runtime.py
+++ b/tests/services/partners/test_partner_runtime.py
@@ -626,6 +626,35 @@ class TestOutboundThreadRouting:
assert out.metadata["message_thread_id"] == 55
assert out.metadata["message_id"] == 999
+ @pytest.mark.asyncio
+ async def test_only_answer_stream_end_marks_confirmable_final_delivery(
+ self, partners_root, fake_orchestrator
+ ):
+ fake_orchestrator.script = narration_round("intro", "Checking") + finish("Answer")
+ runner = _runner(partners_root)
+ msg = InboundMessage(
+ channel="feishu",
+ sender_id="ou_user",
+ chat_id="oc_group",
+ content="Question",
+ metadata={"message_id": "om_user", "_wants_stream": True},
+ )
+ delivery_meta: dict[str, Any] = {}
+
+ assert await runner.process_message(msg, delivery_meta=delivery_meta) == "Answer"
+ ends = []
+ while not runner.bus.outbound.empty():
+ outbound = await runner.bus.outbound.get()
+ if outbound.metadata.get("_stream_end"):
+ ends.append(outbound)
+
+ assert len(ends) == 2
+ assert ends[0].metadata.get("_stream_final") is None
+ assert ends[1].metadata["_stream_final"] is True
+ assert ends[1].metadata["message_id"] == "om_user"
+ assert delivery_meta["_streamed"] is True
+ assert delivery_meta["_stream_id"] == ends[1].metadata["_stream_id"]
+
@pytest.mark.asyncio
async def test_missing_thread_metadata_is_not_injected(self, partners_root, fake_orchestrator):
fake_orchestrator.script = finish("reply text")