diff --git a/.gitignore b/.gitignore index dbc11e63..d20656c6 100644 --- a/.gitignore +++ b/.gitignore @@ -41,4 +41,5 @@ web/ **/__pycache__ /scripts/scale_dev_jobs.sh server -frontend/.vite \ No newline at end of file +frontend/.vite +frontend/chrome-extension/ \ No newline at end of file diff --git a/client/agent.go b/client/agent.go index f669f4f5..f3773ac2 100644 --- a/client/agent.go +++ b/client/agent.go @@ -22,16 +22,17 @@ type MentionedItem struct { // AgentQARequest agent Q&A request payload. type AgentQARequest struct { - Query string `json:"query"` // Required query text - KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"` // Optional KBs for this query - KnowledgeIDs []string `json:"knowledge_ids,omitempty"` // Optional specific knowledge IDs for this query - AgentEnabled bool `json:"agent_enabled"` // Whether to run in agent mode - AgentID string `json:"agent_id,omitempty"` // Optional custom agent ID - WebSearchEnabled bool `json:"web_search_enabled"` // Whether to enable web search - SummaryModelID string `json:"summary_model_id,omitempty"` // Optional summary model override - MentionedItems []MentionedItem `json:"mentioned_items,omitempty"` // @mentioned knowledge bases and files - DisableTitle bool `json:"disable_title,omitempty"` // Whether to disable auto title generation - MCPServiceIDs []string `json:"mcp_service_ids,omitempty"` // Optional MCP service allow list (deprecated) + Query string `json:"query"` // Required query text + KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"` // Optional KBs for this query + KnowledgeIDs []string `json:"knowledge_ids,omitempty"` // Optional specific knowledge IDs for this query + AgentEnabled bool `json:"agent_enabled"` // Whether to run in agent mode + AgentID string `json:"agent_id,omitempty"` // Optional custom agent ID + WebSearchEnabled bool `json:"web_search_enabled"` // Whether to enable web search + SummaryModelID string `json:"summary_model_id,omitempty"` // Optional summary model override + MentionedItems []MentionedItem `json:"mentioned_items,omitempty"` // @mentioned knowledge bases and files + DisableTitle bool `json:"disable_title,omitempty"` // Whether to disable auto title generation + MCPServiceIDs []string `json:"mcp_service_ids,omitempty"` // Optional MCP service allow list (deprecated) + Images []ImageAttachment `json:"images,omitempty"` // Attached images for multimodal chat } // AgentResponseType defines the type of agent response diff --git a/client/organization.go b/client/organization.go index aec50405..f0c21626 100644 --- a/client/organization.go +++ b/client/organization.go @@ -126,6 +126,19 @@ type JoinRequestResponse struct { ReviewedAt *time.Time `json:"reviewed_at,omitempty"` } +// UserInfo represents user information for API responses +type UserInfo struct { + ID string `json:"id"` + Username string `json:"username"` + Email string `json:"email"` + Avatar string `json:"avatar"` + TenantID uint64 `json:"tenant_id"` + IsActive bool `json:"is_active"` + CanAccessAllTenants bool `json:"can_access_all_tenants"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + // SharedKnowledgeBaseInfo represents a shared knowledge base type SharedKnowledgeBaseInfo struct { ShareID string `json:"share_id"` diff --git a/client/session.go b/client/session.go index 9ea3621b..831fc4c6 100644 --- a/client/session.go +++ b/client/session.go @@ -198,16 +198,26 @@ func (c *Client) GenerateTitle(ctx context.Context, sessionID string, request *G return response.Data, nil } +// ImageAttachment represents an image in a chat request. +// Frontend sends base64 data in the Data field; the backend saves, runs VLM analysis, +// and populates URL/Caption before proceeding with the chat pipeline. +type ImageAttachment struct { + Data string `json:"data,omitempty"` // base64 data URI (data:image/png;base64,...) + URL string `json:"url,omitempty"` // serving URL after saving to storage + Caption string `json:"caption,omitempty"` // VLM analysis result +} + // KnowledgeQARequest knowledge Q&A request type KnowledgeQARequest struct { - Query string `json:"query"` // Query text for knowledge base search - KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // Selected knowledge base IDs for this request - KnowledgeIDs []string `json:"knowledge_ids"` // Selected knowledge IDs for this request - AgentEnabled bool `json:"agent_enabled"` // Whether agent mode is enabled for this request - AgentID string `json:"agent_id"` // Selected custom agent ID for this request - WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search is enabled for this request - SummaryModelID string `json:"summary_model_id"` // Optional summary model ID (overrides session default) - DisableTitle bool `json:"disable_title"` // Whether to disable auto title generation + Query string `json:"query"` // Query text for knowledge base search + KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // Selected knowledge base IDs for this request + KnowledgeIDs []string `json:"knowledge_ids"` // Selected knowledge IDs for this request + AgentEnabled bool `json:"agent_enabled"` // Whether agent mode is enabled for this request + AgentID string `json:"agent_id"` // Selected custom agent ID for this request + WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search is enabled for this request + SummaryModelID string `json:"summary_model_id"` // Optional summary model ID (overrides session default) + DisableTitle bool `json:"disable_title"` // Whether to disable auto title generation + Images []ImageAttachment `json:"images,omitempty"` // Attached images for multimodal chat } // LLMToolCall represents a function/tool call from the LLM diff --git a/config/config.yaml b/config/config.yaml index 2aafb94e..067437a7 100644 --- a/config/config.yaml +++ b/config/config.yaml @@ -29,67 +29,51 @@ conversation: enable_query_expansion: true enable_rerank: true rewrite_prompt_system: | - You are an intelligent assistant specialized in coreference resolution and ellipsis completion. Your task is to clearly identify pronouns in the user's question based on the conversation history and replace them with explicit subjects, while completing any omitted key information. + You are an intelligent assistant that performs THREE tasks on the user's question: + 1. Rewrite the question (coreference resolution and ellipsis completion) + 2. Classify whether the question requires knowledge base retrieval + 3. Analyze attached images (when present) - ## Rewriting Goals - Based on the conversation history, rewrite the current user question with the following objectives: + ## Task 1: Rewriting Goals + Based on the conversation history, rewrite the current user question: - Perform coreference resolution: replace pronouns such as "it", "this", "that", "they", "them", etc. with explicit subjects - Complete omitted key information to ensure the question is semantically complete - Preserve the original meaning and expression style of the question - The rewritten result must also be a question - The rewritten question should be within 30 words - - Output ONLY the rewritten question without any explanation, and do NOT attempt to answer the question - IMPORTANT: The rewritten question must be in the same language as the original question - ## Few-shot Examples + ## Task 2: Intent Classification + Determine if the question requires knowledge base retrieval. + - Output a boolean field `skip_kb_search` instead of any prefix marker. + - Set `skip_kb_search=true` only when you are very confident retrieval is unnecessary. - Example 1: - Conversation history: - User: What features does Slack have? - Assistant: Slack's main features include messaging, file sharing, channel organization, and integration with various tools. + When to set skip_kb_search=true: + - Pure greetings, thanks, or farewell with no question ("谢谢", "你好", "再见") + - Requests to summarize or manipulate the previous conversation itself ("总结一下我们的对话") + - Pure image understanding with NO intent to search documents: describing, summarizing, translating, or extracting content from the image itself ("这张图片是什么", "描述一下图片内容", "帮我翻译图中文字", "图里的表格数据是什么", "帮我识别一下这张图") + - Follow-up questions that clearly refer to previous conversation content (especially previously uploaded images) and can be answered from dialogue context directly ("第一张图再详细描述一下", "第二张门上的字是什么意思", "这个再展开讲讲") - User question: Is it secure? - Rewritten: Is Slack secure? + ## Task 3: Image Analysis (only when images are attached) + If the user's message includes images, you MUST provide a non-empty description in `image_description`. It must NOT be empty when images are present. + Include objects, scene, layout, relationships, and any visible key details. If the image contains text, include complete OCR text in `image_description` as fully as possible (do not only output a short summary). + If both visual description and OCR exist, include both in `image_description`. + Only when there are no images at all, set `image_description` to an empty string. - Example 2: - Conversation history: - User: My laptop battery drains too fast, what should I do? - Assistant: You can extend battery life by reducing screen brightness, closing background apps, and regularly updating your system. + ## Output Format + You MUST output ONLY a single JSON object. + Do NOT output markdown, code fences, explanations, or any extra text. + JSON schema: + {"rewrite_query":"string","skip_kb_search":true|false,"image_description":"string"} - User question: Would that affect the user experience? - Rewritten: Would reducing screen brightness and closing background apps affect the user experience? - - Example 3: - Conversation history: - User: How do you make pasta carbonara? - Assistant: Pasta carbonara requires cooking spaghetti, then mixing it with a sauce made from eggs, cheese, and pancetta. - - User question: How long does it take? - Rewritten: How long does it take to make pasta carbonara? - - Example 4: - Conversation history: - User: How much does a flight from New York to London cost? - Assistant: Flights from New York to London vary by airline and class. Economy tickets are around $400-800, and business class around $2000-5000. - - User question: What about the duration? - Rewritten: How long is the flight from New York to London? - - Example 5: - Conversation history: - User: How do I create a GitHub account? - Assistant: To create a GitHub account, go to github.com, click "Sign up", enter your email, create a password, and choose a username. - - User question: Can I use a company email? - Rewritten: Can I use a company email to create a GitHub account? - rewrite_prompt_user: | ## Conversation History {{conversation}} + rewrite_prompt_user: | ## User Question to Rewrite {{query}} - ## Rewritten Question + ## JSON Output keywords_extraction_prompt: | # Role You are a professional keyword extraction assistant. Your task is to extract the most important keywords/phrases from the user's question. @@ -141,7 +125,7 @@ conversation: You are a precise document summarization expert. Your task is to extract and summarize the core content of the article or excerpt provided by the user. ## Core Requirements - - Summary length should be 50-100 words, adjusted flexibly based on content complexity + - Summary length should be 100-300 words, adjusted flexibly based on content complexity - Generate the summary entirely based on the provided content, without adding any information not present in the article - Ensure the summary captures key information points and main conclusions - Even for complex or specialized content, you must attempt to extract core points for summarization @@ -545,41 +529,3 @@ extract: tenant: # Enable cross-tenant access (can be enabled for intranet environments) enable_cross_tenant_access: false - -# IM integration configuration (optional) -# Uncomment and configure to enable WeCom/Feishu bot integration -# -# mode: -# "webhook" — (default) platform pushes events to your callback URL, requires public domain -# "websocket" — long connection, no public domain needed, SDK maintains persistent connection -im: - wecom: - enabled: true - tenant_id: 10000 # WeKnora tenant ID to use - agent_id: "" # Default agent ID (optional) - knowledge_base_ids: - - "2f046c68-869c-460f-866a-b149ac9a5195" # Default knowledge bases (optional) - mode: "websocket" # "webhook" or "websocket" - output_mode: "stream" # "stream" (default, real-time) or "full" (wait for complete answer) - # --- websocket mode (智能机器人长连接) --- - bot_id: "${WECOM_BOT_ID}" # 智能机器人 Bot ID - bot_secret: "${WECOM_BOT_SECRET}" # 智能机器人 Secret - # --- webhook mode (自建应用回调) --- - # corp_id: "${WECOM_CORP_ID}" # 企业微信 Corp ID - # agent_secret: "${WECOM_AGENT_SECRET}" # 应用 Secret - # token: "${WECOM_TOKEN}" # 回调 Token - # encoding_aes_key: "${WECOM_AES_KEY}" # 回调 EncodingAESKey - # corp_agent_id: 1000001 # 应用 AgentID - feishu: - enabled: true - tenant_id: 10000 # WeKnora tenant ID to use - agent_id: "" # Default agent ID (optional) - knowledge_base_ids: # Default knowledge bases - - "2f046c68-869c-460f-866a-b149ac9a5195" - mode: "websocket" # "webhook" or "websocket" - output_mode: "stream" # "stream" (default, real-time) or "full" (wait for complete answer) - app_id: "${FEISHU_APP_ID}" # 飞书 App ID - app_secret: "${FEISHU_APP_SECRET}" # 飞书 App Secret - # --- 以下仅 webhook 模式需要,websocket 模式可留空 --- - # verification_token: "${FEISHU_TOKEN}" # 事件订阅 Verification Token (webhook only) - # encrypt_key: "${FEISHU_ENCRYPT_KEY}" # 事件订阅 Encrypt Key (webhook only) diff --git a/docker-compose.yml b/docker-compose.yml index 527a6d8b..98bd150f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -38,7 +38,6 @@ services: volumes: - data-files:/data/files - docreader-tmp:/tmp/docreader:ro - # Mount custom config file (required for IM integration) - ./config/config.yaml:/app/config/config.yaml # Optional: mount custom skills directory (allows adding skills without rebuilding image) - ./skills/preloaded:/app/skills/preloaded @@ -114,11 +113,6 @@ services: - SYSTEM_AES_KEY=${SYSTEM_AES_KEY:-} - CONCURRENCY_POOL_SIZE=${CONCURRENCY_POOL_SIZE:-5} - JWT_SECRET=${JWT_SECRET:-} - # IM integration - - FEISHU_APP_ID=${FEISHU_APP_ID:-} - - FEISHU_APP_SECRET=${FEISHU_APP_SECRET:-} - - WECOM_BOT_ID=${WECOM_BOT_ID:-} - - WECOM_BOT_SECRET=${WECOM_BOT_SECRET:-} # File size limit (in MB) - MAX_FILE_SIZE_MB=${MAX_FILE_SIZE_MB:-50} # Agent Skills Sandbox diff --git a/docs/IM集成开发文档.md b/docs/IM集成开发文档.md index 1fb35061..37457814 100644 --- a/docs/IM集成开发文档.md +++ b/docs/IM集成开发文档.md @@ -2,13 +2,17 @@ WeKnora 的 IM 集成模块将企业即时通讯平台(企业微信、飞书)接入 WeKnora 知识问答管道,支持在 IM 中直接向 AI 提问并获得实时流式回答。 +IM 渠道绑定到 Agent,一个 Agent 可接入多个 IM 渠道,所有配置通过前端 Agent 编辑器管理,存储在数据库中。 + ## 目录 - [快速接入指南](#快速接入指南) - [企业微信接入](#企业微信接入) - [飞书接入](#飞书接入) -- [配置参考](#配置参考) +- [前端管理](#前端管理) - [架构总览](#架构总览) +- [数据模型](#数据模型) +- [API 端点](#api-端点) - [核心概念](#核心概念) - [数据流](#数据流) - [接口定义](#接口定义) @@ -23,6 +27,12 @@ WeKnora 的 IM 集成模块将企业即时通讯平台(企业微信、飞书 ## 快速接入指南 +### 前置条件 + +- WeKnora 已部署并运行 +- 已创建至少一个 Agent(自定义智能体) +- Agent 已配置好模型和知识库 + ### 企业微信接入 企业微信提供两种接入模式,根据你的应用类型选择: @@ -33,30 +43,27 @@ WeKnora 的 IM 集成模块将企业即时通讯平台(企业微信、飞书 **第一步:创建智能机器人** -1. 登录 [企业微信工作台](确认已升级到最新版企业微信) → **智能机器人** → **创建机器人** → **手动创建** → **切换API模式创建** → **选择“使用长连接”** +1. 登录 [企业微信工作台](确认已升级到最新版企业微信) → **智能机器人** → **创建机器人** → **手动创建** → **切换API模式创建** → **选择"使用长连接"** 2. 创建完成后,在机器人详情页获取: - **BotID** — 机器人唯一标识 - **BotSecret** — 机器人密钥(点击重置可重新生成) -**第二步:配置 WeKnora** +**第二步:在 WeKnora 中添加 IM 渠道** -编辑 `config/config.yaml`: +1. 进入 Agent 编辑器 → 左侧导航选择 **IM 集成** 标签页 +2. 点击 **添加渠道** +3. 填写配置: + - **平台**:选择「企业微信」 + - **渠道名称**:自定义名称,方便辨识(如「客服机器人」) + - **接入模式**:选择「WebSocket」 + - **输出模式**:选择「流式输出」(推荐) + - **Bot ID**:填入从企业微信获取的 BotID + - **Bot Secret**:填入从企业微信获取的 BotSecret +4. 点击保存 -```yaml -im: - wecom: - enabled: true - mode: "websocket" # 使用 WebSocket 长连接 - output_mode: "stream" # 流式输出(推荐) - tenant_id: ["你的租户ID"] # WeKnora 租户 ID - knowledge_base_ids: ["你的知识库ID"] # 关联的知识库 - bot_id: "${WECOM_BOT_ID}" # 机器人 ID - bot_secret: "${WECOM_BOT_SECRET}" # 机器人 Secret -``` +**第三步:验证** -**第三步:启动服务** - -启动 WeKnora 后,程序会自动建立到企业微信的 WebSocket 长连接(`wss://openws.work.weixin.qq.com`),无需额外配置回调地址。日志中出现以下内容表示连接成功: +保存后 WeKnora 会自动建立到企业微信的 WebSocket 长连接。日志中出现以下内容表示连接成功: ``` [IM] WeCom WebSocket connecting (bot_id=xxx)... @@ -78,31 +85,29 @@ im: - **AgentID** — 应用详情页中的 AgentId(整数) - **Secret** — 应用详情页中的 Secret -**第二步:配置接收消息** +**第二步:在 WeKnora 中添加 IM 渠道** + +1. 进入 Agent 编辑器 → **IM 集成** 标签页 → **添加渠道** +2. 填写配置: + - **平台**:选择「企业微信」 + - **接入模式**:选择「Webhook」 + - **输出模式**:选择「流式输出」 + - **Corp ID**:企业 ID + - **Agent Secret**:应用 Secret + - **Token**:自定义或随机生成(记录下来) + - **EncodingAESKey**:自定义或随机生成(记录下来) + - **Corp Agent ID**:应用 AgentID(整数) +3. 保存后,渠道卡片上会显示**回调地址**,格式为 `https://你的域名/api/v1/im/callback/{channel_id}` +4. 复制该回调地址 + +**第三步:配置企业微信接收消息** 1. 在应用详情页 → **接收消息** → **设置 API 接收** 2. 填写: - - **URL**:`https://你的域名/api/v1/im/callback/wecom` - - **Token**:自定义或随机生成(记录下来) - - **EncodingAESKey**:点击随机生成(记录下来) -3. 点击保存,企业微信会发送 GET 验证请求,WeKnora 需先启动以响应验证 - -**第三步:配置 WeKnora** - -```yaml -im: - wecom: - enabled: true - mode: "webhook" # 使用 Webhook 回调 - output_mode: "stream" - tenant_id: ["你的租户ID"] - knowledge_base_ids: ["你的知识库ID"] - corp_id: "${WECOM_CORP_ID}" # 企业 ID - agent_secret: "${WECOM_AGENT_SECRET}" # 应用 Secret - token: "${WECOM_TOKEN}" # 接收消息 Token - encoding_aes_key: "${WECOM_AES_KEY}" # 接收消息 EncodingAESKey - corp_agent_id: 1000001 # 应用 AgentID(整数) -``` + - **URL**:粘贴上一步复制的回调地址 + - **Token**:填入在 WeKnora 中设置的 Token + - **EncodingAESKey**:填入在 WeKnora 中设置的 EncodingAESKey +3. 点击保存,企业微信会发送 GET 验证请求,WeKnora 会自动响应 **第四步:配置可信域名(可选)** @@ -141,20 +146,16 @@ im: 在 **版本管理与发布** 中创建版本并提交审核。审核通过后用户才能与机器人交互。 -**第四步:配置 WeKnora** +**第四步:在 WeKnora 中添加 IM 渠道** -```yaml -im: - feishu: - enabled: true - mode: "websocket" # 使用长连接 - output_mode: "stream" # 流式输出(推荐,需开启 cardkit:card 权限) - tenant_id: ["你的租户ID"] - knowledge_base_ids: ["你的知识库ID"] - app_id: "${FEISHU_APP_ID}" # App ID - app_secret: "${FEISHU_APP_SECRET}" # App Secret - # WebSocket 模式无需 verification_token 和 encrypt_key -``` +1. 进入 Agent 编辑器 → **IM 集成** → **添加渠道** +2. 填写配置: + - **平台**:选择「飞书」 + - **接入模式**:选择「WebSocket」 + - **输出模式**:选择「流式输出」(需开启 cardkit:card 权限) + - **App ID**:填入从飞书获取的 App ID + - **App Secret**:填入从飞书获取的 App Secret +3. 保存 启动后日志出现以下内容表示连接成功: @@ -170,40 +171,26 @@ im: **前置步骤**同上(创建应用、开通权限),额外需要: -1. **配置事件订阅**: - - 在 **事件与回调** → **事件配置** 中,选择请求方式为 **将事件发送到开发者服务器** - - **请求地址**:`https://你的域名/api/v1/im/callback/feishu` - - 记录页面上的 **Encrypt Key** 和 **Verification Token** - - 添加事件 `im.message.receive_v1` -2. 点击保存时飞书会发送 URL 验证请求(challenge),WeKnora 需先启动以响应 +**第一步:在 WeKnora 中添加 IM 渠道** -```yaml -im: - feishu: - enabled: true - mode: "webhook" - output_mode: "stream" - tenant_id: ["你的租户ID"] - knowledge_base_ids: ["你的知识库ID"] - app_id: "${FEISHU_APP_ID}" - app_secret: "${FEISHU_APP_SECRET}" - verification_token: "${FEISHU_TOKEN}" # 事件订阅页面的 Verification Token - encrypt_key: "${FEISHU_ENCRYPT_KEY}" # 事件订阅页面的 Encrypt Key -``` +1. 进入 Agent 编辑器 → **IM 集成** → **添加渠道** +2. 填写配置: + - **平台**:选择「飞书」 + - **接入模式**:选择「Webhook」 + - **App ID** / **App Secret** + - **Verification Token**:从飞书事件订阅页面获取 + - **Encrypt Key**:从飞书事件订阅页面获取 +3. 保存后,复制渠道卡片上显示的**回调地址** + +**第二步:配置飞书事件订阅** + +1. 在 **事件与回调** → **事件配置** 中,选择请求方式为 **将事件发送到开发者服务器** +2. **请求地址**:粘贴从 WeKnora 复制的回调地址 +3. 添加事件 `im.message.receive_v1` +4. 点击保存时飞书会发送 URL 验证请求(challenge),WeKnora 会自动响应 --- -### 通用配置项说明 - -| 配置项 | 类型 | 说明 | -|--------|------|------| -| `enabled` | bool | 是否启用该平台 | -| `tenant_id` | uint64 | 关联的 WeKnora 租户 ID,消息处理在该租户上下文中执行 | -| `agent_id` | string | 指定自定义 Agent(可选,为空则使用默认知识库问答) | -| `knowledge_base_ids` | []string | 默认关联的知识库 ID 列表 | -| `mode` | string | 连接模式:`"websocket"` (长连接) 或 `"webhook"` (HTTP 回调) | -| `output_mode` | string | 输出模式:`"stream"` (实时流式) 或 `"full"` (等待完整回答后一次发送) | - ### 模式选择指南 | | Webhook | WebSocket | @@ -218,45 +205,27 @@ im: --- -## 配置参考 +## 前端管理 -完整的 `config/config.yaml` 中 `im` 段配置: +IM 渠道在 Agent 编辑器的 **IM 集成** 标签页中管理(仅编辑模式可见,创建 Agent 时不显示)。 -```yaml -im: - wecom: - enabled: true # 是否启用企业微信 - tenant_id: 10000 # 对应的 WeKnora 租户 ID - agent_id: "" # 指定自定义 Agent (可选) - knowledge_base_ids: [] # 默认知识库 ID 列表 - mode: "websocket" # 连接模式: "webhook" | "websocket" - output_mode: "stream" # 输出模式: "stream" (流式) | "full" (完整) +### 渠道列表 - # ── Webhook 模式配置 (自建应用) ── - corp_id: "${WECOM_CORP_ID}" # 企业 ID - agent_secret: "${WECOM_AGENT_SECRET}" # 应用 Secret - token: "${WECOM_TOKEN}" # 接收消息的 Token - encoding_aes_key: "${WECOM_AES_KEY}" # 接收消息的 EncodingAESKey - corp_agent_id: 1000001 # 应用 AgentID(整数) +每个渠道以卡片形式展示,包含: +- **平台标识**:企业微信(绿色)/ 飞书(蓝色) +- **渠道名称**:用户自定义 +- **接入模式**:WebSocket / Webhook +- **输出模式**:流式输出 / 完整输出 +- **启用开关**:可即时启用/停用渠道 +- **回调地址**:Webhook 模式下显示,可一键复制 +- **编辑/删除**:管理渠道配置 - # ── WebSocket 模式配置 (智能机器人) ── - bot_id: "${WECOM_BOT_ID}" # 机器人 ID - bot_secret: "${WECOM_BOT_SECRET}" # 机器人 Secret +### 渠道操作 - feishu: - enabled: true # 是否启用飞书 - tenant_id: 10000 - agent_id: "" - knowledge_base_ids: [] - mode: "websocket" # "websocket" | "webhook" - output_mode: "stream" # "stream" | "full" - app_id: "${FEISHU_APP_ID}" # 应用 App ID - app_secret: "${FEISHU_APP_SECRET}" # 应用 App Secret - verification_token: "${FEISHU_TOKEN}" # 事件验证 Token (仅 Webhook 模式) - encrypt_key: "${FEISHU_ENCRYPT_KEY}" # 加密密钥 (仅 Webhook 模式) -``` - -> **提示:** 配置值支持环境变量引用(`${VAR_NAME}` 语法),建议将密钥类配置通过环境变量注入,避免明文提交到代码仓库。 +- **添加渠道**:选择平台 → 填写凭证 → 选择模式 → 保存 +- **编辑渠道**:可修改名称、模式、输出模式和凭证(平台不可更改) +- **启用/停用**:通过开关即时切换,停用的渠道不会处理消息 +- **删除渠道**:删除后不可恢复 --- @@ -280,15 +249,17 @@ im: │ ─────┼───────────────┼────────────────────────────────────────────── │ │ └───────┬───────┘ │ │ ▼ │ -│ ┌──────────────┐ │ -│ │ im.Service │ 服务编排层 │ -│ │ │ · 消息去重 (MessageID + TTL) │ -│ │ │ · 会话映射 (ChannelSession) │ -│ │ │ · 流式/全量路由 │ -│ └──────┬───────┘ · QA 管道调度 │ -│ │ │ -│ ────────────┼───────────────────────────────────────────────────── │ -│ ▼ │ +│ ┌─────────────────────┐ │ +│ │ im.Service │ 服务编排层 │ +│ │ │ · IM 渠道管理 (CRUD) │ +│ │ ┌───────────────┐ │ · Adapter Factory (动态创建) │ +│ │ │ im_channels │ │ · 消息去重 (MessageID + TTL) │ +│ │ │ (DB表) │ │ · 会话映射 (ChannelSession) │ +│ │ └───────────────┘ │ · 流式/全量路由 │ +│ └──────────┬──────────┘ · QA 管道调度 │ +│ │ │ +│ ───────────┼────────────────────────────────────────────────────── │ +│ ▼ │ │ ┌─────────────────────────────────────┐ │ │ │ WeKnora Core (QA Pipeline) │ 核心层 │ │ │ SessionService · MessageService │ │ @@ -302,13 +273,84 @@ im: | 模式 | 用途 | |------|------| | Adapter Pattern | 统一不同 IM 平台的差异,每个平台实现 `im.Adapter` 接口 | +| Factory Pattern | 通过 `AdapterFactory` 从数据库渠道配置动态创建 Adapter 实例 | | Strategy Pattern | `StreamSender` 可选接口,让平台按需支持流式输出 | | Event-Driven | 通过 `EventBus` 解耦 QA 管道与 IM 输出,支持实时块推送 | --- +## 数据模型 + +### im_channels 表 + +IM 渠道配置存储在 `im_channels` 表中,绑定到 Agent: + +```sql +CREATE TABLE im_channels ( + id VARCHAR(36) PRIMARY KEY, + tenant_id BIGINT NOT NULL, + agent_id VARCHAR(36) NOT NULL, -- 绑定的 Agent ID + platform VARCHAR(20) NOT NULL, -- 'wecom' | 'feishu' + name VARCHAR(255) NOT NULL DEFAULT '', + enabled BOOLEAN NOT NULL DEFAULT true, + mode VARCHAR(20) NOT NULL DEFAULT 'websocket', -- 'webhook' | 'websocket' + output_mode VARCHAR(20) NOT NULL DEFAULT 'stream', -- 'stream' | 'full' + credentials JSONB NOT NULL DEFAULT '{}', -- 平台凭证 + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + deleted_at TIMESTAMPTZ +); +``` + +**credentials 字段结构:** + +| 平台 | 模式 | 字段 | +|------|------|------| +| 企业微信 | WebSocket | `bot_id`, `bot_secret` | +| 企业微信 | Webhook | `corp_id`, `agent_secret`, `token`, `encoding_aes_key`, `corp_agent_id` | +| 飞书 | WebSocket | `app_id`, `app_secret` | +| 飞书 | Webhook | `app_id`, `app_secret`, `verification_token`, `encrypt_key` | + +### im_channel_sessions 表 + +将 IM 渠道中的用户会话映射到 WeKnora 会话: + +``` +(im_channel_id, Platform, UserID, ChatID, TenantID) → SessionID +``` + +--- + +## API 端点 + +### IM 渠道管理 API(需认证) + +| 方法 | 路径 | 说明 | +|------|------|------| +| POST | `/api/v1/agents/:id/im-channels` | 创建 IM 渠道 | +| GET | `/api/v1/agents/:id/im-channels` | 列出 Agent 的所有 IM 渠道 | +| PUT | `/api/v1/im-channels/:id` | 更新 IM 渠道 | +| DELETE | `/api/v1/im-channels/:id` | 删除 IM 渠道 | +| POST | `/api/v1/im-channels/:id/toggle` | 启用/停用 IM 渠道 | + +### IM 回调端点(无需认证,平台签名验证) + +| 方法 | 路径 | 说明 | +|------|------|------| +| GET/POST | `/api/v1/im/callback/:channel_id` | 通用回调(根据 channel_id 自动路由到对应 Adapter) | + +> Webhook 模式下,每个渠道有唯一的回调地址 `/api/v1/im/callback/{channel_id}`,在前端渠道卡片上可一键复制。 + +--- + ## 核心概念 +### IMChannel — IM 渠道 + +每个 IM 渠道代表一个 IM 平台机器人与 WeKnora Agent 的绑定关系。一个 Agent 可以绑定多个渠道(如同时接入企业微信和飞书),同一平台也可以创建多个渠道(如不同的企业微信机器人)。 + +渠道启动时,Service 通过 `AdapterFactory` 根据平台类型和凭证动态创建对应的 Adapter 实例。 + ### IncomingMessage — 统一入站消息 所有平台的消息在解密、解析后被归一化为 `IncomingMessage`,抹平平台差异: @@ -339,13 +381,7 @@ type ReplyMessage struct { ### ChannelSession — 会话映射 -将 IM 渠道 (平台 + 用户 + 群聊) 映射到 WeKnora 会话,实现对话上下文持续性: - -``` -(Platform, UserID, ChatID, TenantID) → SessionID -``` - -首次交互自动创建,后续消息复用同一会话。存储于 `im_channel_sessions` 表。 +将 IM 渠道 (渠道 ID + 用户 + 群聊) 映射到 WeKnora 会话,实现对话上下文持续性。首次交互自动创建,后续消息复用同一会话。存储于 `im_channel_sessions` 表。 --- @@ -358,20 +394,23 @@ type ReplyMessage struct { │ ▼ ┌─ HTTP Handler ──────────────────────────────────┐ -│ 1. 签名验证 (VerifyCallback) │ -│ 2. URL 验证处理 (HandleURLVerification) │ -│ 3. 解密 + 解析 → IncomingMessage (ParseCallback) │ -│ 4. 立即返回 HTTP 200 (异步处理) │ +│ 1. 根据 channel_id 查找渠道配置 │ +│ 2. 获取对应 Adapter │ +│ 3. 签名验证 (VerifyCallback) │ +│ 4. URL 验证处理 (HandleURLVerification) │ +│ 5. 解密 + 解析 → IncomingMessage (ParseCallback) │ +│ 6. 立即返回 HTTP 200 (异步处理) │ └──────────────────────────┬──────────────────────-┘ │ goroutine ▼ ┌─ im.Service ────────────────────────────────────┐ │ 1. 去重检查 (MessageID, 5 分钟 TTL) │ │ 2. 内容长度校验 (≤ 4096 字符) │ -│ 3. 解析/创建 ChannelSession │ -│ 4. 获取 WeKnora Session │ -│ 5. 解析自定义 Agent (可选) │ -│ 6. 判断流式/全量模式 │ +│ 3. 从渠道配置获取 agent_id、tenant_id │ +│ 4. 解析/创建 ChannelSession │ +│ 5. 获取 WeKnora Session │ +│ 6. 加载 Agent 配置(获取知识库等信息) │ +│ 7. 判断流式/全量模式 │ └───────────┬─────────────────────┬───────────────┘ │ │ 流式模式 ▼ 全量模式 ▼ @@ -389,6 +428,29 @@ type ReplyMessage struct { 消息持久化 (user + assistant) ``` +### 渠道生命周期 + +``` +渠道创建/更新 (前端 UI) + │ + ▼ +┌─ im.Service ──────────────────────────┐ +│ 1. 保存渠道配置到数据库 │ +│ 2. 如果渠道已启用: │ +│ a. AdapterFactory 创建 Adapter │ +│ b. WebSocket 模式:建立长连接 │ +│ c. Webhook 模式:注册回调处理 │ +│ 3. 维护 channels map (channel_id → │ +│ channelState{Channel, Adapter}) │ +└────────────────────────────────────────┘ + +服务启动时: + LoadAndStartChannels() → 从 DB 加载所有 enabled 的渠道 → 逐个 StartChannel() + +渠道停用/删除时: + StopChannel() → 取消 Adapter 上下文 → 从 map 移除 +``` + ### 流式输出机制 流式模式通过 `EventBus` 实时收集 QA 管道产生的内容块,以 **300ms 间隔批量推送**,在延迟与 API 限频之间取得平衡: @@ -443,7 +505,15 @@ type StreamSender interface { } ``` -实现此接口后,Service 会自动路由到流式模式。可通过配置 `output_mode: "full"` 强制关闭。 +实现此接口后,Service 会自动路由到流式模式。渠道配置 `output_mode: "full"` 可强制关闭。 + +### im.AdapterFactory — 适配器工厂 + +```go +type AdapterFactory func(ctx context.Context, channel *IMChannel, msgHandler func(*IncomingMessage)) (Adapter, CancelFunc, error) +``` + +每个平台注册一个工厂函数,Service 在启动渠道时调用工厂创建 Adapter 实例。工厂函数根据渠道的 `mode` 和 `credentials` 决定创建哪种 Adapter。 --- @@ -458,7 +528,7 @@ type StreamSender interface { 适用于**自建应用**,需要公网可访问的回调地址。 ``` -企业微信服务器 ──HTTP POST──▶ /api/v1/im/callback/wecom +企业微信服务器 ──HTTP POST──▶ /api/v1/im/callback/{channel_id} │ 解密 (AES-128-CBC) 解析 XML → IncomingMessage @@ -493,8 +563,8 @@ LongConnClient ══WebSocket══▶ wss://openws.work.weixin.qq.com | 文件 | 职责 | |------|------| -| `internal/im/wecom/adapter.go` | Webhook 模式:回调解密、签名验证、REST API 回复、Token 缓存 | -| `internal/im/wecom/bot_adapter.go` | WebSocket 模式适配器壳,代理到 `LongConnClient` | +| `internal/im/wecom/webhook_adapter.go` | Webhook 模式:回调解密、签名验证、REST API 回复、Token 缓存 | +| `internal/im/wecom/ws_adapter.go` | WebSocket 模式适配器壳,代理到 `LongConnClient` | | `internal/im/wecom/longconn.go` | WebSocket 客户端:连接管理、心跳、帧协议、自动重连 | --- @@ -506,7 +576,7 @@ LongConnClient ══WebSocket══▶ wss://openws.work.weixin.qq.com #### Webhook 模式 ``` -飞书服务器 ──HTTP POST──▶ /api/v1/im/callback/feishu +飞书服务器 ──HTTP POST──▶ /api/v1/im/callback/{channel_id} │ 解密 (AES-256-CBC,可选) 解析 JSON → IncomingMessage @@ -574,15 +644,7 @@ EndStream: | 空回答 | 回复 "抱歉,我暂时无法回答这个问题。" | | WebSocket 断连 | 指数退避自动重连 | | 平台重试 | MessageID 去重,5 分钟内自动跳过 | - ---- - -## API 端点 - -| 方法 | 路径 | 说明 | -|------|------|------| -| GET/POST | `/api/v1/im/callback/wecom` | 企业微信回调 (GET 用于 URL 验证) | -| POST | `/api/v1/im/callback/feishu` | 飞书回调 (URL 验证 + 消息事件) | +| 渠道启动失败 | 日志记录错误,不影响其他渠道 | --- @@ -608,23 +670,35 @@ func (a *Adapter) HandleURLVerification(c *gin.Context) bool { /* URL 验证 */ 如需流式输出,额外实现 `im.StreamSender`。 -### 2. 注册适配器 +### 2. 注册适配器工厂 -在 `internal/container/container.go` 的 `registerIMAdapters` 中初始化并注册: +在 `internal/container/container.go` 的 `registerIMAdapterFactories` 中注册工厂函数: ```go -if cfg.IM.DingTalk.Enabled { - adapter := dingtalk.NewAdapter(cfg.IM.DingTalk.AppKey, cfg.IM.DingTalk.AppSecret) - imService.RegisterAdapter(adapter) -} +imService.RegisterAdapterFactory("dingtalk", func(ctx context.Context, channel *im.IMChannel, msgHandler func(*im.IncomingMessage)) (im.Adapter, im.CancelFunc, error) { + creds := parseCredentials(channel.Credentials) + appKey := getString(creds, "app_key") + appSecret := getString(creds, "app_secret") + + adapter := dingtalk.NewAdapter(appKey, appSecret) + + // WebSocket 模式需要启动长连接 + if channel.Mode == "websocket" { + cancelCtx, cancel := context.WithCancel(ctx) + go adapter.StartLongConn(cancelCtx, msgHandler) + return adapter, func() { cancel() }, nil + } + + return adapter, func() {}, nil +}) ``` -### 3. 添加回调路由 +### 3. 前端添加平台选项 -在 `internal/router/router.go` 中注册 HTTP 端点: +在 `IMChannelPanel.vue` 中: +- 添加平台 radio 选项 +- 添加该平台的凭证表单字段 -```go -im.POST("/callback/dingtalk", imHandler.DingTalkCallback) -``` +在 i18n 文件中添加平台名称翻译。 -Service 层 (`im.Service`) 不需要任何修改 —— 消息编排、会话管理、QA 调度、流式控制全部由 Service 统一处理。 +Service 层 (`im.Service`) 不需要任何修改 — 渠道管理、消息编排、会话管理、QA 调度、流式控制全部由 Service 统一处理。 diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.ts index 9aba699f..8a226a73 100644 --- a/frontend/src/api/agent/index.ts +++ b/frontend/src/api/agent/index.ts @@ -35,6 +35,11 @@ export interface CustomAgentConfig { // false: 根据 kb_selection_mode 自动检索知识库 retrieve_kb_only_when_mentioned?: boolean; + // ===== 图片上传/多模态设置 ===== + image_upload_enabled?: boolean; // 是否启用图片上传(默认: false) + vlm_model_id?: string; // VLM模型ID(图片分析用) + image_storage_provider?: string; // 图片存储提供商 + // ===== 文件类型限制 ===== // 支持的文件类型(如 ["csv", "xlsx", "xls"]) // 为空表示支持所有文件类型 @@ -170,3 +175,39 @@ export interface PlaceholdersResponse { export function getPlaceholders() { return get<{ data: PlaceholdersResponse }>('/api/v1/agents/placeholders'); } + +// ===== IM渠道 ===== + +export interface IMChannel { + id: string; + tenant_id?: number; + agent_id: string; + platform: 'wecom' | 'feishu'; + name: string; + enabled: boolean; + mode: 'webhook' | 'websocket'; + output_mode: 'stream' | 'full'; + credentials: Record; + created_at?: string; + updated_at?: string; +} + +export function listIMChannels(agentId: string) { + return get<{ data: IMChannel[] }>(`/api/v1/agents/${agentId}/im-channels`); +} + +export function createIMChannel(agentId: string, data: Partial) { + return post<{ data: IMChannel }>(`/api/v1/agents/${agentId}/im-channels`, data); +} + +export function updateIMChannel(id: string, data: Partial) { + return put<{ data: IMChannel }>(`/api/v1/im-channels/${id}`, data); +} + +export function deleteIMChannel(id: string) { + return del<{ success: boolean }>(`/api/v1/im-channels/${id}`); +} + +export function toggleIMChannel(id: string) { + return post<{ data: IMChannel }>(`/api/v1/im-channels/${id}/toggle`); +} diff --git a/frontend/src/api/chat/index.ts b/frontend/src/api/chat/index.ts index 634958d7..8b59875d 100644 --- a/frontend/src/api/chat/index.ts +++ b/frontend/src/api/chat/index.ts @@ -58,4 +58,8 @@ export async function getSession(session_id: string) { export async function stopSession(session_id: string, message_id: string) { return post(`/api/v1/sessions/${session_id}/stop`, { message_id }); +} + +export async function clearSessionMessages(session_id: string) { + return del(`/api/v1/sessions/${session_id}/messages`); } \ No newline at end of file diff --git a/frontend/src/api/chat/streame.ts b/frontend/src/api/chat/streame.ts index 479c7ba1..b8764f7d 100644 --- a/frontend/src/api/chat/streame.ts +++ b/frontend/src/api/chat/streame.ts @@ -29,7 +29,7 @@ export function useStream() { let renderTimer: number | null = null // 启动流式请求 - const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; agent_enabled?: boolean; agent_id?: string; web_search_enabled?: boolean; enable_memory?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string}>; method: string; url: string }) => { + const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; agent_enabled?: boolean; agent_id?: string; web_search_enabled?: boolean; enable_memory?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string}>; images?: Array<{data: string}>; method: string; url: string }) => { // 重置状态 output.value = ''; error.value = null; @@ -114,6 +114,10 @@ export function useStream() { if (params.mentioned_items !== undefined && params.mentioned_items.length > 0) { postBody.mentioned_items = params.mentioned_items; } + // Include images if provided (base64 data URIs for multimodal chat) + if (params.images !== undefined && params.images.length > 0) { + postBody.images = params.images; + } await fetchEventSource(url, { method: params.method, diff --git a/frontend/src/api/initialization/index.ts b/frontend/src/api/initialization/index.ts index 21640130..928cec6e 100644 --- a/frontend/src/api/initialization/index.ts +++ b/frontend/src/api/initialization/index.ts @@ -412,7 +412,7 @@ export function testMultimodalFunction(testData: { export interface TextRelationExtractionRequest { text: string; tags: string[]; - llm_config: LLMConfig; + model_id: string; } export interface Node { @@ -426,13 +426,6 @@ export interface Relation { type: string; } -export interface LLMConfig { - source: 'local' | 'remote'; - model_name: string; - base_url: string; - api_key: string; -} - export interface TextRelationExtractionResponse { nodes: Node[]; relations: Relation[]; @@ -454,7 +447,7 @@ export function extractTextRelations(request: TextRelationExtractionRequest): Pr export interface FabriTextRequest { tags: string[]; - llm_config: LLMConfig; + model_id: string; } export interface FabriTextResponse { @@ -476,7 +469,6 @@ export function fabriText(request: FabriTextRequest): Promise } export interface FabriTagRequest { - llm_config: LLMConfig; } export interface FabriTagResponse { diff --git a/frontend/src/api/model/index.ts b/frontend/src/api/model/index.ts index e683ceb8..79448c4e 100644 --- a/frontend/src/api/model/index.ts +++ b/frontend/src/api/model/index.ts @@ -22,6 +22,7 @@ export interface ModelConfig { interface_type?: 'ollama' | 'openai'; // VLLM专用 parameter_size?: string; // Ollama模型参数大小 (e.g., "7B", "13B", "70B") extra_config?: Record; // Provider-specific configuration + supports_vision?: boolean; // Whether the model accepts image/multimodal input }; is_default?: boolean; is_builtin?: boolean; diff --git a/frontend/src/assets/dropdown-menu.less b/frontend/src/assets/dropdown-menu.less new file mode 100644 index 00000000..e9ae0def --- /dev/null +++ b/frontend/src/assets/dropdown-menu.less @@ -0,0 +1,322 @@ +/** + * 全局统一下拉菜单样式 + * + * 适用于所有场景的 popup/dropdown 菜单,包括: + * - 卡片操作菜单(知识库、智能体、组织) + * - 文档操作菜单 + * - 对话会话菜单 + * - 上传操作菜单 + * + * 使用方式: + * 1. + .popup-menu 自定义内容模式: overlayClassName="card-more-popup" + * 2. TDesign 下拉模式: 自动匹配全局样式 + */ + +/* 弹出动画 */ +@keyframes dropdownSlideIn { + from { + opacity: 0; + transform: translateY(-6px) scale(0.98); + } + to { + opacity: 1; + transform: translateY(0) scale(1); + } +} + +@keyframes dropdownSlideInUp { + from { + opacity: 0; + transform: translateY(6px) scale(0.98); + } + to { + opacity: 1; + transform: translateY(0) scale(1); + } +} + +/* ============================================ + 一、Popup 容器统一样式( 模式) + ============================================ */ +.card-more-popup { + z-index: 99 !important; + + .t-popup__content { + padding: 4px !important; + margin-top: 4px !important; + min-width: 148px; + border-radius: 10px !important; + background: var(--td-bg-color-container) !important; + border: 0.5px solid var(--td-component-stroke) !important; + box-shadow: + 0 0 0 0.5px rgba(0, 0, 0, 0.03), + 0 2px 4px rgba(0, 0, 0, 0.04), + 0 8px 24px rgba(0, 0, 0, 0.1) !important; + backdrop-filter: blur(20px) saturate(180%) !important; + -webkit-backdrop-filter: blur(20px) saturate(180%) !important; + animation: dropdownSlideIn 0.18s cubic-bezier(0.2, 0, 0, 1) both; + overflow: hidden; + } +} + +/* ============================================ + 二、自定义菜单项统一样式(.popup-menu 模式) + ============================================ */ +.popup-menu { + display: flex; + flex-direction: column; + gap: 1px; +} + +.popup-menu-item { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 12px; + cursor: pointer; + transition: all 0.15s cubic-bezier(0.2, 0, 0, 1); + color: var(--td-text-color-primary); + font-size: 14px; + font-weight: 400; + line-height: 20px; + border-radius: 6px; + position: relative; + + .menu-icon { + font-size: 16px; + flex-shrink: 0; + color: var(--td-text-color-secondary); + transition: all 0.15s cubic-bezier(0.2, 0, 0, 1); + } + + &:hover { + background: var(--td-bg-color-container-hover); + color: var(--td-text-color-primary); + + .menu-icon { + color: var(--td-text-color-primary); + } + } + + &:active { + background: var(--td-bg-color-container-active); + transform: scale(0.98); + } + + &.delete, + &.danger { + color: var(--td-error-color-6); + margin-top: 4px; + position: relative; + + &::before { + content: ''; + position: absolute; + top: -3px; + left: 8px; + right: 8px; + height: 1px; + background: var(--td-component-stroke); + } + + .menu-icon { + color: var(--td-error-color-6); + } + + &:hover { + background: var(--td-error-color-1); + color: var(--td-error-color-6); + + .menu-icon { + color: var(--td-error-color-6); + } + } + + &:active { + background: var(--td-error-color-2); + } + } +} + +/* ============================================ + 三、文档操作菜单统一样式(.card-more 容器) + ============================================ */ +.card-more { + z-index: 99 !important; + + .t-popup__content { + padding: 4px !important; + margin-top: 4px !important; + min-width: 148px; + width: auto; + border-radius: 10px !important; + background: var(--td-bg-color-container) !important; + border: 0.5px solid var(--td-component-stroke) !important; + box-shadow: + 0 0 0 0.5px rgba(0, 0, 0, 0.03), + 0 2px 4px rgba(0, 0, 0, 0.04), + 0 8px 24px rgba(0, 0, 0, 0.1) !important; + backdrop-filter: blur(20px) saturate(180%) !important; + -webkit-backdrop-filter: blur(20px) saturate(180%) !important; + color: var(--td-text-color-primary); + animation: dropdownSlideIn 0.18s cubic-bezier(0.2, 0, 0, 1) both; + overflow: hidden; + } +} + +/* ============================================ + 四、TDesign Dropdown 统一样式 + 适用于 组件(挂载到 body 上) + ============================================ */ +.t-popup__content { + .t-dropdown__menu { + background: var(--td-bg-color-container); + border: 0.5px solid var(--td-component-stroke); + box-shadow: + 0 0 0 0.5px rgba(0, 0, 0, 0.03), + 0 2px 4px rgba(0, 0, 0, 0.04), + 0 8px 24px rgba(0, 0, 0, 0.1); + backdrop-filter: blur(20px) saturate(180%); + -webkit-backdrop-filter: blur(20px) saturate(180%); + padding: 4px; + min-width: 148px; + animation: dropdownSlideIn 0.18s cubic-bezier(0.2, 0, 0, 1) both; + overflow: hidden; + } + + .t-dropdown__item { + padding: 8px 12px; + border-radius: 6px; + margin: 1px 0; + transition: all 0.15s cubic-bezier(0.2, 0, 0, 1); + font-size: 14px; + color: var(--td-text-color-primary); + cursor: pointer; + min-width: auto !important; + max-width: 100% !important; + display: flex !important; + align-items: center; + width: 100%; + position: relative; + + &:hover { + background: var(--td-bg-color-container-hover); + color: var(--td-text-color-primary); + } + + &:active { + background: var(--td-bg-color-container-active); + transform: scale(0.98); + } + + .t-dropdown__item-icon { + flex-shrink: 0; + margin-right: 8px; + color: var(--td-text-color-secondary); + display: flex; + align-items: center; + transition: all 0.15s cubic-bezier(0.2, 0, 0, 1); + + .t-icon { + font-size: 16px; + } + } + + &:hover .t-dropdown__item-icon { + color: var(--td-text-color-primary); + } + + .t-dropdown__item-text { + color: inherit !important; + font-size: 14px !important; + line-height: 20px !important; + white-space: nowrap !important; + overflow: hidden !important; + text-overflow: ellipsis !important; + flex: 1; + min-width: 0; + display: block; + } + + /* TDesign error 主题项(删除操作) */ + &.t-dropdown__item--theme-error { + color: var(--td-error-color-6) !important; + margin-top: 4px; + position: relative; + + &::before { + content: ''; + position: absolute; + top: -3px; + left: 8px; + right: 8px; + height: 1px; + background: var(--td-component-stroke); + } + + .t-dropdown__item-icon { + color: var(--td-error-color-6); + } + + &:hover { + background: var(--td-error-color-1); + color: var(--td-error-color-6) !important; + + .t-dropdown__item-icon { + color: var(--td-error-color-6); + } + } + + &:active { + background: var(--td-error-color-2); + } + } + } +} + +/* tag 更多弹窗 */ +.tag-more-popup { + z-index: 99 !important; + + .t-popup__content { + padding: 4px !important; + margin-top: 4px !important; + min-width: 120px; + border-radius: 10px !important; + background: var(--td-bg-color-container) !important; + border: 0.5px solid var(--td-component-stroke) !important; + box-shadow: + 0 0 0 0.5px rgba(0, 0, 0, 0.03), + 0 2px 4px rgba(0, 0, 0, 0.04), + 0 8px 24px rgba(0, 0, 0, 0.1) !important; + backdrop-filter: blur(20px) saturate(180%) !important; + -webkit-backdrop-filter: blur(20px) saturate(180%) !important; + animation: dropdownSlideIn 0.18s cubic-bezier(0.2, 0, 0, 1) both; + overflow: hidden; + } +} + +/* ============================================ + 五、暗色模式增强 + ============================================ */ +:root[theme-mode="dark"] { + .card-more-popup .t-popup__content, + .card-more .t-popup__content, + .tag-more-popup .t-popup__content { + background: rgba(36, 36, 36, 0.85) !important; + border-color: rgba(255, 255, 255, 0.08) !important; + box-shadow: + 0 0 0 0.5px rgba(255, 255, 255, 0.05), + 0 2px 4px rgba(0, 0, 0, 0.12), + 0 8px 32px rgba(0, 0, 0, 0.28) !important; + } + + .t-popup__content .t-dropdown__menu { + background: rgba(36, 36, 36, 0.85); + border-color: rgba(255, 255, 255, 0.08); + box-shadow: + 0 0 0 0.5px rgba(255, 255, 255, 0.05), + 0 2px 4px rgba(0, 0, 0, 0.12), + 0 8px 32px rgba(0, 0, 0, 0.28); + } +} diff --git a/frontend/src/components/IMChannelPanel.vue b/frontend/src/components/IMChannelPanel.vue new file mode 100644 index 00000000..2e54e3a9 --- /dev/null +++ b/frontend/src/components/IMChannelPanel.vue @@ -0,0 +1,582 @@ + + + + + diff --git a/frontend/src/components/Input-field.vue b/frontend/src/components/Input-field.vue index 2c3e54ff..cc5325d6 100644 --- a/frontend/src/components/Input-field.vue +++ b/frontend/src/components/Input-field.vue @@ -29,6 +29,48 @@ const { t } = useI18n(); let query = ref(""); const showKbSelector = ref(false); + +// Image upload state +const uploadedImages = ref>([]); +const imageInputRef = ref(); +const imageUploading = ref(false); + +const handleImageSelect = (event: Event) => { + const input = event.target as HTMLInputElement; + if (!input.files) return; + addImageFiles(Array.from(input.files)); + input.value = ''; +}; + +const addImageFiles = (files: File[]) => { + if (!isImageUploadEnabledByAgent.value) return; + const allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']; + const maxSize = 10 * 1024 * 1024; + for (const file of files) { + if (uploadedImages.value.length >= 5) { + MessagePlugin.warning(t('chat.imageTooMany')); + break; + } + if (!allowed.includes(file.type)) { + MessagePlugin.warning(t('chat.imageTypeSizeError')); + continue; + } + if (file.size > maxSize) { + MessagePlugin.warning(t('chat.imageTypeSizeError')); + continue; + } + uploadedImages.value.push({ file, preview: URL.createObjectURL(file) }); + } +}; + +const removeImage = (index: number) => { + const removed = uploadedImages.value.splice(index, 1); + if (removed.length > 0) URL.revokeObjectURL(removed[0].preview); +}; + +const triggerImageUpload = () => { + imageInputRef.value?.click(); +}; const atButtonRef = ref(); const showAgentModeSelector = ref(false); const agentModeButtonRef = ref(); @@ -115,6 +157,11 @@ watch([selectedAgentId, agentKnowledgeBases, agentKBSelectionMode], ([newAgentId if (showMention.value) { loadMentionItems(mentionQuery.value, true); } + // Clear images when switching to an agent that doesn't support image upload + if (!isImageUploadEnabledByAgent.value && uploadedImages.value.length > 0) { + uploadedImages.value.forEach(img => URL.revokeObjectURL(img.preview)); + uploadedImages.value = []; + } } }, { immediate: true }); @@ -177,6 +224,12 @@ const agentSupportedFileTypes = computed(() => { return currentAgentConfig.value?.supported_file_types || []; }); +// 智能体是否启用了图片上传(多模态) +const isImageUploadEnabledByAgent = computed(() => { + if (!hasAgentConfig.value) return false; + return currentAgentConfig.value?.image_upload_enabled === true; +}); + // 模型选择是否被智能体锁定 - 已移除锁定逻辑,允许用户自由切换模型 const isModelLockedByAgent = computed(() => { return false; @@ -1321,7 +1374,16 @@ const createSession = async (val: string) => { type: item.type, kb_type: item.type === 'kb' ? (item.kbType || 'document') : undefined })); - emit('send-msg', val, selectedModelId.value, mentionedItems); + const imageFiles = uploadedImages.value.map(img => img.file); + // Blur the textarea BEFORE emitting, so that when the parent navigates away + // and Vue unmounts this component, TDesign's blur handler won't fire on a + // detached DOM element (which causes getComputedStyle to throw). + const textarea = getTextareaEl(); + if (textarea) textarea.blur(); + emit('send-msg', val, selectedModelId.value, mentionedItems, imageFiles); + // Clean up image previews + uploadedImages.value.forEach(img => URL.revokeObjectURL(img.preview)); + uploadedImages.value = []; clearvalue(); } @@ -1503,6 +1565,9 @@ const handleSelectAgent = (agent: CustomAgent, sourceTenantId?: string) => { } const clearvalue = () => { + // Guard: only clear when the textarea DOM element is still mounted, + // otherwise TDesign's autosize will call getComputedStyle on a non-Element. + if (!getTextareaEl()) return; query.value = ""; } @@ -1554,6 +1619,36 @@ const onKeydown = (val: string, event: { e: { preventDefault(): unknown; keyCode } } +const onPaste = (e: ClipboardEvent) => { + const items = e.clipboardData?.items; + if (!items) return; + const imageFiles: File[] = []; + for (const item of items) { + if (item.type.startsWith('image/')) { + const file = item.getAsFile(); + if (file) imageFiles.push(file); + } + } + if (imageFiles.length > 0 && isImageUploadEnabledByAgent.value) { + e.preventDefault(); + addImageFiles(imageFiles); + } +}; + +const onDrop = (e: DragEvent) => { + e.preventDefault(); + const files = e.dataTransfer?.files; + if (!files) return; + const imageFiles = Array.from(files).filter(f => f.type.startsWith('image/')); + if (imageFiles.length > 0 && isImageUploadEnabledByAgent.value) { + addImageFiles(imageFiles); + } +}; + +const onDragOver = (e: DragEvent) => { + e.preventDefault(); +}; + const handleGoToWebSearchSettings = () => { uiStore.openSettings('websearch'); if (route.path !== '/platform/settings') { @@ -1732,9 +1827,25 @@ onBeforeRouteUpdate((to, from, next) => {