deer-flow/backend/tests/test_channel_hidden_human_input.py
Storm 3f7a076972
feat(channels): Feishu interactive clarification cards (#6670)
* feat(channels): render Feishu option clarifications as button cards

When the agent's ask_clarification carries options, the Feishu channel
now renders the question as an interactive card with one button per
option instead of plain text. This is the outbound half: card
construction plus a process-local pending registry that a later
card-action callback handler will validate clicks against.

- New feishu_card_interaction module owns request extraction, button
  card rendering, and the pending registry (30-minute TTL, matching the
  typed-reply clarification window)
- Manager attaches the clarification's structured human_input payload to
  the final outbound's metadata so channels can render richer
  affordances without touching the Gateway protocol
- Feishu channel renders the button card only when
  card_interaction_enabled is set (default off); free-text, form, and
  over-four-option clarifications keep the plain-text path
- Button cards bypass the markdown wrapper via a raw_card_content flag
  on the card send/patch helpers; plain-text call signatures unchanged

* feat(channels): close the Feishu button-card click loop

The inbound half of interactive clarification cards: a click on an
option button validates, resolves the clarification, and marks the
card in place.

- Register the card-action callback only when card_interaction_enabled
  is set; clicks arrive as WS EVENT frames through the SDK's callback
  processor map, and the synchronous return value becomes the toast ack
- consume_if_originator atomically validates operator identity against
  the pending entry: non-originators get a refusal toast and the entry
  survives; unknown or expired requests are toast-only and dropped
- A validated click consumes once, updates the card to a terminal
  resolved state, and injects a hidden inbound carrying the
  human_input_response so the run resumes on the originating thread
  with Web-card parity
- Manager translates the inbound's human_input_response metadata into
  the human message's additional_kwargs with hide_from_ui set

* docs(channels): document Feishu interactive clarification cards

- README / README_zh: optional card_interaction_enabled setup, calling
  out that card.action.trigger lives under the console's callback
  configuration tab (separate from event subscriptions) and requires
  publishing a new app version
- config.example.yaml: commented flag with the same console caveat
- backend/AGENTS.md: module ownership note for feishu_card_interaction

* fix(channels): close Feishu card-click routing and ack gaps from review

Address review on #6670:

- Carry the routing identity (topic_id, connection_id, owner_user_id)
  on the pending entry and the synthetic inbound, so clicks resolve to
  the clarified thread in topic-scoped chats and pass bound-identity
  admission instead of opening a new thread or being rejected
- Validate option_value against the registered options at consume time:
  an unknown value is treated like a stale card and the entry is kept
- Return a warning toast when a click cannot be dispatched, and flip
  the card to its resolved state only after the inbound is durably in
  the bus — never display a choice that was not recorded
- Drop the dead mark_sent/consume registry APIs and pass the payload's
  own option ids through to the buttons
- Add an end-to-end test through the manager's thread resolution
  pinning that a card answer reuses the clarified thread

* fix(channels): carry workspace_id on the Feishu card-click inbound

The connections-enabled admission path re-reads the binding with the
message's workspace_id, and Feishu connections are bound with
workspace_id = chat_id. The synthetic inbound set connection_id and
owner_user_id but never workspace_id, so the re-read missed and every
click was rejected as unbound after the entry was consumed.

- Set inbound.workspace_id from the entry's chat_id (Feishu's
  chat-as-workspace binding convention)
- Extend the card-click e2e to require_bound_identity=True, driven
  through the channel's real _resolve_card_click production

* fix(channels): stabilize Feishu clarification delivery and routing

Option cards could fail through the real reply SDK, resume another conversation,
or leave a stale text hint after the answer was accepted.

Unify raw-card delivery and persist trusted thread aliases before showing buttons.
Keep protocol request IDs separate from bounded, one-time callback tokens; validate
originators and option pairs, and retire only the accepted card's text/button state.
Treat valid hidden human answers as turn boundaries so old replies and artifacts
do not leak into the next answer. Cover consecutive clarifications and /new routing
through real SDK request models, stores, and the run journal.

Validation: 147 focused tests and 29,421 offline tests passed (405 skipped);
strict blocking-I/O passed 245 tests (1 skipped). Ruff and guidance checks passed.

* fix(channels): preserve clarification context in Feishu cards

Button cards replaced the full clarification text but omitted its background,
leaving users without the context needed to choose an option.

Carry optional context from request metadata and render its original Markdown
before the question. Keep question-only cards for absent, blank, or invalid context.
Cover rendering and all real SDK delivery paths, and update both user guides.

Validation: 156 focused tests, 245 strict blocking-I/O tests, Ruff, and guidance
checks passed. The offline run recorded 29,381 passed, 49 failed, and 405 skipped;
48 import failures reproduced before the fix. All 49 cases passed on both versions
in isolated environments, and the Feishu-to-export order check passed 13 tests.
2026-10-11 23:58:54 +08:00

132 lines
5.4 KiB
Python

