The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(feishu): drive-comment turns and WS-thread callbacks run under their own profile, not the launch profile
Teknium2952dc62bc28
diff --git a/plugins/platforms/feishu/adapter.py b/plugins/platforms/feishu/adapter.pyindex eb48876cafb..584eb17b7cf 100644--- a/plugins/platforms/feishu/adapter.py+++ b/plugins/platforms/feishu/adapter.py@@ -21,6 +21,7 @@ from __future__ import annotationsimport asyncioimport collectionsimport concurrent.futures+import contextvarsimport hashlibimport hmacimport itertools@@ -1897,8 +1898,11 @@ class FeishuAdapter(BasePlatformAdapter):loop = self._loopif not self._loop_accepts_callbacks(loop):if self._enqueue_pending_inbound_event(data):+ # Replayed events hop onto the loop from THIS thread's context; keep the WS thread's+ # profile scope (see _connect_websocket) rather than starting from an empty one.threading.Thread(- target=self._drain_pending_inbound_events, name="feishu-pending-inbound-drainer", daemon=True,+ target=contextvars.copy_context().run, args=(self._drain_pending_inbound_events,),+ name="feishu-pending-inbound-drainer", daemon=True,).start()returnself._submit_on_loop(loop, self._handle_message_event_data(data))@@ -3716,7 +3720,14 @@ class FeishuAdapter(BasePlatformAdapter):# Without the "channel" UA tag Feishu won't push group @mention events over WS.extra_ua_tags=["channel"],)- self._ws_future = loop.run_in_executor(None, _run_official_feishu_ws_client, self._ws_client, self)+ # The lark SDK owns this thread and fires every event/card callback on it; those hop back+ # to the adapter loop via run_coroutine_threadsafe, which copies the CALLER's context — so+ # whatever scope the WS thread carries is what pre-handler work (inbound media caching,+ # .update_response marker, reactions env, drive comments) runs under. A bare executor+ # thread has an empty context = launch profile. connect() runs inside the profile scope+ # under multiplex (and the supervisor task inherits it), so snapshot it here.+ self._ws_future = loop.run_in_executor(+ None, contextvars.copy_context().run, _run_official_feishu_ws_client, self._ws_client, self)async def _connect_webhook(self) -> None:if not FEISHU_WEBHOOK_AVAILABLE:diff --git a/plugins/platforms/feishu/feishu_comment.py b/plugins/platforms/feishu/feishu_comment.pyindex 0ddf99b4398..3a2da9cbb2c 100644--- a/plugins/platforms/feishu/feishu_comment.py+++ b/plugins/platforms/feishu/feishu_comment.py@@ -6,6 +6,7 @@ add_whole_comment; local -> reply_to_comment, falling back to add_whole_commentfrom __future__ import annotationsimport asyncio+import contextvarsimport jsonimport loggingimport re@@ -607,7 +608,12 @@ async def handle_drive_comment_event(client: Any, data: Any, *, self_open_id: stlogger.info("[Feishu-Comment] [Step 4/5] Prompt built (%d chars), running agent...", len(prompt))logger.debug("[Feishu-Comment] Full prompt:\n%s", prompt)# run_conversation is synchronous -> thread. Session key groups all comment cards on one doc.- response = await asyncio.get_running_loop().run_in_executor(None, _run_comment_agent, prompt, client, _session_key(file_type, file_token))+ # This turn bypasses the gateway's per-profile message handler, so the only scope it has is the+ # one on this coroutine (the adapter's profile under multiplex). A bare executor thread starts+ # with an EMPTY context: model/credential resolution and the AIAgent would then run under the+ # LAUNCH profile (UnscopedSecretError, or the default profile's config/model/state). Carry it.+ response = await asyncio.get_running_loop().run_in_executor(+ None, contextvars.copy_context().run, _run_comment_agent, prompt, client, _session_key(file_type, file_token))if not response or _NO_REPLY_SENTINEL in response:logger.info("[Feishu-Comment] Agent returned NO_REPLY, skipping delivery")else:diff --git a/tests/gateway/test_feishu_profile_scope_hops.py b/tests/gateway/test_feishu_profile_scope_hops.pynew file mode 100644index 00000000000..5413c8c6591--- /dev/null+++ b/tests/gateway/test_feishu_profile_scope_hops.py@@ -0,0 +1,130 @@+"""Profile scope must survive the Feishu adapter's thread hops under a multiplexed gateway.++The adapter is constructed and connected inside ``_profile_runtime_scope`` (HERMES_HOME override ++secret scope as contextvars). Two hops used to start from an EMPTY context, so the work ran under+the LAUNCH profile: the drive-comment agent turn (a full ``AIAgent`` on a bare default executor)+and the lark WS client thread (every SDK callback, and its ``run_coroutine_threadsafe`` hop back+onto the adapter loop, inherits the WS thread's context). The lark SDK is optional, so a fake+client drives the REAL ``_connect_websocket`` / ``_run_official_feishu_ws_client``.+"""++import asyncio+import sys+import types+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import AsyncMock, patch++import pytest++from agent.secret_scope import (+ UnscopedSecretError,+ get_secret,+ reset_secret_scope,+ set_multiplex_active,+ set_secret_scope,+)+from hermes_constants import get_hermes_home, reset_hermes_home_override, set_hermes_home_override+++def _observe(routed_home: Path) -> tuple:+ try:+ secret = get_secret("FEISHU_PROBE_TOKEN")+ except UnscopedSecretError:+ secret = "<unscoped>"+ return ("routed" if Path(get_hermes_home()) == routed_home else "launch", secret)+++def routed_scope(tmp_path):+ """Enter a secondary profile's scope the way gateway/run.py::_profile_runtime_scope does."""+ routed_home = tmp_path / "profiles" / "b"+ routed_home.mkdir(parents=True)+ set_multiplex_active(True)+ home_token = set_hermes_home_override(str(routed_home))+ secret_token = set_secret_scope({"FEISHU_PROBE_TOKEN": "routed-value"})+ try:+ yield routed_home+ finally:+ reset_secret_scope(secret_token)+ reset_hermes_home_override(home_token)+ set_multiplex_active(False)+++def test_drive_comment_agent_turn_runs_under_the_adapter_profile_scope(routed_scope):+ """The comment agent thread must resolve model/credentials/home for the routed profile,+ not the launch profile (bare run_in_executor drops the contextvar scope)."""+ from plugins.platforms.feishu import feishu_comment as fc+ from plugins.platforms.feishu import feishu_comment_rules as rules++ seen = {}++ def _fake_agent(prompt, client, session_key=""):+ seen["turn"] = _observe(routed_scope)+ return "NO_REPLY"++ event = SimpleNamespace(event={+ "comment_id": "c1", "reply_id": "", "is_mentioned": True, "timestamp": "1",+ "notice_meta": {"file_token": "docx_t", "file_type": "docx", "notice_type": "add_reply",+ "from_user_id": {"open_id": "ou_user"}, "to_user_id": {"open_id": "ou_bot"}},+ })+ with patch.object(rules, "load_config", return_value=object()), \+ patch.object(rules, "resolve_rule", return_value=rules.ResolvedCommentRule(True, "allowlist", frozenset(), "top")), \+ patch.object(rules, "has_wiki_keys", return_value=False), \+ patch.object(rules, "is_user_allowed", return_value=True), \+ patch.object(fc, "query_document_meta", AsyncMock(return_value={"title": "T", "url": "u"})), \+ patch.object(fc, "batch_query_comment", AsyncMock(return_value={"is_whole": False, "quote": ""})), \+ patch.object(fc, "_local_comment_prompt", AsyncMock(return_value="prompt")), \+ patch.object(fc, "_run_comment_agent", _fake_agent):+ asyncio.run(fc.handle_drive_comment_event(object(), event, self_open_id="ou_bot"))++ assert seen["turn"] == ("routed", "routed-value")+++def test_ws_client_thread_and_its_loop_callbacks_carry_the_adapter_profile_scope(routed_scope, monkeypatch):+ """Lark SDK callbacks run on the WS thread and re-enter the adapter loop through+ run_coroutine_threadsafe (which copies the caller's context): both must see the profile that+ connected the adapter, so media caching / markers / env reads before handle_message stay in it."""+ from plugins.platforms.feishu import adapter as fa++ client_mod = types.ModuleType("lark_oapi.ws.client")+ client_mod.loop = SimpleNamespace(name="sdk-default-loop")+ client_mod.websockets = SimpleNamespace(connect=lambda *a, **k: None)+ lark_ws = types.ModuleType("lark_oapi.ws")+ lark_ws.client = client_mod+ lark = types.ModuleType("lark_oapi")+ lark.ws = lark_ws+ for name, mod in (("lark_oapi", lark), ("lark_oapi.ws", lark_ws), ("lark_oapi.ws.client", client_mod)):+ monkeypatch.setitem(sys.modules, name, mod)+ monkeypatch.setattr(fa, "_WS_ISOLATION_INSTALLED", False)+ monkeypatch.setattr(fa, "FEISHU_WEBSOCKET_AVAILABLE", True)+ monkeypatch.setattr(fa, "lark", SimpleNamespace(LogLevel=SimpleNamespace(INFO=1)))++ seen = {}++ async def scenario():+ adapter_loop = asyncio.get_running_loop()++ async def _on_loop():+ return _observe(routed_scope)++ class FakeWSClient:+ def __init__(self, **kwargs):+ pass++ def start(self): # the SDK-owned thread every lark callback fires on+ seen["ws_thread"] = _observe(routed_scope)+ seen["loop_callback"] = asyncio.run_coroutine_threadsafe(_on_loop(), adapter_loop).result(5)++ monkeypatch.setattr(fa, "FeishuWSClient", FakeWSClient)+ stub = SimpleNamespace(+ _loop=adapter_loop, _app_id="cli_x", _app_secret="s", _domain_name="feishu", _event_handler=None,+ _ws_thread_loop=None, _ws_reconnect_nonce=None, _ws_reconnect_interval=None,+ _ws_ping_interval=None, _ws_ping_timeout=None, _ws_client=None, _ws_future=None,+ _prepare_client=lambda: "feishu-domain", _hydrate_bot_identity=AsyncMock(),+ )+ await fa.FeishuAdapter._connect_websocket(stub)+ await stub._ws_future++ asyncio.run(scenario())+ assert seen == {"ws_thread": ("routed", "routed-value"), "loop_callback": ("routed", "routed-value")}