From cd9fbf2967d198b049b559db53278e6c2b62eeca Mon Sep 17 00:00:00 2001 From: Totoro Date: Mon, 23 Nov 2026 21:54:39 +0800 Subject: [PATCH] fix(feishu): keep topic and card replies on their conversation (#8523) * fix(feishu): keep topic and card replies on their conversation * fix(feishu): preserve topic and sender routing through dispatch * fix(feishu): follow explicit replies to earlier answer cards --------- Co-authored-by: Totoro-qaq <279883115+Totoro-qaq@users.noreply.github.com> --- backend/app/channels/connection_identity.py | 13 +- backend/app/channels/feishu.py | 143 +++++++++++--------- backend/app/channels/manager.py | 6 +- backend/app/channels/service.py | 5 + backend/docs/IM_CHANNEL_CONNECTIONS.md | 12 ++ backend/tests/test_channels.py | 11 ++ backend/tests/test_feishu_card_delivery.py | 118 ++++++++++++---- backend/tests/test_feishu_parser.py | 65 ++++++--- 8 files changed, 265 insertions(+), 108 deletions(-) diff --git a/backend/app/channels/connection_identity.py b/backend/app/channels/connection_identity.py index 5b0b8a018b..80d3dcfc84 100644 --- a/backend/app/channels/connection_identity.py +++ b/backend/app/channels/connection_identity.py @@ -44,6 +44,17 @@ async def attach_connection_identity( return inbound +def fallback_store_channel(channel_name: str, topic_id: str | None, repo: Any) -> str: + """Select the binding namespace for a topic without a connection. + + Feishu deployments using connection identities keep unbound topics in a + separate namespace. Room bindings and legacy deployments use the channel name. + """ + if channel_name == "feishu" and topic_id and repo is not None: + return "feishu-unbound" + return channel_name + + async def lookup_thread_id(msg: InboundMessage, *, repo: Any, store: Any) -> str | None: """Return the DeerFlow thread mapped to *msg*'s conversation/topic, if any. @@ -58,4 +69,4 @@ async def lookup_thread_id(msg: InboundMessage, *, repo: Any, store: Any) -> str return await repo.get_thread_id(msg.connection_id, msg.chat_id, msg.topic_id) if store is None: return None - return await store.get_thread_id(msg.channel_name, msg.chat_id, topic_id=msg.topic_id) + return await store.get_thread_id(fallback_store_channel(msg.channel_name, msg.topic_id, repo), msg.chat_id, topic_id=msg.topic_id) diff --git a/backend/app/channels/feishu.py b/backend/app/channels/feishu.py index e28de9fe27..6ae862c404 100644 --- a/backend/app/channels/feishu.py +++ b/backend/app/channels/feishu.py @@ -13,12 +13,12 @@ from collections import deque from collections.abc import Callable, Coroutine from concurrent.futures import CancelledError as FutureCancelledError from concurrent.futures import Future -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from typing import Any, Literal, TypeVar from app.channels.base import Channel, ChannelStopTimeout, ChannelUnavailable, abort_connection_transport, shutdown_private_loop from app.channels.commands import is_known_channel_command, strip_leading_mentions -from app.channels.connection_identity import attach_connection_identity, lookup_thread_id +from app.channels.connection_identity import attach_connection_identity, fallback_store_channel, lookup_thread_id from app.channels.feishu_card_interaction import ( ClarificationCardRequest, PendingCardEntry, @@ -122,6 +122,9 @@ class _Routing: from_stored_mapping: bool from_pending: bool clarification_card_id: str | None = None + connection_id: str | None = None + owner_user_id: str | None = None + workspace_id: str | None = None @dataclass(slots=True) @@ -344,9 +347,9 @@ class FeishuChannel(Channel): self._background_tasks: set[asyncio.Task] = set() self._running_card_ids: dict[str, str] = {} self._running_card_tasks: dict[str, asyncio.Task] = {} - # Thread aliases (chat_id, thread_id, topic_id, user_id) already written + # Thread aliases (chat_id, thread_id, topic_id, sender_id, connection_id) written # for each in-flight reply, keyed by source message id. - self._remembered_thread_aliases: dict[str, set[tuple[str, str, str, str]]] = {} + self._remembered_thread_aliases: dict[str, set[tuple[str, str, str, str, str | None]]] = {} self._pending_clarifications: dict[tuple[str, str], list[dict[str, Any]]] = {} # Interactive clarification cards (button answers). Off by default: the # feature needs a one-time console subscription to card.action.trigger. @@ -1209,15 +1212,7 @@ class FeishuChannel(Channel): # is reused across a thread's cards without exposing callback tokens. topic_id = f"feishu-card:{msg.thread_id}" try: - if msg.connection_id: - if self._connection_repo is None or not msg.owner_user_id: - return None - await self._connection_repo.set_thread_id(connection_id=msg.connection_id, owner_user_id=msg.owner_user_id, provider=self.name, external_conversation_id=msg.chat_id, thread_id=msg.thread_id, external_topic_id=topic_id) - else: - store = self.config.get("channel_store") - if store is None: - return None - await store.set_thread_id(self.name, msg.chat_id, msg.thread_id, topic_id=topic_id, user_id=user_id) + await self._record_thread_alias(msg.chat_id, topic_id, msg.thread_id, user_id, msg.connection_id, msg.owner_user_id) except Exception: logger.exception("[Feishu] cannot bind clarification card to thread %s; using text fallback", msg.thread_id) return None @@ -1356,17 +1351,25 @@ class FeishuChannel(Channel): # -- internal ---------------------------------------------------------- + async def _record_thread_alias(self, chat_id: str, topic_id: str, thread_id: str, user_id: str, connection_id: str | None, owner_id: str | None) -> None: + if connection_id: + if self._connection_repo is None or not owner_id: + raise ValueError("Missing Feishu connection owner or repository") + # A late reply can add an alias, but /new owns explicit topic rebinding. + await self._connection_repo.claim_thread_id(connection_id=connection_id, owner_user_id=owner_id, provider=self.name, external_conversation_id=chat_id, external_topic_id=topic_id, thread_id=thread_id) + else: + store = self.config["channel_store"] + await store.set_thread_id(fallback_store_channel(self.name, topic_id, self._connection_repo), chat_id, thread_id, topic_id=topic_id, user_id=user_id) + async def _remember_thread_mapping(self, msg: OutboundMessage, *topic_ids: str | None) -> None: """Map the reply's message, card and topic ids to its DeerFlow thread. Every streamed chunk of a reply carries the same aliases, and each write is a full ``store.json`` rewrite or a database upsert, so a non-final - chunk only writes the aliases this reply has not stored yet. The final - outbound writes all of them again, leaving the store as it was when every - chunk wrote them. + chunk only records new aliases. The final outbound checks them all again + so a missing alias can be restored. """ - store = self.config.get("channel_store") - if store is None or not msg.thread_id: + if not msg.thread_id or (not msg.connection_id and self.config.get("channel_store") is None): return topic_id = self._non_empty_str(msg.metadata.get("topic_id")) @@ -1389,17 +1392,11 @@ class FeishuChannel(Channel): if not topic_id or topic_id in seen: continue seen.add(topic_id) - alias = (msg.chat_id, msg.thread_id, topic_id, user_id) + alias = (msg.chat_id, msg.thread_id, topic_id, user_id, msg.connection_id) if alias in remembered: continue try: - await store.set_thread_id( - self.name, - msg.chat_id, - msg.thread_id, - topic_id=topic_id, - user_id=user_id, - ) + await self._record_thread_alias(msg.chat_id, topic_id, msg.thread_id, user_id, msg.connection_id, msg.owner_user_id) except Exception: # Not remembered, so the next chunk retries it. logger.exception("[Feishu] failed to remember thread mapping for topic_id=%s", topic_id) @@ -1586,6 +1583,8 @@ class FeishuChannel(Channel): "topic_id": topic_id, "source_message_id": source_message_id, "card_message_id": card_message_id, + "connection_id": msg.connection_id, + "owner_user_id": msg.owner_user_id if msg.connection_id else None, "created_at": time.time(), } with self._thread_lock: @@ -1601,7 +1600,7 @@ class FeishuChannel(Channel): msg.thread_id, ) - def _consume_pending_clarification(self, chat_id: str, user_id: str, *, reply_to_ids: list[str] | None = None) -> dict[str, Any] | None: + def _consume_pending_clarification(self, chat_id: str, user_id: str, *, reply_to_ids: list[str] | None = None, connection_id: str | None = None, owner_user_id: str | None = None) -> dict[str, Any] | None: key = self._pending_key(chat_id, user_id) with self._thread_lock: pending_items = self._pending_clarifications.get(key) @@ -1610,14 +1609,15 @@ class FeishuChannel(Channel): now = time.time() pending_items = [pending for pending in pending_items if isinstance(pending.get("created_at"), (int, float)) and now - pending["created_at"] <= PENDING_CLARIFICATION_TTL_SECONDS] + candidates = [(i, p) for i, p in enumerate(pending_items) if (p.get("connection_id"), p.get("owner_user_id")) == (connection_id, owner_user_id if connection_id else None)] # Explicit replies target a card/source, while accepted ordinary # replies use their current thread alias. Shared roots cannot select # a card belonging to a conversation replaced by /new. if reply_to_ids is None: - matched = 0 if pending_items else None + matched = candidates[0][0] if candidates else None else: matched = next( - (index for field in ("card_message_id", "source_message_id", "topic_id") for candidate in reply_to_ids for index, pending in enumerate(pending_items) if pending.get(field) == candidate), + (index for field in ("card_message_id", "source_message_id", "topic_id") for candidate in reply_to_ids for index, pending in candidates if pending.get(field) == candidate), None, ) pending = pending_items.pop(matched) if matched is not None else None @@ -1646,45 +1646,60 @@ class FeishuChannel(Channel): async def _resolve_routing(self, attempt: _RoutingAttempt) -> _Routing: """Decide a message's topic on the Gateway loop, consulting and updating the channel store. - Stored mappings for the root / parent / thread ids win (``_first_stored_topic``); - otherwise the route is the root (or the message itself; ``None`` in P2P chats), - unless a pending clarification for the sender names a topic — that topic's - mapping is then persisted so the manager finds the clarified thread. The - pending clarification is consumed once: a retried attempt keeps the decision - and only redoes the write. + Bound chat replies prefer the parent message so an earlier card can still + be followed after ``/new``. Commands and unbound messages prefer the root. + The Feishu thread ID is checked last. A miss falls back to the root or + the message itself (``None`` in P2P chats). If a pending clarification + supplies a topic, persist its mapping so the manager finds that thread. + A retry reuses the same clarification and only repeats the write. """ store = self.config.get("channel_store") parsed = attempt.parsed + route = InboundMessage(channel_name=self.name, chat_id=parsed.chat_id, user_id=parsed.sender_id, text="") + if self._connection_repo is not None: + await self._attach_connection_identity(route) + default = _Routing( + topic_id=None if parsed.chat_type == "p2p" else (parsed.root_id or parsed.msg_id), + from_stored_mapping=False, + from_pending=False, + connection_id=route.connection_id, + owner_user_id=route.owner_user_id, + workspace_id=route.workspace_id, + ) if attempt.pending is None: - candidates = [candidate for candidate in (self._non_empty_str(parsed.root_id), parsed.parent_id, parsed.feishu_thread_id) if candidate] + root_id = self._non_empty_str(parsed.root_id) + message_ids = (parsed.parent_id, root_id) if route.connection_id and parsed.msg_type == InboundMessageType.CHAT else (root_id, parsed.parent_id) + candidates = [candidate for candidate in (*message_ids, parsed.feishu_thread_id) if candidate] if candidates: - stored = await self._first_stored_topic(store, parsed.chat_id, candidates) + stored = await self._first_stored_topic(store, route, candidates) if stored: pending = ( - self._consume_pending_clarification(parsed.chat_id, parsed.sender_id, reply_to_ids=[parsed.parent_id]) if self._card_interaction_enabled and parsed.msg_type == InboundMessageType.CHAT and parsed.parent_id else None + self._consume_pending_clarification(parsed.chat_id, parsed.sender_id, reply_to_ids=[parsed.parent_id], connection_id=route.connection_id, owner_user_id=route.owner_user_id) + if self._card_interaction_enabled and parsed.msg_type == InboundMessageType.CHAT and parsed.parent_id + else None ) if pending: - return _Routing(pending["topic_id"], True, True, self._non_empty_str(pending.get("card_message_id"))) - return _Routing(stored, True, False) - topic_id: str | None = parsed.root_id or parsed.msg_id - if parsed.chat_type == "p2p": - topic_id = None + return replace(default, topic_id=pending["topic_id"], from_stored_mapping=True, from_pending=True, clarification_card_id=self._non_empty_str(pending.get("card_message_id"))) + return replace(default, topic_id=stored, from_stored_mapping=True) if parsed.msg_type != InboundMessageType.CHAT: - return _Routing(topic_id, False, False) + return default if self._card_interaction_enabled and parsed.chat_type == "p2p" and not candidates: # Unthreaded P2P messages follow the current conversation, # including /new. Only explicit card replies use the old alias. - return _Routing(None, False, False) + return default reply_to_ids = [parsed.parent_id] if self._card_interaction_enabled and parsed.parent_id else None - pending = self._consume_pending_clarification(parsed.chat_id, parsed.sender_id, reply_to_ids=reply_to_ids) + pending = self._consume_pending_clarification(parsed.chat_id, parsed.sender_id, reply_to_ids=reply_to_ids, connection_id=route.connection_id, owner_user_id=route.owner_user_id) if not (pending and self._non_empty_str(pending.get("topic_id"))): - return _Routing(topic_id, False, False) + return default attempt.pending = pending pending_topic_id = self._non_empty_str(attempt.pending.get("topic_id")) thread_id = self._non_empty_str(attempt.pending.get("thread_id")) - if thread_id: - await store.set_thread_id(self.name, parsed.chat_id, thread_id, topic_id=pending_topic_id, user_id=parsed.sender_id) - return _Routing(pending_topic_id, False, True, self._non_empty_str(attempt.pending.get("card_message_id"))) + if (attempt.pending.get("connection_id"), attempt.pending.get("owner_user_id")) != (route.connection_id, route.owner_user_id): + attempt.pending = None + return default + if thread_id and (route.connection_id or store is not None): + await self._record_thread_alias(parsed.chat_id, pending_topic_id, thread_id, parsed.sender_id, route.connection_id, route.owner_user_id) + return replace(default, topic_id=pending_topic_id, from_pending=True, clarification_card_id=self._non_empty_str(attempt.pending.get("card_message_id"))) async def _resolve_routing_bounded(self, attempt: _RoutingAttempt) -> _Routing | StoreLookupUnresolved: """``_resolve_routing`` under the store deadline; no answer in time (or a store error) is *unresolved*. @@ -1704,10 +1719,11 @@ class FeishuChannel(Channel): logger.warning("[Feishu] channel store call failed for message %s (%s); treating the lookup as unresolved", attempt.parsed.msg_id, exc.__class__.__name__, exc_info=True) return StoreLookupUnresolved(f"channel store error: {exc.__class__.__name__}") - async def _first_stored_topic(self, store: Any, chat_id: str, candidates: list[str]) -> str | None: + async def _first_stored_topic(self, store: Any, route: InboundMessage, candidates: list[str]) -> str | None: """The first candidate topic id the store already maps to a thread, in priority order.""" for candidate in candidates: - if await store.get_thread_id(self.name, chat_id, topic_id=candidate): + route.topic_id = candidate + if await lookup_thread_id(route, repo=self._connection_repo, store=store): return candidate return None @@ -1860,6 +1876,9 @@ class FeishuChannel(Channel): metadata=metadata, ) inbound.topic_id = routing.topic_id + inbound.connection_id = routing.connection_id + inbound.owner_user_id = routing.owner_user_id + inbound.workspace_id = routing.workspace_id if self._is_batchable_file_inbound( msg_type=parsed.msg_type, @@ -1941,14 +1960,15 @@ class FeishuChannel(Channel): def _queue_file_inbound_batch(self, msg_id: str, inbound: InboundMessage) -> bool: key = self._pending_key(inbound.chat_id, inbound.user_id) should_schedule_flush = False - expired_batch: tuple[str, InboundMessage, list[str]] | None = None + previous_batch: tuple[str, InboundMessage, list[str]] | None = None with self._thread_lock: batch = self._pending_inbound_batches.get(key) now = time.time() if batch: - if now - batch["created_at"] <= FEISHU_INBOUND_BATCH_WINDOW_SECONDS: - batched_inbound = batch["inbound"] + batched_inbound = batch["inbound"] + same_binding = (batched_inbound.connection_id, batched_inbound.owner_user_id) == (inbound.connection_id, inbound.owner_user_id) + if same_binding and now - batch["created_at"] <= FEISHU_INBOUND_BATCH_WINDOW_SECONDS: batch["message_ids"].append(msg_id) batch["text_parts"].append(inbound.text) batched_inbound.text = "\n\n".join(part for part in batch["text_parts"] if part) @@ -1964,7 +1984,7 @@ class FeishuChannel(Channel): ) return True - expired_batch = (batch["anchor_message_id"], batch["inbound"], list(batch["message_ids"])) + previous_batch = (batch["anchor_message_id"], batch["inbound"], list(batch["message_ids"])) self._pending_inbound_batches[key] = { "anchor_message_id": msg_id, @@ -1978,9 +1998,9 @@ class FeishuChannel(Channel): if should_schedule_flush: self._schedule_batch_flush(key, msg_id) - if expired_batch: - anchor_message_id, expired_inbound, source_message_ids = expired_batch - self._schedule_prepare_inbound(anchor_message_id, expired_inbound, source_message_ids=source_message_ids) + if previous_batch: + anchor_message_id, previous_inbound, source_message_ids = previous_batch + self._schedule_prepare_inbound(anchor_message_id, previous_inbound, source_message_ids=source_message_ids) return True def _pop_pending_inbound_batch(self, key: tuple[str, str], *, anchor_message_id: str | None = None) -> tuple[str, InboundMessage, list[str]] | None: @@ -2040,12 +2060,11 @@ class FeishuChannel(Channel): """Kick off Feishu side effects without delaying inbound dispatch.""" try: clarification_card_id = inbound.metadata.pop(_PENDING_CARD_METADATA_KEY, None) - inbound = await self._attach_connection_identity(inbound) if self._card_interaction_enabled and not clarification_card_id and inbound.msg_type == InboundMessageType.CHAT: # Ordinary answers retire only the current thread's buttons; # older cards cannot redirect a fresh /new conversation. thread_id = await lookup_thread_id(inbound, repo=self._connection_repo, store=self.config.get("channel_store")) - pending = self._consume_pending_clarification(inbound.chat_id, inbound.user_id, reply_to_ids=[f"feishu-card:{thread_id}"]) if thread_id else None + pending = self._consume_pending_clarification(inbound.chat_id, inbound.user_id, reply_to_ids=[f"feishu-card:{thread_id}"], connection_id=inbound.connection_id, owner_user_id=inbound.owner_user_id) if thread_id else None if pending: clarification_card_id = pending.get("card_message_id") inbound.metadata[RESOLVED_FROM_PENDING_CLARIFICATION_METADATA_KEY] = True @@ -2279,7 +2298,7 @@ class FeishuChannel(Channel): # topic_id determines which LangGraph thread the message maps to. # P2P chats: topic_id=None so all messages share one thread (like Telegram DMs). # But check stored mappings first for backward compatibility with pre-upgrade P2P threads. - if self.config.get("channel_store") is None: + if self.config.get("channel_store") is None and self._connection_repo is None: self._dispatch_inbound(parsed, self._route_without_store(parsed)) return diff --git a/backend/app/channels/manager.py b/backend/app/channels/manager.py index 99c5e8e437..606ae6800f 100644 --- a/backend/app/channels/manager.py +++ b/backend/app/channels/manager.py @@ -30,7 +30,7 @@ from app.channels import buzz_run_policy as _buzz_run_policy # noqa: F401 from app.channels import feishu_run_policy as _feishu_run_policy # noqa: F401 from app.channels.capabilities import CHANNEL_CAPABILITIES from app.channels.commands import KNOWN_CHANNEL_COMMANDS -from app.channels.connection_identity import lookup_thread_id +from app.channels.connection_identity import fallback_store_channel, lookup_thread_id from app.channels.dedupe_store import InboundDedupeStore, MemoryInboundDedupeStore from app.channels.goal_status import goal_reply_text, goal_status_text, is_active_goal_state from app.channels.message_bus import ( @@ -2914,7 +2914,7 @@ class ChannelManager: return await self.store.set_thread_id( - msg.channel_name, + fallback_store_channel(msg.channel_name, msg.topic_id, self._connection_repo), msg.chat_id, thread_id, topic_id=msg.topic_id, @@ -2932,7 +2932,7 @@ class ChannelManager: external_topic_id=msg.topic_id, thread_id=thread_id, ) - return await self.store.claim_thread_id(msg.channel_name, msg.chat_id, thread_id, topic_id=msg.topic_id, user_id=msg.user_id) + return await self.store.claim_thread_id(fallback_store_channel(msg.channel_name, msg.topic_id, self._connection_repo), msg.chat_id, thread_id, topic_id=msg.topic_id, user_id=msg.user_id) def _remember_thread_agent(self, thread_id: str, agent_name: str | None) -> None: if len(self._thread_agent_names) > IN_PROCESS_CACHE_MAX_ENTRIES: diff --git a/backend/app/channels/service.py b/backend/app/channels/service.py index 803fb84645..07e33efee9 100644 --- a/backend/app/channels/service.py +++ b/backend/app/channels/service.py @@ -236,6 +236,7 @@ class ChannelService: # runs this constructor off the loop. self.store: ChannelStore = store if store is not None else resolve_channel_store(app_config) self._connection_repo = connection_repo + self._connections_configured = bool(getattr(getattr(app_config, "channel_connections", None), "enabled", False)) # Language of DeerFlow's own replies (/connect, /goal): the owner's web UI # language, read from the connection repository's database, else # channel_connections.notification_locale (captured here; restart-scoped). @@ -742,6 +743,10 @@ class ChannelService: logger.warning("Refusing to start %s while ChannelService is stopped or stopping", name) return False + if name == "feishu" and self._connections_configured and self._connection_repo is None: + logger.error("Feishu requires an available connection repository when channel connections are enabled") + return False + import_path = _CHANNEL_REGISTRY.get(name) if not import_path: logger.warning("Unknown channel type") diff --git a/backend/docs/IM_CHANNEL_CONNECTIONS.md b/backend/docs/IM_CHANNEL_CONNECTIONS.md index df65fd2cc4..558d8fc60e 100644 --- a/backend/docs/IM_CHANNEL_CONNECTIONS.md +++ b/backend/docs/IM_CHANNEL_CONNECTIONS.md @@ -411,6 +411,18 @@ When `channel_connections.enabled` and `require_bound_identity` are true, auth-e Upgrade note: existing auth-enabled deployments that already have `channel_connections.enabled: true` will start rejecting ordinary unbound IM messages after this field is introduced because `require_bound_identity` defaults to true. Legacy operator-owned/open-bot deployments that intentionally allow unbound platform users to create DeerFlow runs should set `require_bound_identity: false` before upgrading and restart the service. +When channel connections are enabled, Feishu stores topic and card aliases +for bound senders with their connection. After `/new`, ordinary topic messages and +commands follow the new conversation even if an earlier answer finishes streaming. +Replying directly to that earlier card continues its original conversation. Feishu +requires the connection repository to be available before its transport starts. +Unbound chats use a separate topic namespace. +After upgrading a mixed deployment, unbound replies to older topics +start a fresh conversation. Unthreaded chats and legacy-only deployments keep +their existing routing. Upgrade all Gateway workers together. If a previously +mixed deployment switches off channel connections, clear its old Feishu topic +aliases before reopening legacy routing. + ## Connect Flow Every worker answers the bind message in the chat: ` connected to DeerFlow.` on success, otherwise that the code (Telegram: the link) is invalid or expired, or that the bind could not be completed from that message. Replies use the code owner's web UI language once the code is consumed, else `channel_connections.notification_locale` ([reply language](#goal-status-goal)). diff --git a/backend/tests/test_channels.py b/backend/tests/test_channels.py index ad1ea7bde2..db539cb782 100644 --- a/backend/tests/test_channels.py +++ b/backend/tests/test_channels.py @@ -10611,6 +10611,17 @@ class TestChannelService: _run(go()) + def test_feishu_requires_configured_connection_repository_before_start(self, tmp_path, monkeypatch): + from app.channels.service import ChannelService + + config = SimpleNamespace(channel_connections=SimpleNamespace(enabled=True)) + service = ChannelService(app_config=config, store=JsonChannelStore(tmp_path / "store.json")) + service._running = True + loader = MagicMock() + monkeypatch.setattr("deerflow.reflection.resolve_class", loader) + assert _run(service._start_channel("feishu", {})) is False + loader.assert_not_called() + def test_connection_repo_is_forwarded_to_manager(self): from app.channels.service import ChannelService diff --git a/backend/tests/test_feishu_card_delivery.py b/backend/tests/test_feishu_card_delivery.py index 4dfb8a804c..db373b8266 100644 --- a/backend/tests/test_feishu_card_delivery.py +++ b/backend/tests/test_feishu_card_delivery.py @@ -4,6 +4,7 @@ from __future__ import annotations import asyncio import json +from dataclasses import replace from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock from uuid import uuid4 @@ -208,6 +209,9 @@ async def test_consecutive_card_answers_resume_the_same_thread(card_channel, tmp card_channel.bus.subscribe_outbound(deliver) await card_channel.send(message, _max_retries=1) + if bound_identity: + assert await repo.get_thread_id(connection["id"], "chat-1", "source-1") == "thread-1" + assert await store.list_entries() == [] button = sent_button(card_channel) if reset_conversation: command = InboundMessage( @@ -275,6 +279,49 @@ def group_message(message_id: str) -> _ParsedMessage: return _ParsedMessage(chat_id="chat-1", msg_id=message_id, sender_id="ou-originator", root_id=None, parent_id=None, feishu_thread_id=None, chat_type="group", text="Another question", files=[]) +@pytest.mark.asyncio +async def test_bound_text_clarification_keeps_the_connection_alias(card_channel): + message = clarification_outbound() + message.connection_id = "conn-1" + message.owner_user_id = "owner-1" + repo = SimpleNamespace( + find_connection_by_external_identity=AsyncMock(return_value={"id": "conn-1", "owner_user_id": "owner-1"}), + claim_thread_id=AsyncMock(), + get_thread_id=AsyncMock(return_value=None), + ) + card_channel._connection_repo = repo + await card_channel.send(message, _max_retries=1) + repo.claim_thread_id.reset_mock() + + routed = await card_channel._resolve_routing(_RoutingAttempt(group_message("plain-answer"))) + assert routed.from_pending + repo.claim_thread_id.assert_awaited_once_with(connection_id="conn-1", owner_user_id="owner-1", provider="feishu", external_conversation_id="chat-1", external_topic_id=routed.topic_id, thread_id=message.thread_id) + assert await card_channel.config["channel_store"].list_entries() == [] + + +@pytest.mark.asyncio +async def test_unbound_feishu_topic_starts_fresh_after_legacy_alias_and_keeps_new_binding(card_channel, tmp_path): + from app.channels.manager import ChannelManager + from app.channels.store import JsonChannelStore + + store = JsonChannelStore(path=tmp_path / "mixed.json") + await store.set_thread_id("feishu", "chat-1", "pre-upgrade", topic_id="old-topic") + repo = SimpleNamespace(find_connection_by_external_identity=AsyncMock(return_value=None)) + card_channel.config["channel_store"] = store + card_channel._connection_repo = repo + parsed = group_message("new-message") + parsed.root_id = "old-topic" + routing = await card_channel._resolve_routing(_RoutingAttempt(parsed)) + assert not routing.from_stored_mapping + + inbound = InboundMessage(channel_name="feishu", chat_id=parsed.chat_id, user_id=parsed.sender_id, text="Hello", topic_id=routing.topic_id) + manager = ChannelManager(bus=card_channel.bus, store=store, connection_repo=repo) + assert await manager._lookup_thread_id(inbound) is None + assert await manager._claim_thread_id(inbound, "new-thread") == "new-thread" + assert await manager._lookup_thread_id(inbound) == "new-thread" + assert (await card_channel._resolve_routing(_RoutingAttempt(parsed))).from_stored_mapping + + @pytest.mark.asyncio @pytest.mark.parametrize("with_store", [False, True]) @pytest.mark.parametrize("other_pending_card", [False, True]) @@ -459,6 +506,8 @@ async def test_explicit_text_answer_keeps_the_new_conversation_route(card_channe @pytest.mark.parametrize("reset_conversation", [False, True]) @pytest.mark.parametrize("topic_id", [None, "source-1"]) async def test_ordinary_text_uses_current_conversation(card_channel, tmp_path, monkeypatch, bound_identity, reset_conversation, topic_id): + from lark_oapi.api.im.v1 import P2ImMessageReceiveV1 + from app.channels.manager import ChannelManager from deerflow.persistence.channel_connections import ChannelConnectionRepository, ChannelCredentialCipher from deerflow.persistence.engine import close_engine, get_session_factory, init_engine @@ -466,6 +515,28 @@ async def test_ordinary_text_uses_current_conversation(card_channel, tmp_path, m monkeypatch.delenv("DEER_FLOW_AUTH_DISABLED", raising=False) store = card_channel.config["channel_store"] message = clarification_outbound(topic_id=topic_id) + + async def receive(message_id: str, text: str, parent_id: str | None = None) -> InboundMessage: + event = P2ImMessageReceiveV1( + { + "event": { + "sender": {"sender_id": {"open_id": "ou-originator"}}, + "message": { + "message_id": message_id, + "chat_id": message.chat_id, + "chat_type": "group" if topic_id else "p2p", + "root_id": topic_id, + "parent_id": parent_id, + "content": json.dumps({"text": text}), + }, + } + } + ) + await asyncio.to_thread(card_channel._on_message, event) + inbound = await asyncio.wait_for(card_channel.bus.get_inbound(), timeout=2) + card_channel.bus.inbound_task_done() + return inbound + repo = None try: if bound_identity: @@ -492,38 +563,37 @@ async def test_ordinary_text_uses_current_conversation(card_channel, tmp_path, m card_channel.bus.subscribe_outbound(card_channel._on_outbound) await card_channel.send(message, _max_retries=1) old_button = sent_button(card_channel) - command = InboundMessage( - channel_name="feishu", - chat_id="chat-1", - user_id="ou-originator", - text="/new", - msg_type=InboundMessageType.COMMAND, - topic_id=topic_id, - connection_id=message.connection_id, - owner_user_id=message.owner_user_id, - workspace_id="chat-1", - metadata={"user_id": "ou-originator", "topic_id": topic_id}, - ) - if reset_conversation: - await manager._handle_command(command) - parsed = group_message("ordinary-answer") - parsed.chat_type = "group" if topic_id else "p2p" - parsed.root_id = topic_id - parsed.parent_id = "source-new" if topic_id and reset_conversation else None - parsed.text = "Beta" card_channel._main_loop = asyncio.get_running_loop() - card_channel._dispatch_inbound(parsed, await card_channel._resolve_routing(_RoutingAttempt(parsed))) - inbound = await asyncio.wait_for(card_channel.bus.get_inbound(), timeout=2) - card_channel.bus.inbound_task_done() + if reset_conversation: + command = await receive("source-new", "/new") + await manager._handle_command(command) + if bound_identity and topic_id: + late_reply = replace(message, text="Earlier answer", thread_ts="earlier-source", metadata={"user_id": command.user_id, "root_id": topic_id}) + await card_channel.send(late_reply, _max_retries=1) + assert await manager._lookup_thread_id(command) == "thread-after-new" + assert await repo.get_thread_id(connection["id"], "chat-1", "earlier-source") == "thread-1" + inbound = await receive("ordinary-answer", "Beta", parent_id="unknown-parent" if topic_id and reset_conversation else None) + topic = replace(inbound, topic_id=topic_id) await manager._handle_chat(inbound) expected_thread = "thread-after-new" if reset_conversation else "thread-1" assert client.runs.stream.call_args.args[0] == expected_thread - assert await manager._lookup_thread_id(command) == expected_thread + assert await manager._lookup_thread_id(topic) == expected_thread if reset_conversation: old_answer = await click_button(card_channel, old_button) await manager._handle_chat(old_answer) assert client.runs.stream.call_args.args[0] == "thread-1" - assert await manager._lookup_thread_id(command) == "thread-after-new" + assert await manager._lookup_thread_id(topic) == "thread-after-new" + if bound_identity and topic_id: + card_id = "card-earlier-source" + followup = await receive("old-card-followup", "Tell me more", parent_id=card_id) + await manager._handle_chat(followup) + assert client.runs.stream.call_args.args[0] == "thread-1" + assert await manager._lookup_thread_id(topic) == expected_thread + + client.threads.create.return_value = {"thread_id": "next-topic"} + await manager._handle_command(await receive("next-reset", "/new", parent_id=card_id)) + assert await manager._lookup_thread_id(topic) == "next-topic" + assert await repo.get_thread_id(connection["id"], message.chat_id, card_id) == "thread-1" else: event = SimpleNamespace(event=SimpleNamespace(action=SimpleNamespace(value=old_button), operator=SimpleNamespace(open_id="ou-originator"))) assert card_channel._on_card_action(event).toast.type == "warning" diff --git a/backend/tests/test_feishu_parser.py b/backend/tests/test_feishu_parser.py index 5adad39e05..d66e57796c 100644 --- a/backend/tests/test_feishu_parser.py +++ b/backend/tests/test_feishu_parser.py @@ -7,6 +7,7 @@ import time from collections import deque from io import BytesIO from pathlib import Path +from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock import pytest @@ -857,6 +858,29 @@ async def _on_message_from_sdk_loop(channel: FeishuChannel, event) -> float: return await asyncio.to_thread(sdk_thread) +@pytest.mark.asyncio +@pytest.mark.parametrize("bound", [True, False], ids=["connected", "unbound"]) +@pytest.mark.parametrize("with_store", [True, False], ids=["channel-store", "connection-repo-only"]) +async def test_topic_routing_passes_the_resolved_sender_to_the_bus(tmp_path, bound, with_store): + store = JsonChannelStore(path=tmp_path / "routing.json") + bus = MessageBus() + channel = FeishuChannel(bus, {"app_id": "test", "app_secret": "test", "channel_store": store if with_store else None}) + connection = {"id": "conn-1", "owner_user_id": "owner-1", "workspace_id": "chat_1"} if bound else None + lookup = AsyncMock(return_value=connection) + channel._connection_repo = SimpleNamespace(find_connection_by_external_identity=lookup, get_thread_id=AsyncMock(return_value="thread-a")) + await store.set_thread_id("feishu-unbound", "chat_1", "thread-a", topic_id="root", user_id="user_1") + + try: + await _on_message_from_sdk_loop(channel, _make_text_event("hello", message_id="reply", root_id="root")) + inbound = await asyncio.wait_for(bus.get_inbound(), timeout=2) + bus.inbound_task_done() + lookup.assert_awaited_once_with(provider="feishu", external_account_id="user_1", workspace_id="chat_1") + assert inbound.topic_id == "root" + assert (inbound.connection_id, inbound.owner_user_id, inbound.workspace_id) == (("conn-1", "owner-1", "chat_1") if bound else (None, None, None)) + finally: + await channel._close_and_drain_threadsafe_futures() + + class _GatedStore: """A channel store whose database only answers once ``gate`` is set (slow or hung DB).""" @@ -1259,27 +1283,29 @@ def test_feishu_post_with_text_and_top_level_files_extracts_attachments(): assert mock_make_inbound.call_args[1]["files"] == [{"file_key": "file_inv_a"}, {"file_key": "file_inv_b"}, {"file_key": "file_po"}] +@pytest.mark.asyncio @pytest.mark.parametrize("code", ["bind-code", None]) -def test_feishu_post_connect_reads_only_the_caption(monkeypatch, code): - channel = FeishuChannel(MessageBus(), {"app_id": "test", "app_secret": "test", "connection_repo": object()}) - channel._main_loop = MagicMock() - bind = MagicMock() - submit = MagicMock(return_value=True) +async def test_feishu_post_connect_reads_only_the_caption(monkeypatch, code): + repo = SimpleNamespace(find_connection_by_external_identity=AsyncMock(return_value=None)) + channel = FeishuChannel(MessageBus(), {"app_id": "test", "app_secret": "test", "connection_repo": repo}) + bind = AsyncMock() monkeypatch.setattr(channel, "_bind_connection_from_connect_code", bind) - monkeypatch.setattr(channel, "_submit_threadsafe_coroutine", submit) - monkeypatch.setattr(channel, "_schedule_prepare_inbound", MagicMock()) caption = f"@_user_1 /connect {code}" if code else "@_user_1 /connect" event = _make_post_event({"content": [[{"tag": "text", "text": caption}]], "files": [{"file_key": "file_a"}]}) - channel._on_message(event) - - if code: - bind.assert_called_once() - assert bind.call_args.kwargs["code"] == code - submit.assert_called_once() - else: - bind.assert_not_called() - submit.assert_not_called() + try: + await _on_message_from_sdk_loop(channel, event) + if code: + await _eventually(lambda: bind.await_count == 1) + assert bind.await_args.kwargs["code"] == code + assert channel.bus.inbound_queue.empty() + else: + inbound = await asyncio.wait_for(channel.bus.get_inbound(), timeout=2) + channel.bus.inbound_task_done() + assert inbound.files == [{"file_key": "file_a"}] + bind.assert_not_awaited() + finally: + await channel._close_and_drain_threadsafe_futures() @pytest.mark.asyncio @@ -1679,7 +1705,8 @@ def test_feishu_explicit_file_reply_does_not_enter_batch(monkeypatch): _run(go()) -def test_feishu_expired_file_batch_does_not_get_overwritten(monkeypatch): +@pytest.mark.parametrize(("elapsed", "connection_id"), [(1.0, None), (0.1, "new-connection")], ids=["expired", "rebound"]) +def test_feishu_file_batch_flushes_before_a_new_window_or_connection(monkeypatch, elapsed, connection_id): monkeypatch.setattr("app.channels.feishu.FEISHU_INBOUND_BATCH_WINDOW_SECONDS", 0.5) now = 0.0 monkeypatch.setattr("app.channels.feishu.time.time", lambda: now) @@ -1703,11 +1730,13 @@ def test_feishu_expired_file_batch_does_not_get_overwritten(monkeypatch): user_id="user_1", text="[file]", thread_ts="msg_file_2", + connection_id=connection_id, + owner_user_id="owner" if connection_id else None, files=[{"file_key": "file_b"}], ) channel._queue_file_inbound_batch("msg_file_1", first) - now = 1.0 + now = elapsed channel._queue_file_inbound_batch("msg_file_2", second) channel._schedule_prepare_inbound.assert_called_once_with(