"""Hidden user answers form turn boundaries; internal control messages do not."""
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from app.channels.manager import ChannelManager, _extract_artifacts, _extract_response_text
from app.channels.message_bus import HUMAN_INPUT_RESPONSE_METADATA_KEY, InboundMessage, MessageBus
from app.channels.store import JsonChannelStore
def _hidden_answer() -> dict:
return {
"type": "human",
"content": "Alpha",
"additional_kwargs": {
"hide_from_ui": True,
"human_input_response": {
"version": 1,
"kind": "human_input_response",
"source": "ask_clarification",
"request_id": "clarification:call-1",
"response_kind": "option",
"option_id": "alpha",
"value": "Alpha",
},
},
}
def test_hidden_answer_stops_previous_clarification_text():
result = {
"messages": [
{"type": "human", "content": "Original question"},
{"type": "tool", "name": "ask_clarification", "content": "Pick one"},
_hidden_answer(),
]
}
assert _extract_response_text(result) == ""
def _file_response(content: str, path: str) -> dict:
return {"type": "ai", "content": content, "tool_calls": [{"name": "present_files", "args": {"filepaths": [path]}}]}
@pytest.mark.parametrize("response_kind", ["option", "text"])
def test_hidden_answer_stops_previous_response_and_artifacts(response_kind):
answer = _hidden_answer()
response = answer["additional_kwargs"][HUMAN_INPUT_RESPONSE_METADATA_KEY]
response["response_kind"] = response_kind
if response_kind == "text":
response.pop("option_id")
result = {"messages": [{"type": "human", "content": "Original question"}, _file_response("Previous answer", "/old.txt"), answer], "artifacts": ["/old.txt"]}
assert _extract_response_text(result) == ""
assert _extract_artifacts(result) == []
def test_hidden_answer_keeps_current_response_and_artifacts():
result = {
"messages": [
{"type": "human", "content": "Original question"},
_file_response("Previous answer", "/old.txt"),
_hidden_answer(),
_file_response("Current answer", "/new.txt"),
{"type": "human", "content": "Internal context", "additional_kwargs": {"hide_from_ui": True}},
]
}
assert _extract_response_text(result) == "Current answer"
assert _extract_artifacts(result) == ["/new.txt"]
@pytest.mark.parametrize("invalid_response", [None, {}, "invalid", {"version": 2}, {"option_id": ""}, {"value": " "}])
def test_invalid_hidden_answer_remains_a_control_message(invalid_response):
hidden = _hidden_answer()
if invalid_response is None:
hidden["additional_kwargs"].pop(HUMAN_INPUT_RESPONSE_METADATA_KEY)
elif isinstance(invalid_response, dict):
hidden["additional_kwargs"][HUMAN_INPUT_RESPONSE_METADATA_KEY].update(invalid_response)
if not invalid_response:
hidden["additional_kwargs"][HUMAN_INPUT_RESPONSE_METADATA_KEY] = {}
else:
hidden["additional_kwargs"][HUMAN_INPUT_RESPONSE_METADATA_KEY] = invalid_response
result = {"messages": [{"type": "human", "content": "Current question"}, _file_response("Current answer", "/current.txt"), hidden]}
assert _extract_response_text(result) == "Current answer"
assert _extract_artifacts(result) == ["/current.txt"]
@pytest.mark.asyncio
@pytest.mark.parametrize("failed", [False, True])
async def test_card_answer_without_fresh_ai_preserves_terminal_result(tmp_path, monkeypatch, failed):
monkeypatch.delenv("DEER_FLOW_AUTH_DISABLED", raising=False)
bus = MessageBus()
store = JsonChannelStore(path=tmp_path / "routing.json")
await store.set_thread_id("feishu", "chat-1", "thread-1", topic_id="topic-1")
manager = ChannelManager(bus=bus, store=store)
inbound = InboundMessage(
channel_name="feishu", chat_id="chat-1", user_id="ou-originator", topic_id="topic-1", text="Alpha", metadata={HUMAN_INPUT_RESPONSE_METADATA_KEY: _hidden_answer()["additional_kwargs"][HUMAN_INPUT_RESPONSE_METADATA_KEY]}
)
client = MagicMock()
client.threads.get = AsyncMock(return_value={"thread_id": "thread-1"})
client.threads.update = AsyncMock(return_value={"thread_id": "thread-1"})
async def stream(*args, **kwargs):
answer = dict(kwargs["input"]["messages"][0], type="human")
yield SimpleNamespace(
event="values",
data={"messages": [{"type": "human", "content": "Original question"}, _file_response("Previous answer", "/old.txt"), {"type": "tool", "name": "ask_clarification", "content": "Pick one"}, answer], "artifacts": ["/old.txt"]},
)
if failed:
yield SimpleNamespace(event="error", data={"name": "ModelError", "message": "offline failure"})
client.runs.stream = MagicMock(side_effect=stream)
manager._client = client
outbound = []
async def capture(message):
outbound.append(message)
bus.subscribe_outbound(capture)
await manager._handle_chat(inbound)
assert len(outbound) == 1
assert outbound[0].is_final is True
assert outbound[0].text == ("An error occurred while processing your request. Please try again." if failed else "(No response from agent)")
assert outbound[0].artifacts == []
assert outbound[0].attachments == []