mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-11-27 19:22:05 +08:00
feat(OASlackBridge): post user details in the takeover thread (#2914)
After the Slack root message, reply in its thread with the user's full OpenID, session ID, Official Account bot, message count, first contact time and the most recent user/AI messages (history_messages, default 10, max 50). Data comes from the read-only monitoring.messages Workspace operation, now declared; without the grant the details fall back to the basic fields with a hint. Never blocks the takeover. Toggle with send_user_details. Bump to 0.4.0. Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: multica-agent <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
multica-agent
parent
e18195bc7c
commit
63ac89a5f1
@@ -232,7 +232,7 @@
|
||||
},
|
||||
{
|
||||
"id": "langbot-team/OASlackBridge",
|
||||
"version": "0.3.0",
|
||||
"version": "0.4.0",
|
||||
"category": "misc",
|
||||
"path": "misc/OASlackBridge",
|
||||
"repository": "https://github.com/langbot-app/LangBot/tree/master/plugins/misc/OASlackBridge"
|
||||
|
||||
@@ -7,9 +7,10 @@ Hand off WeChat Official Account conversations from the AI to human agents in Sl
|
||||
1. A WeChat user sends a message containing a keyword (for example 转人工). The AI stops replying.
|
||||
2. The user receives a notice: "已为您转接人工客服,请稍候,客服会在这里回复您。" (You are being connected to a human agent.)
|
||||
3. A "📩 Official Account takeover" message appears in Slack with the (masked) user, the matched keyword and the original text.
|
||||
4. Further messages from the user during the takeover are added to that message's thread.
|
||||
5. Staff reply in the thread; the user receives the reply in WeChat and the thread shows ✅.
|
||||
6. Staff send `!close` in the thread. The user receives "人工客服已结束本次服务,后续将由 AI 助手继续为您解答。" (The human session has ended; the AI assistant will continue.) and the AI takes over again.
|
||||
4. Right below it, the thread gets a "👤 User details" reply: full OpenID, session ID, message count, first contact time and the most recent user/AI messages, so staff have the context.
|
||||
5. Further messages from the user during the takeover are added to that message's thread.
|
||||
6. Staff reply in the thread; the user receives the reply in WeChat and the thread shows ✅.
|
||||
7. Staff send `!close` in the thread. The user receives "人工客服已结束本次服务,后续将由 AI 助手继续为您解答。" (The human session has ended; the AI assistant will continue.) and the AI takes over again.
|
||||
|
||||
Both user notices can be changed or turned off in the plugin configuration.
|
||||
|
||||
@@ -52,7 +53,12 @@ Both user notices can be changed or turned off in the plugin configuration.
|
||||
### Step 4: Install the plugin and confirm permissions
|
||||
|
||||
1. Install this plugin.
|
||||
2. On the plugin detail page, **confirm the permissions** `bot.message.send` (send messages to the WeChat user and to Slack) and `storage.plugin` (store takeover sessions). The plugin does nothing until they are confirmed.
|
||||
2. On the plugin detail page, **confirm the permissions**:
|
||||
- `bot.message.send`: send messages to the WeChat user and to Slack;
|
||||
- `storage.plugin`: store takeover sessions;
|
||||
- `monitoring.messages` (read-only message history): message count, first contact time and recent conversation in the user details.
|
||||
|
||||
The plugin does nothing until the first two are confirmed. Without the third, user details contain only the OpenID and basic info, plus a hint to confirm the permission.
|
||||
|
||||
### Step 5: Fill in the plugin configuration
|
||||
|
||||
@@ -65,6 +71,8 @@ Both user notices can be changed or turned off in the plugin configuration.
|
||||
| Case-sensitive matching | Off by default |
|
||||
| Takeover duration (minutes) | How long after the user's latest message the takeover ends on its own. Default 60; every user message restarts the timer |
|
||||
| Forward follow-up messages | On by default. When off, the AI still stays quiet during the takeover, but follow-up messages are not posted to Slack |
|
||||
| Post user details in the thread | On by default. Replies in the takeover thread with user details |
|
||||
| Recent messages in user details | Default 10, up to 50; 0 posts only the basic info, without conversation |
|
||||
| Notice to the user when takeover starts | Default "已为您转接人工客服,请稍候,客服会在这里回复您。"; leave empty to disable |
|
||||
| Notice to the user when takeover ends | Default "人工客服已结束本次服务,后续将由 AI 助手继续为您解答。"; leave empty to disable |
|
||||
|
||||
@@ -123,6 +131,8 @@ An ongoing takeover ends when the user next writes; the user has to send a keywo
|
||||
- The plugin does not queue or retry sends, so users never get duplicates; a ❌ receipt in the thread is the source of truth.
|
||||
- Customer messages stay in Slack; set channel membership and retention to match your organization's policy.
|
||||
- The plugin stores only the user ↔ Slack thread mapping, not chat history. Replies to an existing thread still work after a plugin restart.
|
||||
- The conversation in "User details" comes from LangBot's message records and is posted to Slack; make sure that fits your data policy, or turn it off / set the count to 0.
|
||||
- WeChat no longer gives Official Accounts the user's nickname or avatar, so users are identified by OpenID.
|
||||
|
||||
## For developers
|
||||
|
||||
|
||||
@@ -68,6 +68,44 @@ DEFAULT_START_NOTICE = "已为您转接人工客服,请稍候,客服会在
|
||||
DEFAULT_END_NOTICE = "人工客服已结束本次服务,后续将由 AI 助手继续为您解答。"
|
||||
|
||||
|
||||
COMPONENT_LABELS = {
|
||||
"Image": "[图片 / Image]", "Voice": "[语音 / Voice]", "File": "[文件 / File]",
|
||||
"Face": "[表情 / Sticker]", "Forward": "[转发 / Forward]",
|
||||
}
|
||||
MAX_HISTORY_MESSAGES = 50
|
||||
MAX_HISTORY_CHARS = 300
|
||||
|
||||
|
||||
def stored_text(content) -> str:
|
||||
"""Render a monitoring message_content (JSON message chain) as one line of plain text."""
|
||||
try:
|
||||
parts = json.loads(content) if isinstance(content, str) else content
|
||||
except ValueError:
|
||||
return str(content)
|
||||
if not isinstance(parts, list):
|
||||
return str(parts)
|
||||
rendered = []
|
||||
for part in parts:
|
||||
if not isinstance(part, dict) or part.get("type") in ("Source", "Quote"):
|
||||
continue
|
||||
if part.get("type") == "Plain":
|
||||
rendered.append(str(part.get("text", "")))
|
||||
else:
|
||||
rendered.append(COMPONENT_LABELS.get(part.get("type"), f"[{part.get('type')}]"))
|
||||
text = " ".join("".join(rendered).split())
|
||||
return text if len(text) <= MAX_HISTORY_CHARS else text[:MAX_HISTORY_CHARS] + "…"
|
||||
|
||||
|
||||
def utc_label(timestamp) -> str:
|
||||
try:
|
||||
moment = datetime.fromisoformat(str(timestamp))
|
||||
except ValueError:
|
||||
return str(timestamp)
|
||||
if moment.tzinfo is None:
|
||||
moment = moment.replace(tzinfo=UTC)
|
||||
return moment.astimezone(UTC).strftime("%Y-%m-%d %H:%M")
|
||||
|
||||
|
||||
def permission_notice(capability: str) -> str:
|
||||
return f"❌ 缺少权限 / Permission denied: {capability}. 请成员确认插件权限 / Ask a member to confirm plugin permissions."
|
||||
|
||||
@@ -131,6 +169,77 @@ class OASlackBridge(BasePlugin):
|
||||
return f"⚠️ 未能向用户发送接管{label}提示 / Failed to send the {kind} notice: {send_error(error)}"
|
||||
return ""
|
||||
|
||||
async def query_messages(self, bot: str, session_id: str, limit: int, offset: int = 0):
|
||||
"""Read the user's processed messages (newest first); returns (rows, total) or an error string."""
|
||||
try:
|
||||
response = await self.workspace.monitoring.messages(
|
||||
bot_ids=[bot], session_ids=[session_id], limit=limit, offset=offset,
|
||||
)
|
||||
except Exception as error:
|
||||
return None, "permission_denied" if permission_denied(error) else type(error).__name__
|
||||
if not isinstance(response, dict) or not response.get("ok"):
|
||||
if "permission_denied" in str(response):
|
||||
return None, "permission_denied"
|
||||
code = (response.get("error") or {}).get("code", "error") if isinstance(response, dict) else "error"
|
||||
return None, str(code)
|
||||
rows, total = (list(response.get("result") or []) + [[], 0])[:2]
|
||||
return (rows if isinstance(rows, list) else [], int(total or 0)), ""
|
||||
|
||||
async def user_details(self, config: dict, session: dict, matched: str) -> str:
|
||||
"""Build the user details posted into a new takeover thread."""
|
||||
openid = session["openid"]
|
||||
session_id = f"person_{openid}"
|
||||
expires = datetime.fromtimestamp(session["expires_at"], UTC).strftime("%Y-%m-%d %H:%M")
|
||||
lines = [
|
||||
"👤 用户详情 / User details",
|
||||
f"• OpenID: `{slack_text(openid)}`",
|
||||
f"• 会话 / Session: `{slack_text(session_id)}`",
|
||||
f"• 触发关键词 / Keyword: {slack_text(matched)}",
|
||||
f"• 接管至 / Takeover until (UTC): {expires}",
|
||||
]
|
||||
try:
|
||||
history = min(MAX_HISTORY_MESSAGES, max(0, int(config.get("history_messages", 10))))
|
||||
except (TypeError, ValueError):
|
||||
history = 10
|
||||
page, error = await self.query_messages(session["oa_bot"], session_id, max(history, 1))
|
||||
if error:
|
||||
reason = (
|
||||
"需在插件详情页确认 monitoring.messages 权限 / confirm the monitoring.messages permission"
|
||||
if error == "permission_denied" else f"查询失败 / query failed ({slack_text(error)})"
|
||||
)
|
||||
lines.append(f"• 历史记录不可用 / History unavailable: {reason}")
|
||||
return "\n".join(lines)
|
||||
rows, total = page
|
||||
first_seen = rows[-1].get("timestamp") if rows else None
|
||||
if total > len(rows):
|
||||
oldest, _ = await self.query_messages(session["oa_bot"], session_id, 1, total - 1)
|
||||
if oldest and oldest[0]:
|
||||
first_seen = oldest[0][0].get("timestamp")
|
||||
bot_name = next((row.get("bot_name") for row in rows if row.get("bot_name")), "")
|
||||
if bot_name:
|
||||
lines.insert(1, f"• 公众号 Bot / Official Account bot: {slack_text(str(bot_name))}")
|
||||
lines.append(f"• 历史消息数 / Messages so far: {total}")
|
||||
if first_seen:
|
||||
lines.append(f"• 首次联系 / First contact (UTC): {utc_label(first_seen)}")
|
||||
if history and rows:
|
||||
lines.append("")
|
||||
lines.append(f"最近 {min(history, len(rows))} 条对话 / Recent conversation (UTC):")
|
||||
for row in reversed(rows[:history]):
|
||||
who = "用户 / User" if row.get("role") == "user" else "AI / Bot"
|
||||
body = stored_text(row.get("message_content")) or "[空 / empty]"
|
||||
lines.append(f"[{utc_label(row.get('timestamp'))}] {who}: {slack_text(body)}")
|
||||
return "\n".join(lines)
|
||||
|
||||
async def post_user_details(self, config: dict, session: dict, matched: str):
|
||||
if not config.get("send_user_details", True):
|
||||
return
|
||||
try:
|
||||
details = await self.user_details(config, session, matched)
|
||||
except Exception as error:
|
||||
logging.getLogger(__name__).warning("OASlackBridge user details failed: %s", type(error).__name__)
|
||||
return
|
||||
await self.warn_in_thread(config, session, details)
|
||||
|
||||
async def warn_in_thread(self, config: dict, session: dict, warning: str):
|
||||
if not warning:
|
||||
return
|
||||
@@ -214,6 +323,7 @@ class OASlackBridge(BasePlugin):
|
||||
await self.save(key, session)
|
||||
await self.save(self.thread_key(session), {"session_key": key})
|
||||
if new_session:
|
||||
await self.post_user_details(config, session, matched)
|
||||
await self.warn_in_thread(config, session, await self.notify_user(config, session, "start"))
|
||||
elif config.get("forward_followups", True):
|
||||
await self.to_slack(config, slack_text(text) or "[非文本消息 / Non-text message]", session["thread"])
|
||||
|
||||
@@ -4,7 +4,7 @@ metadata:
|
||||
author: langbot-team
|
||||
name: OASlackBridge
|
||||
repository: https://github.com/langbot-app/LangBot/tree/master/plugins/misc/OASlackBridge
|
||||
version: 0.3.0
|
||||
version: 0.4.0
|
||||
description:
|
||||
en_US: Forward Official Account keyword messages to Slack and reply from threads.
|
||||
zh_Hans: 公众号关键词消息转发 Slack,员工在 thread 内回复用户。
|
||||
@@ -27,7 +27,8 @@ metadata:
|
||||
spec:
|
||||
permissions:
|
||||
capabilities: [bot.message.send, storage.plugin]
|
||||
workspace_operations: []
|
||||
workspace_operations:
|
||||
- monitoring.messages
|
||||
config:
|
||||
- name: oa_bot
|
||||
type: bot-selector
|
||||
@@ -71,6 +72,24 @@ spec:
|
||||
label:
|
||||
en_US: Forward follow-up messages
|
||||
zh_Hans: 转发接管期间的后续消息
|
||||
- name: send_user_details
|
||||
type: boolean
|
||||
default: true
|
||||
label:
|
||||
en_US: Post user details in the thread
|
||||
zh_Hans: 在 thread 中发送用户详情
|
||||
description:
|
||||
en_US: After the Slack takeover message, reply in its thread with the user's OpenID, message count, first contact time and recent conversation.
|
||||
zh_Hans: 创建 Slack 通知后,在其 thread 中发送用户的 OpenID、历史消息数、首次联系时间和最近对话。
|
||||
- name: history_messages
|
||||
type: integer
|
||||
default: 10
|
||||
label:
|
||||
en_US: Recent messages in user details
|
||||
zh_Hans: 用户详情中的最近对话条数
|
||||
description:
|
||||
en_US: How many recent messages (user and AI) to include, up to 50. 0 omits the conversation.
|
||||
zh_Hans: 附带最近多少条对话(含用户和 AI),最多 50;0 表示不附带对话。
|
||||
- name: start_notice
|
||||
type: string
|
||||
default: "已为您转接人工客服,请稍候,客服会在这里回复您。"
|
||||
|
||||
@@ -7,9 +7,10 @@
|
||||
1. 公众号用户发送含关键词的消息(例如「转人工」),AI 停止回复。
|
||||
2. 用户收到提示:「已为您转接人工客服,请稍候,客服会在这里回复您。」
|
||||
3. Slack 频道出现一条「📩 公众号人工接管」通知,包含用户(已脱敏)、命中的关键词和原文。
|
||||
4. 用户在接管期间继续发的消息,会追加到这条通知的 thread 里。
|
||||
5. 员工在 thread 里回复,用户在公众号里收到;回复成功后 thread 里会出现 ✅。
|
||||
6. 员工在 thread 里发 `!close` 结束接管,用户收到「人工客服已结束本次服务,后续将由 AI 助手继续为您解答。」,之后恢复 AI 回复。
|
||||
4. 通知的 thread 里紧接着出现一条「👤 用户详情」:完整 OpenID、会话 ID、历史消息数、首次联系时间,以及最近若干条用户与 AI 的对话,方便员工了解上下文。
|
||||
5. 用户在接管期间继续发的消息,会追加到这条通知的 thread 里。
|
||||
6. 员工在 thread 里回复,用户在公众号里收到;回复成功后 thread 里会出现 ✅。
|
||||
7. 员工在 thread 里发 `!close` 结束接管,用户收到「人工客服已结束本次服务,后续将由 AI 助手继续为您解答。」,之后恢复 AI 回复。
|
||||
|
||||
两条给用户的提示文案都可以在插件配置里修改或关闭。
|
||||
|
||||
@@ -52,7 +53,12 @@
|
||||
### 第 4 步:安装插件并确认权限
|
||||
|
||||
1. 安装本插件。
|
||||
2. 在插件详情页**确认权限**:`bot.message.send`(给公众号用户和 Slack 发消息)和 `storage.plugin`(保存接管会话)。不确认的话插件不会工作。
|
||||
2. 在插件详情页**确认权限**:
|
||||
- `bot.message.send`:给公众号用户和 Slack 发消息;
|
||||
- `storage.plugin`:保存接管会话;
|
||||
- `monitoring.messages`(消息历史查询,只读):生成「用户详情」里的历史消息数、首次联系时间和最近对话。
|
||||
|
||||
前两项不确认的话插件不会工作;只缺第三项时,用户详情里只有 OpenID 等基本信息,并提示确认权限。
|
||||
|
||||
### 第 5 步:填写插件配置
|
||||
|
||||
@@ -67,6 +73,8 @@
|
||||
| 区分大小写 | 关键词是否区分大小写,默认否 |
|
||||
| 接管时长(分钟) | 用户最后一次发言后多久自动结束接管,默认 60。用户每发一条都会重新计时 |
|
||||
| 转发接管期间的后续消息 | 默认开启。关闭后接管期间仍不回复 AI,但不把用户后续消息转到 Slack |
|
||||
| 在 thread 中发送用户详情 | 默认开启。创建 Slack 通知后在其 thread 里发送用户详情 |
|
||||
| 用户详情中的最近对话条数 | 默认 10,最多 50;填 0 则只发基本信息、不附带对话 |
|
||||
| 进入人工时发给用户的提示 | 默认「已为您转接人工客服,请稍候,客服会在这里回复您。」,留空则不发 |
|
||||
| 退出人工时发给用户的提示 | 默认「人工客服已结束本次服务,后续将由 AI 助手继续为您解答。」,留空则不发 |
|
||||
|
||||
@@ -125,6 +133,8 @@
|
||||
- 插件不排队、不自动重发,避免用户收到重复消息;发送失败时以 thread 里的 ❌ 为准。
|
||||
- 客户的消息内容会保留在 Slack 里,请按公司要求设置频道成员和消息保留策略。
|
||||
- 插件只保存「用户 ↔ Slack thread」的对应关系,不保存聊天记录;插件重启后仍可继续在原 thread 回复。
|
||||
- 「用户详情」里的对话来自 LangBot 的消息记录,会被发到 Slack 频道,请确认这符合你的数据管理要求;不需要时可以关闭或把条数设为 0。
|
||||
- 微信已不再向公众号提供用户昵称和头像,所以用户详情里以 OpenID 标识用户。
|
||||
|
||||
## 给开发者
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ CONFIG = {
|
||||
"keywords": ["help", "人工"], "case_sensitive": False,
|
||||
"takeover_minutes": 60, "forward_followups": True,
|
||||
# Notices are covered by their own tests; keep the original message counts here.
|
||||
"start_notice": "", "end_notice": "",
|
||||
"start_notice": "", "end_notice": "", "send_user_details": False,
|
||||
}
|
||||
NOTICES = {**CONFIG, "start_notice": "start-notice", "end_notice": "end-notice"}
|
||||
OPENID = "openid-complete-value-12345"
|
||||
@@ -51,6 +51,9 @@ class Host:
|
||||
self.sent = []
|
||||
self.failure = None
|
||||
self.root_result = {"message_id": "1234.000001"}
|
||||
self.history = []
|
||||
self.operations = []
|
||||
self.operation_response = None
|
||||
|
||||
async def call_action(self, action, data, *args, **kwargs):
|
||||
if action == getattr(self, "denied_action", None):
|
||||
@@ -62,6 +65,13 @@ class Host:
|
||||
data = {"bot_uuid": data["bot_uuid"], "target_type": data["params"]["target_type"],
|
||||
"target_id": data["params"]["target_id"], "message_chain": data["params"]["message"]}
|
||||
action = Action.SEND_MESSAGE
|
||||
if action == Action.CALL_APPLICATION_OPERATION:
|
||||
self.operations.append(data)
|
||||
if self.operation_response is not None:
|
||||
return self.operation_response
|
||||
args = data["arguments"]
|
||||
rows = self.history[args["offset"]:args["offset"] + args["limit"]]
|
||||
return {"ok": True, "result": [rows, len(self.history)]}
|
||||
if action == Action.GET_PLUGIN_STORAGE_KEYS:
|
||||
return {"keys": list(self.storage)}
|
||||
if action == Action.GET_PLUGIN_STORAGE:
|
||||
@@ -577,9 +587,9 @@ def test_sdk_local_permission_denial_is_recognized():
|
||||
def test_component_and_permission_manifest():
|
||||
plugin = yaml.safe_load((ROOT / "manifest.yaml").read_text())
|
||||
runner = yaml.safe_load((ROOT / "components/runner/slack_reply.yaml").read_text())
|
||||
assert plugin["metadata"]["version"] == "0.3.0"
|
||||
assert plugin["metadata"]["version"] == "0.4.0"
|
||||
assert plugin["spec"]["permissions"] == {
|
||||
"capabilities": ["bot.message.send", "storage.plugin"], "workspace_operations": [],
|
||||
"capabilities": ["bot.message.send", "storage.plugin"], "workspace_operations": ["monitoring.messages"],
|
||||
}
|
||||
assert runner["spec"]["usages"] == ["event"]
|
||||
assert runner["spec"]["events"] == ["message.received"]
|
||||
@@ -712,3 +722,103 @@ async def test_failed_end_notice_is_reported_after_close():
|
||||
assert host.storage == {}
|
||||
assert "closed" in text(host.sent[-2])
|
||||
assert "end notice" in text(host.sent[-1]) and "errcode=45015" in text(host.sent[-1])
|
||||
|
||||
|
||||
DETAILS = {**CONFIG, "send_user_details": True}
|
||||
|
||||
|
||||
def history_row(index, role, text, ts):
|
||||
return {
|
||||
"role": role, "bot_name": "微信公众号", "timestamp": ts,
|
||||
"message_content": json.dumps([{"type": "Source", "id": index}, {"type": "Plain", "text": text}]),
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_user_details_follow_root_in_thread(monkeypatch):
|
||||
monkeypatch.setattr(bridge.time, "time", lambda: 1000)
|
||||
_plugin, host, handlers = await graph()
|
||||
# Newest first, as monitoring.messages returns them.
|
||||
host.history = [
|
||||
history_row(3, "user", "help <me>", "2026-11-06T07:29:33"),
|
||||
history_row(2, "assistant", "I am the assistant", "2026-11-06T07:29:25"),
|
||||
history_row(1, "user", "who are you", "2026-11-06T07:29:08"),
|
||||
]
|
||||
ctx = context()
|
||||
with bind_invocation(host, config={**DETAILS, "history_messages": 2}, binding=binding()):
|
||||
await receive(handlers, ctx)
|
||||
assert [payload["target_type"] for payload in host.sent] == ["group", "group"]
|
||||
details = text(host.sent[1])
|
||||
assert thread_id(host.sent[1]) == "1234.000001"
|
||||
assert f"OpenID: `{OPENID}`" in details
|
||||
assert f"person_{OPENID}" in details
|
||||
assert "微信公众号" in details
|
||||
assert "Messages so far: 3" in details
|
||||
assert "First contact (UTC): 2026-11-06 07:29" in details
|
||||
assert "who are you" not in details
|
||||
assert details.index("I am the assistant") < details.index("help <me>")
|
||||
assert host.operations[0]["operation_id"] == "monitoring.messages"
|
||||
assert host.operations[0]["arguments"]["session_ids"] == [f"person_{OPENID}"]
|
||||
assert host.operations[0]["arguments"]["bot_ids"] == ["oa-1"]
|
||||
ctx.prevent_default.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_user_details_first_contact_reads_oldest_page():
|
||||
_plugin, host, handlers = await graph()
|
||||
host.history = [history_row(i, "user", f"m{i}", f"2026-11-0{6 - i}T00:00:00") for i in range(5)]
|
||||
with bind_invocation(host, config={**DETAILS, "history_messages": 2}, binding=binding()):
|
||||
await receive(handlers, context())
|
||||
details = text(host.sent[1])
|
||||
assert "Messages so far: 5" in details
|
||||
assert "First contact (UTC): 2026-11-02 00:00" in details
|
||||
assert host.operations[1]["arguments"]["offset"] == 4
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_user_details_without_permission_still_takes_over():
|
||||
_plugin, host, handlers = await graph()
|
||||
host.operation_response = {"ok": False, "error": {"code": "permission_denied", "message": "denied"}}
|
||||
ctx = context()
|
||||
with bind_invocation(host, config=DETAILS, binding=binding()):
|
||||
await receive(handlers, ctx)
|
||||
details = text(host.sent[1])
|
||||
assert f"OpenID: `{OPENID}`" in details
|
||||
assert "monitoring.messages" in details
|
||||
ctx.prevent_default.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_user_details_only_on_new_takeover_and_can_be_disabled():
|
||||
_plugin, host, handlers = await graph()
|
||||
with bind_invocation(host, config=DETAILS, binding=binding()):
|
||||
await receive(handlers, context())
|
||||
await receive(handlers, context("another question"))
|
||||
assert sum("User details" in text(payload) for payload in host.sent) == 1
|
||||
_plugin, host, handlers = await graph()
|
||||
with bind_invocation(host, config={**DETAILS, "send_user_details": False}, binding=binding()):
|
||||
await receive(handlers, context())
|
||||
assert host.operations == []
|
||||
assert len(host.sent) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_zero_history_keeps_summary_without_conversation():
|
||||
_plugin, host, handlers = await graph()
|
||||
host.history = [history_row(1, "user", "secret question", "2026-11-06T07:00:00")]
|
||||
with bind_invocation(host, config={**DETAILS, "history_messages": 0}, binding=binding()):
|
||||
await receive(handlers, context())
|
||||
details = text(host.sent[1])
|
||||
assert "Messages so far: 1" in details
|
||||
assert "secret question" not in details
|
||||
|
||||
|
||||
def test_stored_text_renders_components_and_truncates():
|
||||
content = json.dumps([
|
||||
{"type": "Source", "id": 1}, {"type": "Plain", "text": "hi"},
|
||||
{"type": "Image", "url": "x"}, {"type": "Plain", "text": " there"},
|
||||
])
|
||||
assert bridge.stored_text(content) == "hi[图片 / Image] there"
|
||||
long = bridge.stored_text(json.dumps([{"type": "Plain", "text": "a" * 400}]))
|
||||
assert len(long) == bridge.MAX_HISTORY_CHARS + 1 and long.endswith("…")
|
||||
assert bridge.stored_text("not json") == "not json"
|
||||
|
||||
Reference in New Issue
Block a user