Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

feat(channels): allow chat channels to connect to agents (#19307)

Gonghan-Princess24c115bf921d
diff --git a/api/apps/restful_apis/chat_channel_api.py b/api/apps/restful_apis/chat_channel_api.py
index 83c6425c95..08f0a081db 100644
--- a/api/apps/restful_apis/chat_channel_api.py
+++ b/api/apps/restful_apis/chat_channel_api.py
@@ -16,6 +16,7 @@
import logging
from api.apps import current_user, login_required
+from api.channels.targets import validate_agent_target
from api.db.services.chat_channel_service import ChatChannelService
from api.db.services.dialog_service import DialogService
from api.utils.api_utils import get_data_error_result, get_json_result, get_request_json, validate_request
@@ -37,7 +38,26 @@ def _chat_channel_auth_error(channel_id: str, user_id: str):
async def create_chat_channel():
"""Create a chat channel bot owned by the current tenant."""
req = await get_request_json()
- channel = {"id": get_uuid(), "tenant_id": current_user.id, "name": req["name"], "channel": req["channel"], "config": req.get("config") or {}, "chat_id": req.get("chat_id") or None}
+ chat_id = req.get("chat_id") or None
+ agent_id = req.get("agent_id") or None
+ if chat_id and agent_id:
+ return get_data_error_result(message="Choose either a chat assistant or an Agent, not both.")
+ channel_id = get_uuid()
+ if agent_id:
+ target_error = validate_agent_target(agent_id, current_user.id)
+ if target_error == "not_found":
+ return get_data_error_result(message="Can't find this Agent!")
+ if target_error == "forbidden":
+ return _chat_channel_auth_error(channel_id, current_user.id)
+ channel = {
+ "id": channel_id,
+ "tenant_id": current_user.id,
+ "name": req["name"],
+ "channel": req["channel"],
+ "config": req.get("config") or {},
+ "chat_id": chat_id,
+ "agent_id": agent_id,
+ }
ChatChannelService.insert(**channel)
e, conn = ChatChannelService.get_by_id(channel["id"])
@@ -81,6 +101,9 @@ async def update_chat_channel(channel_id):
if isinstance(req, dict) and isinstance(req.get("data"), dict):
req = req["data"]
+ if req.get("chat_id") and req.get("agent_id"):
+ return get_data_error_result(message="Choose either a chat assistant or an Agent, not both.")
+
# Validate the connected dialog (if provided) belongs to the channel's tenant.
if req.get("chat_id"):
e, dia = DialogService.get_by_id(req["chat_id"])
@@ -89,7 +112,18 @@ async def update_chat_channel(channel_id):
if dia.tenant_id != conn.tenant_id:
return _chat_channel_auth_error(channel_id, current_user.id)
- update_fields = {fld: req[fld] for fld in ["name", "config", "chat_id"] if fld in req}
+ if req.get("agent_id"):
+ target_error = validate_agent_target(req["agent_id"], conn.tenant_id)
+ if target_error == "not_found":
+ return get_data_error_result(message="Can't find this Agent!")
+ if target_error == "forbidden":
+ return _chat_channel_auth_error(channel_id, current_user.id)
+
+ update_fields = {fld: req[fld] for fld in ["name", "config", "chat_id", "agent_id"] if fld in req}
+ if req.get("chat_id"):
+ update_fields["agent_id"] = None
+ elif req.get("agent_id"):
+ update_fields["chat_id"] = None
if update_fields:
ChatChannelService.update_by_id(channel_id, update_fields)
diff --git a/api/channels/bootstrap.py b/api/channels/bootstrap.py
index 5139cd11e5..d799afa2ed 100644
--- a/api/channels/bootstrap.py
+++ b/api/channels/bootstrap.py
@@ -31,6 +31,8 @@ import json
import logging
import threading
+from api.channels.targets import validate_agent_target
+
LOGGER = logging.getLogger(__name__)
# Channel packages bundled under api/channels that self-register on import.
@@ -49,6 +51,43 @@ _BUNDLED_CHANNELS = (
_RECONCILE_INTERVAL_SECS = 10
+def _canvas_state(dsl) -> dict:
+ """Normalize a persisted canvas DSL into a dictionary."""
+ value = dsl
+ for _ in range(2):
+ if not isinstance(value, str):
+ break
+ try:
+ value = json.loads(value)
+ except (TypeError, ValueError):
+ return {}
+ return value if isinstance(value, dict) else {}
+
+
+def _prepare_agent_turn(text: str, session_dsl) -> tuple[str, dict]:
+ """Turn a channel message into either a question or a pending form reply."""
+ state = _canvas_state(session_dsl)
+ path = state.get("path") or []
+ if not path or "userfillup" not in str(path[0]).lower():
+ return text, {}
+
+ component = (state.get("components") or {}).get(path[0]) or {}
+ params = (component.get("obj") or {}).get("params") or {}
+ fields = params.get("inputs") or {}
+ if not isinstance(fields, dict) or not fields:
+ return text, {}
+
+ field_name, field = next(iter(fields.items()))
+ value = dict(field) if isinstance(field, dict) else {}
+ value["value"] = text
+ return "", {field_name: value}
+
+
+def _channel_agent_user_id(channel_id: str, chat_id: str, sender_id: str) -> str:
+ """Build a stable Agent user id without sharing context across group members."""
+ return f"channel:{channel_id}:{chat_id}:{sender_id}"
+
+
def _register_channels() -> None:
"""Import each bundled channel package so it self-registers a builder.
@@ -93,7 +132,7 @@ def _build_one(account_id: str, channel: str, credential: dict):
def _make_chat_handler(ch):
- """Build the inbound-message handler bound to a single channel.
+ """Build the inbound-message handler bound to a chat assistant or Agent.
Mirrors the non-streaming path of ``session_completion``: the message is
appended to a per-end-user conversation under the dialog connected to the
@@ -103,7 +142,8 @@ def _make_chat_handler(ch):
connected dialog ignore inbound messages.
"""
from api.channels.core.base import IncomingMessage, OutgoingMessage
-
+ from api.db.services.api_service import API4ConversationService
+ from api.db.services.canvas_service import completion as agent_completion
from api.db.services.chat_channel_service import ChatChannelService
from api.db.services.conversation_service import ConversationService, structure_answer
from api.db.services.dialog_service import DialogService, async_chat
@@ -113,16 +153,64 @@ def _make_chat_handler(ch):
if not (msg.text or "").strip():
return
- # account_id == chat_channel.id; re-read so a re-connected dialog applies live.
+ # account_id == chat_channel.id; re-read so target changes apply live.
e, cc = ChatChannelService.get_by_id(ch.account_id)
- if not e or not cc.chat_id:
+ if not e or (not cc.chat_id and not cc.agent_id):
LOGGER.info(
- "[%s:%s] no dialog connected; ignoring message",
+ "[%s:%s] no assistant connected; ignoring message",
ch.channel_id,
ch.account_id,
)
return
+ if cc.agent_id:
+ target_error = validate_agent_target(cc.agent_id, cc.tenant_id)
+ if target_error:
+ LOGGER.warning(
+ "[%s:%s] connected Agent is unavailable or inaccessible: %s",
+ ch.channel_id,
+ ch.account_id,
+ cc.agent_id,
+ )
+ return
+ user_id = _channel_agent_user_id(ch.account_id, msg.chat_id, msg.sender_id)
+ session = API4ConversationService.get_latest_agent_channel_session(cc.agent_id, user_id)
+ query, inputs = _prepare_agent_turn(msg.text, session.dsl if session else None)
+ answer_text = ""
+ try:
+ async for raw in agent_completion(
+ tenant_id=cc.tenant_id,
+ agent_id=cc.agent_id,
+ session_id=session.id if session else None,
+ query=query,
+ inputs=inputs,
+ user_id=user_id,
+ ):
+ if not isinstance(raw, str):
+ continue
+ for line in raw.splitlines():
+ if not line.startswith("data:"):
+ continue
+ payload = line[len("data:") :].strip()
+ if not payload:
+ continue
+ event = json.loads(payload)
+ if event.get("event") == "message":
+ answer_text += event.get("data", {}).get("content", "") or ""
+ except Exception:
+ LOGGER.exception("[%s:%s] Agent completion failed", ch.channel_id, ch.account_id)
+ answer_text = "抱歉,当前无法处理这条消息,请稍后重试。"
+
+ if answer_text:
+ await ch.send(
+ OutgoingMessage(
+ chat_id=msg.chat_id,
+ text=answer_text,
+ reply_to_message_id=msg.message_id or None,
+ )
+ )
+ return
+
e, dia = DialogService.get_by_id(cc.chat_id)
if not e:
LOGGER.warning("[%s:%s] connected dialog not found: %s", ch.channel_id, ch.account_id, cc.chat_id)
diff --git a/api/channels/targets.py b/api/channels/targets.py
new file mode 100644
index 0000000000..f873eaeb45
--- /dev/null
+++ b/api/channels/targets.py
@@ -0,0 +1,34 @@
+#
+# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from __future__ import annotations
+
+from typing import Any
+
+
+def validate_agent_target(agent_id: str, tenant_id: str, *, service: Any = None) -> str | None:
+ """Validate that a channel tenant may run the selected Agent."""
+ if service is None:
+ from api.db.services.canvas_service import UserCanvasService
+
+ service = UserCanvasService
+
+ found, agent = service.get_by_id(agent_id)
+ if not found or getattr(agent, "canvas_category", "") != "agent_canvas":
+ return "not_found"
+ if not service.accessible(agent_id, tenant_id):
+ return "forbidden"
+ return None
diff --git a/api/db/db_models.py b/api/db/db_models.py
index 80b925b574..1b59e97e84 100644
--- a/api/db/db_models.py
+++ b/api/db/db_models.py
@@ -1739,6 +1739,7 @@ class ChatChannel(DataBaseModel):
channel = CharField(max_length=128, null=False, help_text="Chat channel type", index=True)
config = JSONField(null=False, default={}, help_text="Channel credential & settings")
chat_id = CharField(max_length=32, null=True, default=None, help_text="connected chat id", index=True)
+ agent_id = CharField(max_length=32, null=True, default=None, help_text="connected agent id", index=True)
status = IntegerField(default=1, index=True)
def __str__(self):
@@ -2469,6 +2470,7 @@ def migrate_db():
alter_db_add_column(migrator, "tenant", "tenant_ocr_id", CharField(max_length=32, null=True, help_text="id in tenant_model", index=True))
alter_db_column_type(migrator, "chat_channel", "status", IntegerField(default=1, index=True))
alter_db_rename_column(migrator, "chat_channel", "dialog_id", "chat_id")
+ alter_db_add_column(migrator, "chat_channel", "agent_id", CharField(max_length=32, null=True, help_text="connected agent id", index=True))
# ---- FileCommit / FileCommitItem: artifact-page commit extension ----
alter_db_add_column(migrator, "file_commit", "title", CharField(max_length=255, null=True))
alter_db_add_column(migrator, "file_commit", "comments", TextField(null=True))
diff --git a/api/db/services/api_service.py b/api/db/services/api_service.py
index 1c9dcff562..0e474fec98 100644
--- a/api/db/services/api_service.py
+++ b/api/db/services/api_service.py
@@ -45,6 +45,20 @@ class APITokenService(CommonService):
class API4ConversationService(CommonService):
model = API4Conversation
+ @classmethod
+ @DB.connection_context()
+ def get_latest_agent_channel_session(cls, agent_id, user_id):
+ return (
+ cls.model.select()
+ .where(
+ cls.model.dialog_id == agent_id,
+ cls.model.user_id == user_id,
+ cls.model.source == "agent",
+ )
+ .order_by(cls.model.update_time.desc(), cls.model.create_time.desc())
+ .first()
+ )
+
@staticmethod
def _normalize_query_date(value, is_end=False):
if "T" in value:
diff --git a/api/db/services/chat_channel_service.py b/api/db/services/chat_channel_service.py
index 981b1e874d..6d39ac38a2 100644
--- a/api/db/services/chat_channel_service.py
+++ b/api/db/services/chat_channel_service.py
@@ -17,7 +17,7 @@ import logging
from peewee import JOIN
-from api.db.db_models import DB, ChatChannel, Dialog
+from api.db.db_models import DB, ChatChannel, Dialog, UserCanvas
from api.db.services.common_service import CommonService
LOGGER = logging.getLogger(__name__)
@@ -35,8 +35,10 @@ class ChatChannelService(CommonService):
cls.model.name,
cls.model.channel,
cls.model.chat_id,
+ cls.model.agent_id,
cls.model.status,
Dialog.name.alias("dialog_name"),
+ UserCanvas.title.alias("agent_name"),
]
return list(
cls.model.select(*fields)
@@ -45,6 +47,12 @@ class ChatChannelService(CommonService):
join_type=JOIN.LEFT_OUTER,
on=(Dialog.id == cls.model.chat_id),
)
+ .switch(cls.model)
+ .join(
+ UserCanvas,
+ join_type=JOIN.LEFT_OUTER,
+ on=(UserCanvas.id == cls.model.agent_id),
+ )
.where(cls.model.tenant_id == tenant_id)
.order_by(cls.model.create_time.desc())
.dicts()
diff --git a/test/unit_test/api/channels/test_agent_channel_bridge.py b/test/unit_test/api/channels/test_agent_channel_bridge.py
new file mode 100644
index 0000000000..b98b506d0b
--- /dev/null
+++ b/test/unit_test/api/channels/test_agent_channel_bridge.py
@@ -0,0 +1,64 @@
+import json
+
+from api.channels import bootstrap
+
+
+def test_prepare_agent_turn_resumes_waiting_user_fillup_with_fresh_form_value():
+ assert hasattr(bootstrap, "_prepare_agent_turn"), "Agent channel turn preparation is missing"
+
+ dsl = {
+ "path": ["UserFillUp:Clarification"],
+ "components": {
+ "UserFillUp:Clarification": {
+ "obj": {
+ "component_name": "UserFillUp",
+ "params": {
+ "inputs": {
+ "clarification": {
+ "name": "补充信息",
+ "optional": False,
+ "options": [],
+ "type": "line",
+ }
+ }
+ },
+ }
+ }
+ },
+ }
+
+ query, inputs = bootstrap._prepare_agent_turn("TESLA-M 后面板工位", json.dumps(dsl))
+
+ assert query == ""
+ assert inputs == {
+ "clarification": {
+ "name": "补充信息",
+ "optional": False,
+ "options": [],
+ "type": "line",
+ "value": "TESLA-M 后面板工位",
+ }
+ }
+
+
+def test_prepare_agent_turn_treats_regular_agent_session_as_a_new_question():
+ assert hasattr(bootstrap, "_prepare_agent_turn"), "Agent channel turn preparation is missing"
+
+ query, inputs = bootstrap._prepare_agent_turn(
+ "同轴线怎么安装",
+ {"path": ["Retrieval:Search"], "components": {}},
+ )
+
+ assert query == "同轴线怎么安装"
+ assert inputs == {}
+
+
+def test_channel_agent_user_id_isolates_people_in_the_same_feishu_group():
+ assert hasattr(bootstrap, "_channel_agent_user_id"), "Agent channel session identity is missing"
+
+ first = bootstrap._channel_agent_user_id("channel-1", "group-1", "user-a")
+ second = bootstrap._channel_agent_user_id("channel-1", "group-1", "user-b")
+
+ assert first == "channel:channel-1:group-1:user-a"
+ assert second == "channel:channel-1:group-1:user-b"
+ assert first != second
diff --git a/test/unit_test/api/channels/test_channel_targets.py b/test/unit_test/api/channels/test_channel_targets.py
new file mode 100644
index 0000000000..32c56ea8eb
--- /dev/null
+++ b/test/unit_test/api/channels/test_channel_targets.py
@@ -0,0 +1,42 @@
+from types import SimpleNamespace
+
+
+def test_validate_agent_target_rejects_inaccessible_agent():
+ from api.channels.targets import validate_agent_target
+
+ class FakeUserCanvasService:
+ @staticmethod
+ def get_by_id(_agent_id):
+ return True, SimpleNamespace(canvas_category="agent_canvas")
+
+ @staticmethod
+ def accessible(_agent_id, _tenant_id):
+ return False
+
+ assert validate_agent_target("agent-1", "tenant-1", service=FakeUserCanvasService) == "forbidden"
+
+
+def test_validate_agent_target_rejects_non_agent_canvas():
+ from api.channels.targets import validate_agent_target
+
+ class FakeUserCanvasService:
+ @staticmethod
+ def get_by_id(_agent_id):
+ return True, SimpleNamespace(canvas_category="pipeline")
+
+ assert validate_agent_target("canvas-1", "tenant-1", service=FakeUserCanvasService) == "not_found"
+
+
+def test_validate_agent_target_accepts_accessible_agent():
+ from api.channels.targets import validate_agent_target
+
+ class FakeUserCanvasService:
+ @staticmethod
+ def get_by_id(_agent_id):
+ return True, SimpleNamespace(canvas_category="agent_canvas")
+
+ @staticmethod
+ def accessible(_agent_id, _tenant_id):
+ return True
+
+ assert validate_agent_target("agent-1", "tenant-1", service=FakeUserCanvasService) is None
diff --git a/web/src/locales/en.ts b/web/src/locales/en.ts
index 47e4dd98d2..5e8723a06b 100644
--- a/web/src/locales/en.ts
+++ b/web/src/locales/en.ts
@@ -1904,12 +1904,14 @@ Example: Virtual Hosted Style`,
deleteChannelModalTitle: 'Delete chat channel',
deleteChannelModalContent:
'Are you sure you want to delete this chat channel bot? This action cannot be undone.',
- connectDialog: 'Connect assistant',
- connectDialogTitle: 'Connect {{name}} to an assistant',
- selectDialog: 'Select an assistant',
+ connectDialog: 'Connect assistant or Agent',
+ connectDialogTitle: 'Connect {{name}} to an assistant or Agent',
+ selectDialog: 'Select an assistant or Agent',
connectDialogTip:
- 'Messages received by this channel will be answered by the connected assistant. Clear the selection to disconnect.',
- notConnected: 'No assistant connected',
+ 'Messages received by this channel will be answered by the connected assistant or Agent. Clear the selection to disconnect.',
+ notConnected: 'No assistant or Agent connected',
+ chatChannelAssistant: 'Chat assistant',
+ chatChannelAgent: 'Agent',
chatChannelDesc: {
clickclack: 'Connect a ClickClack bot',
discord: 'Connect a Discord bot',
diff --git a/web/src/locales/zh.ts b/web/src/locales/zh.ts
index 3fccab40eb..da8b32d7cb 100644
--- a/web/src/locales/zh.ts
+++ b/web/src/locales/zh.ts
@@ -1570,12 +1570,14 @@ NER:使用 spaCy NER 和基于规则的关键词提取来抽取 Entities 和 R
deleteChannelModalTitle: '删除聊天渠道',
deleteChannelModalContent:
'确定要删除此聊天渠道机器人吗?此操作无法撤销。',
- connectDialog: '关联助手',
- connectDialogTitle: '将 {{name}} 关联到助手',
- selectDialog: '选择助手',
+ connectDialog: '关联助手或智能体',
+ connectDialogTitle: '将 {{name}} 关联到助手或智能体',
+ selectDialog: '选择助手或智能体',
connectDialogTip:
- '该渠道收到的消息将由关联的助手回复。清空选择即可解除关联。',
- notConnected: '未关联助手',
+ '该渠道收到的消息将由关联的助手或智能体回复。清空选择即可解除关联。',
+ notConnected: '未关联助手或智能体',
+ chatChannelAssistant: '聊天助手',
+ chatChannelAgent: '智能体',
chatChannelDesc: {
clickclack: '连接 ClickClack 机器人',
discord: '连接 Discord 机器人',
diff --git a/web/src/pages/user-setting/chat-channel/component/added-channel-card.tsx b/web/src/pages/user-setting/chat-channel/component/added-channel-card.tsx
index 1baf4e2561..90329a4454 100644
--- a/web/src/pages/user-setting/chat-channel/component/added-channel-card.tsx
+++ b/web/src/pages/user-setting/chat-channel/component/added-channel-card.tsx
@@ -127,10 +127,12 @@ export const AddedChannelCard = (props: IAddedChannelCardProps) => {
>
<div className="flex flex-col gap-0.5">
<div className="text-sm text-text-primary">{item.name}</div>
- {item.chat_id ? (
+ {item.chat_id || item.agent_id ? (
<div className="text-xs text-text-secondary flex items-center gap-1">
<Link2 size={12} />
- {item.dialog_name || item.chat_id}
+ {item.agent_id
+ ? `[${t('setting.chatChannelAgent')}] ${item.agent_name || item.agent_id}`
+ : item.dialog_name || item.chat_id}
</div>
) : (
<div className="text-xs text-text-secondary/60">
diff --git a/web/src/pages/user-setting/chat-channel/component/connect-dialog-modal.tsx b/web/src/pages/user-setting/chat-channel/component/connect-dialog-modal.tsx
index 6ca9d94afa..db7bb9c3e1 100644
--- a/web/src/pages/user-setting/chat-channel/component/connect-dialog-modal.tsx
+++ b/web/src/pages/user-setting/chat-channel/component/connect-dialog-modal.tsx
@@ -17,6 +17,7 @@
import { Button } from '@/components/ui/button';
import { Modal } from '@/components/ui/modal/modal';
import { RAGFlowSelect } from '@/components/ui/select';
+import { useFetchAllAgentList } from '@/hooks/use-agent-request';
import { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
@@ -24,6 +25,7 @@ import {
useConnectChatChannelDialog,
} from '../hooks';
import { IChatChannelBase } from '../interface';
+import { toChatChannelTargetValue } from '../connect-target';
const ConnectDialogModal = ({
visible,
@@ -36,25 +38,43 @@ const ConnectDialogModal = ({
}) => {
const { t } = useTranslation();
const { dialogs } = useChatChannelDialogList();
+ const { data: agents } = useFetchAllAgentList();
const { connect, connecting } = useConnectChatChannelDialog();
- const [dialogId, setDialogId] = useState<string | undefined>(
- channel?.chat_id ?? undefined,
+ const [targetValue, setTargetValue] = useState<string | undefined>(
+ channel?.agent_id
+ ? toChatChannelTargetValue('agent', channel.agent_id)
+ : toChatChannelTargetValue('chat', channel?.chat_id),
);
useEffect(() => {
- setDialogId(channel?.chat_id ?? undefined);
- }, [channel?.id, channel?.chat_id]);
+ setTargetValue(
+ channel?.agent_id
+ ? toChatChannelTargetValue('agent', channel.agent_id)
+ : toChatChannelTargetValue('chat', channel?.chat_id),
+ );
+ }, [channel?.id, channel?.chat_id, channel?.agent_id]);
const options = useMemo(
- () => (dialogs || []).map((d) => ({ label: d.name, value: d.id })),
- [dialogs],
+ () => [
+ ...(dialogs || []).map((d) => ({
+ label: `[${t('setting.chatChannelAssistant')}] ${d.name}`,
+ value: toChatChannelTargetValue('chat', d.id)!,
+ })),
+ ...(agents || [])
+ .filter((agent) => 'title' in agent)
+ .map((agent) => ({
+ label: `[${t('setting.chatChannelAgent')}] ${agent.title}`,
+ value: toChatChannelTargetValue('agent', agent.id)!,
+ })),
+ ],
+ [agents, dialogs, t],
);
const handleConfirm = async () => {
if (!channel) {
return;
}
- await connect({ channelId: channel.id, dialogId: dialogId || null });
+ await connect({ channelId: channel.id, targetValue });
hideModal();
};
@@ -80,8 +100,8 @@ const ConnectDialogModal = ({
{t('setting.selectDialog')}
</label>
<RAGFlowSelect
- value={dialogId}
- onChange={(val: string) => setDialogId(val || undefined)}
+ value={targetValue}
+ onChange={(val: string) => setTargetValue(val || undefined)}
options={options}
allowClear
placeholder={t('setting.selectDialog')}
diff --git a/web/src/pages/user-setting/chat-channel/connect-target.test.ts b/web/src/pages/user-setting/chat-channel/connect-target.test.ts
new file mode 100644
index 0000000000..289a81840d
--- /dev/null
+++ b/web/src/pages/user-setting/chat-channel/connect-target.test.ts
@@ -0,0 +1,24 @@
+import { toChatChannelBinding } from './connect-target';
+
+describe('chat channel assistant binding', () => {
+ it('binds an agent while clearing the ordinary chat assistant', () => {
+ expect(toChatChannelBinding('agent:agent-1')).toEqual({
+ chat_id: null,
+ agent_id: 'agent-1',
+ });
+ });
+
+ it('binds an ordinary chat assistant while clearing the agent', () => {
+ expect(toChatChannelBinding('chat:chat-1')).toEqual({
+ chat_id: 'chat-1',
+ agent_id: null,
+ });
+ });
+
+ it('clears both targets when the selection is removed', () => {
+ expect(toChatChannelBinding(undefined)).toEqual({
+ chat_id: null,
+ agent_id: null,
+ });
+ });
+});
diff --git a/web/src/pages/user-setting/chat-channel/connect-target.ts b/web/src/pages/user-setting/chat-channel/connect-target.ts
new file mode 100644
index 0000000000..511e74dd39
--- /dev/null
+++ b/web/src/pages/user-setting/chat-channel/connect-target.ts
@@ -0,0 +1,28 @@
+export type ChatChannelTargetType = 'chat' | 'agent';
+
+export interface ChatChannelBinding {
+ chat_id: string | null;
+ agent_id: string | null;
+}
+
+export const toChatChannelTargetValue = (
+ targetType?: ChatChannelTargetType,
+ targetId?: string | null,
+) => (targetType && targetId ? `${targetType}:${targetId}` : undefined);
+
+export const toChatChannelBinding = (value?: string): ChatChannelBinding => {
+ if (!value) {
+ return { chat_id: null, agent_id: null };
+ }
+
+ const separator = value.indexOf(':');
+ const type = value.slice(0, separator);
+ const id = separator >= 0 ? value.slice(separator + 1) : '';
+ if (type === 'agent' && id) {
+ return { chat_id: null, agent_id: id };
+ }
+ if (type === 'chat' && id) {
+ return { chat_id: id, agent_id: null };
+ }
+ return { chat_id: null, agent_id: null };
+};
diff --git a/web/src/pages/user-setting/chat-channel/hooks.ts b/web/src/pages/user-setting/chat-channel/hooks.ts
index 9cd95754b4..fda62f3164 100644
--- a/web/src/pages/user-setting/chat-channel/hooks.ts
+++ b/web/src/pages/user-setting/chat-channel/hooks.ts
@@ -26,6 +26,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { t } from 'i18next';
import { useCallback, useMemo, useState } from 'react';
import { ChatChannelKey, useChatChannelInfo } from './constant';
+import { toChatChannelBinding } from './connect-target';
import { IChatChannel, IChatChannelBase, IChatChannelInfo } from './interface';
export const ChatChannelKeys = {
@@ -184,13 +185,11 @@ export const useConnectChatChannelDialog = () => {
const { mutateAsync, isPending } = useMutation({
mutationKey: ['connect-chat-channel-dialog'],
- mutationFn: async (params: {
- channelId: string;
- dialogId: string | null;
- }) => {
- const { data } = await updateChatChannel(params.channelId, {
- chat_id: params.dialogId,
- });
+ mutationFn: async (params: { channelId: string; targetValue?: string }) => {
+ const { data } = await updateChatChannel(
+ params.channelId,
+ toChatChannelBinding(params.targetValue),
+ );
if (data.code === 0) {
message.success(t('message.operated'));
queryClient.invalidateQueries({ queryKey: ChatChannelKeys.list() });
diff --git a/web/src/pages/user-setting/chat-channel/interface.ts b/web/src/pages/user-setting/chat-channel/interface.ts
index c964980dcb..c653fb5348 100644
--- a/web/src/pages/user-setting/chat-channel/interface.ts
+++ b/web/src/pages/user-setting/chat-channel/interface.ts
@@ -30,6 +30,8 @@ export interface IChatChannelBase {
// Connected assistant (chat), joined in by the list endpoint.
chat_id?: string | null;
dialog_name?: string | null;
+ agent_id?: string | null;
+ agent_name?: string | null;
}
export type IChatChannel = IChatChannelBase & {