feat(embed): add widget, visitor chat, and management UI (#1657)

Add embed.html entrypoint, floating widget SDK, secure-mode snippets,
management panel with preview, visitor chat composables, citation rendering,
and integration docs for subdomain and server-side token exchange.
This commit is contained in:
wizardchen
2026-06-12 22:40:18 +08:00
committed by lyingbug
parent ed9802ff2b
commit 08852ab19d
41 changed files with 10186 additions and 745 deletions
+182
View File
@@ -0,0 +1,182 @@
# Embed 安全模式
> **一句话**:长期密钥(发布 Token `em_…`)只放在**你自己的服务器**;访客浏览器里只有 30 分钟有效的短时令牌(`ems_…`)。
## 为什么要用?
| 方式 | 发布 Token 在哪 | 风险 |
|------|-----------------|------|
| iframe / 普通 Widget | 写在页面 HTML 或 URL hash 里 | 任何人「查看源代码」就能复制,等于公开密钥 |
| **安全模式 Widget** | 仅环境变量 / 密钥管理,在服务端 | 浏览器拿不到长期密钥;还可先校验访客是否登录 |
生产环境对外嵌入,**应优先用安全模式**。
## 两种 Token
| 名称 | 格式 | 谁持有 | 用途 |
|------|------|--------|------|
| 发布 Token | `em_…` | 仅你的服务端 | 向 WeKnora 换取短时令牌;在管理端「渠道密钥」查看 |
| 会话 Token | `ems_…` | 访客浏览器(iframe 内) | 调聊天、上传等 embed API;约 30 分钟过期,Widget 会自动刷新 |
## 工作流程
```
访客浏览器 你的后端(shop 的服务器) WeKnora
│ │ │
│ 1. 加载 Widget │ │
│ data-token-endpoint │ │
│ (不含 em_) │ │
│─────────────────────────────►│ │
│ │ 2. 校验访客已登录(可选) │
│ │ 3. POST .../embed/:id/exchange │
│ │ Authorization: Embed em_… │
│ │─────────────────────────────►│
│ │◄──── session_token (ems_…) ───│
│◄── 4. { token, expiresIn } ──│ │
│ 5. iframe 用 ems_ 聊天 │ │
```
对应管理端「嵌入渠道 → 安全模式」里的两段代码:
1. **页面脚本**:`data-token-endpoint="https://你的域名/weknora/embed-token"`(没有 `data-token`)
2. **服务端接口**:用发布 Token 调 exchange,把 `ems_…` 返回给前端
## 集成步骤
### 第 1 步:在 WeKnora 创建渠道
- 记下 **渠道 ID** 和 **发布 Token**(`em_…`)
- 配置域名白名单(见下)
- 配置分钟 / 日限流
### 第 2 步:部署取令牌接口
在你的业务后端新增一个 HTTP 接口(路径自定),要求:
**入参**:浏览器 GET 请求(Widget 会 `fetch` 这个地址)
**你必须做**:
- 校验调用方是合法访客(Session Cookie、JWT 等),未登录返回 `401`
- 用发布 Token 调 WeKnora exchange
- 成功时返回 JSON:`{ "token": "<ems_…>", "expiresIn": 1800 }`
**调 exchange 的约定**:
```http
POST https://<weknora-host>/api/v1/embed/<channel_id>/exchange
Authorization: Embed <发布 Token em_…>
Origin: https://<你的业务站点> ← 须与渠道白名单一致,否则 403
```
> 服务端 `fetch` 默认不带 `Origin`,需要**手动设置**与白名单匹配的 `Origin` 头。
### 第 3 步:粘贴安全模式 Widget 代码
把 `data-token-endpoint` 改成上一步的真实 URL。完整示例在管理端「安全模式」Tab 可复制。
## 服务端示例
以下 `<WEKNORA_HOST>`、`<CHANNEL_ID>` 替换为实际值;发布 Token 放环境变量 `WEKNORA_PUBLISH_TOKEN`,**不要**写进前端。
### Node.js(Express)
```javascript
const WEKNORA_BASE = 'https://<WEKNORA_HOST>';
const CHANNEL_ID = '<CHANNEL_ID>';
const ALLOWED_ORIGIN = 'https://shop.example.com'; // 与渠道白名单一致
app.get('/weknora/embed-token', async (req, res) => {
const hasSession = Boolean(req.cookies?.session_id);
const auth = req.headers.authorization || '';
if (!hasSession && !auth.startsWith('Bearer ')) {
return res.status(401).json({ error: 'unauthorized' });
}
const r = await fetch(`${WEKNORA_BASE}/api/v1/embed/${CHANNEL_ID}/exchange`, {
method: 'POST',
headers: {
Authorization: 'Embed ' + process.env.WEKNORA_PUBLISH_TOKEN,
Origin: ALLOWED_ORIGIN,
},
});
const body = await r.json();
if (!body?.data?.session_token) {
return res.status(502).json({ error: 'mint failed' });
}
res.json({ token: body.data.session_token, expiresIn: body.data.expires_in });
});
```
### Go(net/http)
```go
func embedTokenHandler(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") == "" && r.Header.Get("Cookie") == "" {
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
return
}
req, _ := http.NewRequest(http.MethodPost,
"https://<WEKNORA_HOST>/api/v1/embed/<CHANNEL_ID>/exchange", nil)
req.Header.Set("Authorization", "Embed "+os.Getenv("WEKNORA_PUBLISH_TOKEN"))
req.Header.Set("Origin", "https://shop.example.com") // 与渠道白名单一致
resp, err := http.DefaultClient.Do(req)
if err != nil || resp.StatusCode >= 300 {
http.Error(w, `{"error":"mint failed"}`, http.StatusBadGateway)
return
}
defer resp.Body.Close()
var body struct {
Data struct {
SessionToken string `json:"session_token"`
ExpiresIn int `json:"expires_in"`
} `json:"data"`
}
if json.NewDecoder(resp.Body).Decode(&body) != nil || body.Data.SessionToken == "" {
http.Error(w, `{"error":"mint failed"}`, http.StatusBadGateway)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{
"token": body.Data.SessionToken, "expiresIn": body.Data.ExpiresIn,
})
}
```
管理端「安全模式 → 服务端示例」Tab 会按当前渠道 ID 生成带真实 URL 的片段。
## 域名白名单怎么填?
| 要放行的请求来源 | 白名单示例 |
|------------------|------------|
| 聊天 iframe 所在源站(embed 页面) | `https://app.example.com` 或 `https://embed.example.com` |
| 你的取令牌后端(exchange 时带的 Origin) | `https://shop.example.com` |
若 embed 使用[独立子域](./embed-subdomain.md),**两条都要加**(embed 源站 + 业务后端源站)。
开发环境可临时使用 `*`;**生产环境禁止 `*`**。
## 上线检查
- [ ] 发布 Token 仅通过环境变量 / 密钥服务注入,未提交到 Git、未打进前端静态包
- [ ] 取令牌接口校验访客身份
- [ ] 全链路 HTTPS
- [ ] 白名单已包含 embed 源站与 exchange 使用的 Origin
- [ ] 已配置限流;敏感智能体不要用普通模式把 Token 暴露在网页里
- [ ] 轮换发布 Token 后,同步更新服务端环境变量
## 常见问题
| 现象 | 原因与处理 |
|------|------------|
| exchange 返回 **401** / `publish token required` | 发布 Token 错误、已轮换,或误用了 `ems_` 会话 Token |
| exchange 或聊天 API 返回 **403** `origin not allowed` | 白名单未包含当前请求的 `Origin`;服务端 exchange 记得手动加 `Origin` 头 |
| iframe 一直「等待 Token」 | `token-endpoint` 未返回 `{ token, expiresIn }`,或 CORS 未允许 Widget 所在源站访问你的接口 |
| 取令牌接口 **502** `mint failed` | WeKnora 不可达、渠道已停用,或 exchange 响应格式不对 |
| 访客随便就能聊 | 取令牌接口未做登录校验——在 exchange 前加 Session / JWT 检查 |
## 相关
- 可选:embed 独立子域 → [embed-subdomain.md](./embed-subdomain.md)
- Widget SDK 注释:`frontend/public/weknora-widget.js`
- 代码生成:`frontend/src/api/embed/index.ts`
+106
View File
@@ -0,0 +1,106 @@
# Embed 独立子域部署(可选)
> **一句话**:把聊天页面单独放到 `embed.example.com`,与主站 `app.example.com` 分开。**大多数部署不需要这一步**——主站和 embed 同域就能用。只有对安全隔离有明确要求时再考虑。
## 先搞清楚三个「网站」
嵌入聊天时,实际涉及三类地址(可以相同,也可以不同):
| 角色 | 举例 | 干什么 |
|------|------|--------|
| **A. 业务站点(宿主)** | `https://shop.example.com` | 你的商城 / 文档站;在这里粘贴 Widget 脚本或 iframe |
| **B. Embed 页面源站** | `https://app.example.com` 或 `https://embed.example.com` | 提供 `embed.html`、`weknora-widget.js`;聊天 iframe 加载自这里 |
| **C. WeKnora API** | 通常与 B 同域,如 `https://app.example.com/api` | 后端接口 |
**默认(推荐入门)**:B 和主站管理后台都在 `https://app.example.com`,A 可以是任意第三方域名。
```
shop.example.com app.example.com
┌─────────────────┐ ┌──────────────────────────┐
│ <script src= │ │ /weknora-widget.js │
│ app.../widget> │──────►│ /embed/:channelId │
│ │ │ /api/v1/embed/... │
│ (浮窗 iframe) │◄──────│ │
└─────────────────┘ └──────────────────────────┘
```
**独立子域(进阶)**:把 B 拆到 `https://embed.example.com`,主站 `https://app.example.com` 只留管理后台。
```
shop.example.com embed.example.com app.example.com
┌─────────────────┐ ┌──────────────────┐ ┌─────────────┐
│ Widget 脚本 │──────►│ embed 静态页+API │ │ 管理后台 │
│ iframe 指向 embed│◄──────│ (无 index SPA) │ │ (可选分离) │
└─────────────────┘ └──────────────────┘ └─────────────┘
```
## 什么时候需要独立子域?
| 场景 | 是否需要 |
|------|----------|
| 内测、PoC、单域 Docker 部署 | **不需要** |
| 主站 `X-Frame-Options: SAMEORIGIN`,但要把聊天嵌到第三方页面 | **不需要**(被嵌的是 `/embed/*` 页面,不是管理后台 SPA) |
| 希望 embed 站点不携带主站登录 Cookie、缩小暴露面 | **可以考虑** |
| 希望 CDN / WAF 对 embed 流量单独限速、缓存 | **可以考虑** |
| 合规要求「对外嵌入」与「内部管理」必须不同源 | **需要** |
本地开发:`http://localhost:5173` 同域即可,Vite 已把 `/embed/*` 指到 `embed.html`,**不必**配子域。
## 怎么配置
### 1. 告诉管理端「embed 页面公网地址」
管理端生成 iframe / Widget 代码时,需要知道 B 的地址。在 `frontend/public/config.js`(或 Docker 启动脚本生成的配置)里设置:
```javascript
window.__RUNTIME_CONFIG__ = {
// embed 页面与 widget.js 的源站;留空则使用当前浏览器所在域名
EMBED_BASE_URL: 'https://embed.example.com',
MAX_FILE_SIZE_MB: 50,
};
```
构建期也可通过环境变量注入:`VITE_EMBED_BASE_URL=https://embed.example.com`(可选)。
### 2. Nginx:单独 server 块只服务 embed
`frontend/nginx.conf` 顶部有注释掉的示例。要点:
- `server_name embed.example.com`
- 只暴露:`/embed/*` → `embed.html`,`/weknora-widget.js`,`/assets/*`
- `/api/` 反代到 WeKnora 后端(与主站相同后端即可)
- **不要**在这个 server 上挂完整 `index.html` 管理 SPA(减少攻击面)
主站 `server` 块可继续 `X-Frame-Options: SAMEORIGIN`,不影响第三方嵌 embed 子域的 iframe。
### 3. 域名白名单填什么?
渠道里的「域名白名单」校验的是 **API 请求的 `Origin` 头**,不是「允许哪些网站粘贴脚本」的抽象概念。
实际要填:
1. **Embed 页面源站**(必填)——聊天 iframe 内发 API 时浏览器会带这个 Origin
- 同域部署:`https://app.example.com`
- 独立子域:`https://embed.example.com`
2. **你的业务后端源站**(安全模式时建议填)——你自己写的「取令牌接口」在服务端调用 `POST .../exchange` 时,需带与白名单一致的 `Origin` 头(见 [embed-secure-mode.md](./embed-secure-mode.md))
第三方商城 `https://shop.example.com` **通常不用**进白名单(它只是加载脚本,不直接调 embed API)。
若你把 embed 反代到商城同域路径下(少见),才需要填商城域名。
## Widget 跨域与 sandbox
当宿主站 A 与 embed 源站 B **不同域**时,`weknora-widget.js` 会自动给内部 iframe 加上 `sandbox`(也可手动 `data-sandbox="true"`)。
A 与 B 同域时保持默认即可,无需 `data-sandbox`。
## 检查清单
- [ ] `EMBED_BASE_URL` 与真实访问地址一致(含 `https`)
- [ ] embed 子域能打开 `/embed/<渠道ID>` 和 `/weknora-widget.js`
- [ ] embed 子域 `/api/` 能连到后端
- [ ] 渠道白名单包含 embed 源站(及安全模式下的业务后端源站)
- [ ] 管理端复制的 snippet 里 URL 已变为 embed 子域
## 相关文档
- 发布 Token 不落浏览器:[embed-secure-mode.md](./embed-secure-mode.md)
+27
View File
@@ -0,0 +1,27 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>WeKnora Embed</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="renderer" content="webkit">
<link rel="shortcut icon" type="image/png" href="./public/favicon.ico"/>
<style>
html, body, #embed-app { height: 100%; margin: 0; }
</style>
</head>
<body>
<script>
(function(){
document.documentElement.setAttribute('theme-mode', 'light');
document.documentElement.style.background = '#fff';
document.body.style.background = '#fff';
})();
</script>
<script src="/config.js"></script>
<script src="/tdesign-icons/0.4.1/fonts/index.js"></script>
<div id="embed-app"></div>
<script type="module" src="/src/embed-main.ts"></script>
</body>
</html>
+31
View File
@@ -1,3 +1,17 @@
# Optional dedicated embed origin — uncomment and set server_name (e.g. embed.example.com).
# Serve only embed.html + static assets; proxy /api to the WeKnora backend.
# See docs/embed-subdomain.md
#
# server {
# listen 80;
# server_name embed.example.com;
# client_max_body_size ${MAX_FILE_SIZE};
# location = /weknora-widget.js { root /usr/share/nginx/html; }
# location ^~ /embed/ { root /usr/share/nginx/html; try_files $uri $uri/ /embed.html; }
# location ^~ /assets/ { root /usr/share/nginx/html; add_header Cache-Control "public, max-age=31536000, immutable"; }
# location /api/ { proxy_pass http://weknora-backend:8080; proxy_set_header Host $host; }
# }
server {
listen 80;
server_name localhost;
@@ -24,6 +38,23 @@ server {
error_log /var/log/nginx/error.log warn;
access_log /var/log/nginx/access.log;
# Static widget loader for third-party sites
location = /weknora-widget.js {
root /usr/share/nginx/html;
add_header Cache-Control "public, max-age=3600" always;
add_header X-Content-Type-Options "nosniff" always;
}
# Embed widget pages may be loaded inside third-party iframes (lightweight embed.html)
location ^~ /embed/ {
root /usr/share/nginx/html;
try_files $uri $uri/ /embed.html;
add_header Cache-Control "no-cache, must-revalidate" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
}
# 前端静态文件
location / {
root /usr/share/nginx/html;
+3 -1
View File
@@ -1,4 +1,6 @@
// 运行时配置(本地开发默认值,Docker 环境会被 entrypoint 脚本覆盖)
window.__RUNTIME_CONFIG__ = {
MAX_FILE_SIZE_MB: 50
MAX_FILE_SIZE_MB: 50,
// Optional: serve embed on a dedicated origin, e.g. 'https://embed.example.com'
EMBED_BASE_URL: '',
};
+434
View File
@@ -0,0 +1,434 @@
/**
* WeKnora embed widget SDK — floating chat launcher.
*
* Programmatic:
* WeKnora.init({ channel, token, position, primaryColor, title, baseUrl })
* WeKnora.open() | close() | toggle() | destroy()
* WeKnora.on('ready', fn) | off('ready', fn)
*
* Host context & actions (postMessage to iframe):
* WeKnora.setContext({ userId, page, ... })
* Inject visitor/page context merged into each chat query.
* WeKnora.openWithQuery('How do I reset my password?')
* Opens the panel (if closed) and sends the query when the iframe is ready.
* WeKnora.setLocale('en-US')
* Switch embed UI language (zh-CN | en-US | ko-KR | ru-RU).
*
* Secure mode (recommended): instead of `token`, pass `tokenEndpoint` — a URL on
* your own backend that returns { token: "ems_...", expiresIn: 1800 }. Your
* backend mints that short-lived session token by exchanging the publish token
* (kept server-side) against POST /api/v1/embed/:channel/exchange. The publish
* token then never reaches the browser; the widget auto-refreshes before expiry.
*
* Legacy script-tag auto-init via data-* attributes on the script element
* (data-channel + data-token, or data-channel + data-token-endpoint).
*/
(function (global) {
'use strict';
var HOST_SOURCE = 'weknora-host';
var EMBED_SOURCE = 'weknora-embed';
var POSITIONS = ['bottom-right', 'bottom-left', 'top-right', 'top-left'];
var DEFAULT_POSITION = 'bottom-right';
var DEFAULT_COLOR = '#07C05F';
var DEFAULT_TITLE = 'AI Assistant';
var DEFAULT_WIDTH = 400;
var DEFAULT_HEIGHT = 600;
var instance = null;
var listeners = {};
function normalizePosition(pos) {
if (!pos || POSITIONS.indexOf(pos) < 0) return DEFAULT_POSITION;
return pos;
}
function positionStyles(position, kind) {
var isLeft = position.indexOf('left') >= 0;
var isTop = position.indexOf('top') >= 0;
var horizontal = isLeft ? 'left:24px' : 'right:24px';
if (kind === 'launcher') {
return horizontal + ';' + (isTop ? 'top:24px' : 'bottom:24px');
}
return horizontal + ';' + (isTop ? 'top:88px' : 'bottom:88px');
}
function emit(event, payload) {
var handlers = listeners[event];
if (!handlers) return;
handlers.slice().forEach(function (fn) {
try { fn(payload); } catch (e) { console.error('[WeKnora]', e); }
});
}
function createWidget(opts) {
var channelId = opts.channel || opts.channelId;
// Insecure mode: a long-lived publish token is embedded in the page.
var staticToken = opts.token;
// Secure mode: the page never holds the publish token. Instead it points at
// an endpoint on the integrator's own backend that mints a short-lived
// session token (by server-side exchange of the publish token). The widget
// fetches a fresh token here and refreshes it before expiry.
var tokenEndpoint = opts.tokenEndpoint || opts.token_endpoint || '';
if (!channelId || (!staticToken && !tokenEndpoint)) {
console.warn('[WeKnora] channel and (token or tokenEndpoint) are required');
return null;
}
var currentToken = staticToken || '';
var tokenInFlight = null;
var refreshTimer = null;
function scheduleRefresh(expiresInSec) {
if (!tokenEndpoint) return;
if (refreshTimer) clearTimeout(refreshTimer);
var ttl = Number(expiresInSec) > 0 ? Number(expiresInSec) : 1800;
// Refresh at ~80% of the lifetime, never sooner than 30s.
var delayMs = Math.max(Math.floor(ttl * 0.8), 30) * 1000;
refreshTimer = setTimeout(function () {
loadToken(true).then(function (tok) {
if (tok) provideToken();
}).catch(function () { /* keep last token; next interaction retries */ });
}, delayMs);
}
// Returns a Promise resolving to a usable token. In static mode this is the
// embedded publish token. In secure mode it fetches from tokenEndpoint.
function loadToken(force) {
if (staticToken) return Promise.resolve(staticToken);
if (currentToken && !force) return Promise.resolve(currentToken);
if (tokenInFlight) return tokenInFlight;
tokenInFlight = fetch(tokenEndpoint, {
method: 'GET',
credentials: 'include',
headers: { Accept: 'application/json' },
})
.then(function (res) {
if (!res.ok) throw new Error('token endpoint HTTP ' + res.status);
return res.json();
})
.then(function (data) {
var d = data || {};
var inner = d.data || d;
var tok = inner.token || inner.session_token || '';
var expiresIn = inner.expiresIn || inner.expires_in || 0;
if (!tok) throw new Error('token endpoint returned no token');
currentToken = tok;
scheduleRefresh(expiresIn);
return tok;
})
.catch(function (e) {
console.error('[WeKnora] failed to load token', e);
throw e;
})
.then(function (tok) { tokenInFlight = null; return tok; }, function (e) { tokenInFlight = null; throw e; });
return tokenInFlight;
}
var position = normalizePosition(opts.position);
var primaryColor = opts.primaryColor || opts.primary_color || DEFAULT_COLOR;
var title = opts.title || DEFAULT_TITLE;
var baseUrl = (opts.baseUrl || opts.base || '').replace(/\/$/, '');
if (!baseUrl) {
var script = document.currentScript;
if (script && script.src) {
baseUrl = script.src.replace(/\/weknora-widget\.js.*$/, '');
} else {
baseUrl = global.location ? global.location.origin : '';
}
}
var panelWidth = Number(opts.width) > 0 ? Number(opts.width) : DEFAULT_WIDTH;
var panelHeight = Number(opts.height) > 0 ? Number(opts.height) : DEFAULT_HEIGHT;
var embedUrl = baseUrl + '/embed/' + encodeURIComponent(channelId);
var embedOrigin = baseUrl;
try {
// Derive the exact origin (scheme + host + port) rather than trusting the
// raw baseUrl string, so postMessage origin checks are precise.
embedOrigin = new URL(embedUrl, global.location ? global.location.href : undefined).origin;
} catch (e) {
embedOrigin = baseUrl;
}
var destroyed = false;
var panelOpen = false;
var iframeReady = false;
var iframeOrigin = '';
var launcher = document.createElement('button');
launcher.type = 'button';
launcher.setAttribute('aria-label', title);
launcher.textContent = '💬';
launcher.style.cssText = [
'position:fixed',
'z-index:2147483000',
'width:56px',
'height:56px',
'border-radius:50%',
'border:none',
'cursor:pointer',
'font-size:24px',
'box-shadow:0 4px 16px rgba(0,0,0,.18)',
'background:' + primaryColor,
'color:#fff',
'opacity:0.92',
'transition:opacity .2s',
positionStyles(position, 'launcher'),
].join(';');
var panel = document.createElement('div');
panel.style.cssText = [
'position:fixed',
'z-index:2147482999',
'width:' + panelWidth + 'px',
'max-width:calc(100vw - 32px)',
'height:' + panelHeight + 'px',
'max-height:calc(100vh - 100px)',
'border-radius:12px',
'overflow:hidden',
'box-shadow:0 8px 32px rgba(0,0,0,.2)',
'display:none',
'background:#fff',
positionStyles(position, 'panel'),
].join(';');
var iframe = document.createElement('iframe');
iframe.src = embedUrl;
iframe.style.cssText = 'width:100%;height:100%;border:none';
iframe.setAttribute('allow', 'clipboard-write');
var hostOrigin = '';
try {
hostOrigin = global.location ? global.location.origin : '';
} catch (e) { hostOrigin = ''; }
var crossOriginEmbed = hostOrigin && embedOrigin && hostOrigin !== embedOrigin;
var sandboxAttr = String(opts.sandbox || opts.sandboxMode || '').trim();
if (!sandboxAttr && opts.scriptEl) {
sandboxAttr = String(opts.scriptEl.getAttribute('data-sandbox') || '').trim();
}
if (sandboxAttr === 'true' || sandboxAttr === '1') {
sandboxAttr = 'allow-scripts allow-forms allow-popups allow-modals allow-same-origin';
}
if (!sandboxAttr && crossOriginEmbed) {
sandboxAttr = 'allow-scripts allow-forms allow-popups allow-modals allow-same-origin';
}
if (sandboxAttr && sandboxAttr !== 'false' && sandboxAttr !== '0') {
iframe.setAttribute('sandbox', sandboxAttr);
}
iframe.setAttribute('title', title);
panel.appendChild(iframe);
function isTrustedOrigin(origin) {
if (!origin || origin === 'null') return false;
return origin === embedOrigin;
}
function postToIframe(message) {
if (!iframe.contentWindow) return;
// Always target the known embed origin; never fall back to '*' so the
// publish token can't leak to an unexpected document.
iframe.contentWindow.postMessage(message, embedOrigin || '/');
}
function provideToken() {
loadToken(false).then(function (tok) {
if (!tok) return;
postToIframe({
source: HOST_SOURCE,
type: 'provide_token',
token: tok,
channel_id: channelId,
});
}).catch(function () { /* already logged; iframe stays awaiting */ });
}
function postHostPayload(type, payload) {
if (!iframe.contentWindow) {
console.warn('[WeKnora] iframe not ready');
return false;
}
postToIframe({ source: HOST_SOURCE, type: type, payload: payload || {} });
return true;
}
function whenIframeReady(fn, attempt) {
var tries = attempt || 0;
if (iframeReady && iframe.contentWindow) {
fn();
return;
}
if (tries >= 20) {
console.warn('[WeKnora] iframe not ready');
return;
}
setTimeout(function () { whenIframeReady(fn, tries + 1); }, 100);
}
function setContext(ctx) {
if (!ctx || typeof ctx !== 'object') {
console.warn('[WeKnora] setContext expects an object');
return;
}
postHostPayload('set_context', ctx);
}
function openWithQuery(query) {
var text = String(query || '').trim();
if (!text) {
console.warn('[WeKnora] openWithQuery requires a non-empty query');
return;
}
setOpen(true);
whenIframeReady(function () {
postHostPayload('open_with_query', { query: text });
});
}
function setLocale(locale) {
var loc = String(locale || '').trim();
if (!loc) {
console.warn('[WeKnora] setLocale requires a locale string');
return;
}
postHostPayload('set_locale', { locale: loc });
}
function onMessage(e) {
// Only trust messages coming from our own iframe window and origin.
if (e.source !== iframe.contentWindow) return;
if (!isTrustedOrigin(e.origin)) return;
if (!e.data || e.data.source !== EMBED_SOURCE) return;
if (e.data.channel_id && e.data.channel_id !== channelId) return;
if (!iframeOrigin) {
iframeOrigin = e.origin;
}
switch (e.data.type) {
case 'bootstrap_request':
provideToken();
break;
case 'ready':
iframeReady = true;
launcher.style.opacity = '1';
emit('ready', { channelId: channelId });
break;
case 'message_sent':
emit('message_sent', {
channelId: channelId,
sessionId: e.data.session_id,
query: e.data.query,
});
break;
case 'message_received':
emit('message_received', {
channelId: channelId,
sessionId: e.data.session_id,
content: e.data.content,
});
break;
default:
break;
}
}
function setOpen(next) {
panelOpen = !!next;
panel.style.display = panelOpen ? 'block' : 'none';
launcher.textContent = panelOpen ? '✕' : '💬';
if (panelOpen) {
emit('open', { channelId: channelId });
} else {
emit('close', { channelId: channelId });
}
}
function open() { setOpen(true); }
function close() { setOpen(false); }
function toggle() { setOpen(!panelOpen); }
function destroy() {
if (destroyed) return;
destroyed = true;
if (refreshTimer) clearTimeout(refreshTimer);
global.removeEventListener('message', onMessage);
if (launcher.parentNode) launcher.parentNode.removeChild(launcher);
if (panel.parentNode) panel.parentNode.removeChild(panel);
listeners = {};
if (instance === api) instance = null;
}
launcher.addEventListener('click', toggle);
iframe.addEventListener('load', function () {
// The embed page lives at embedOrigin; we cannot (and need not) read the
// cross-origin contentWindow.location. Just (re)provide the token.
iframeOrigin = embedOrigin;
provideToken();
});
document.body.appendChild(launcher);
document.body.appendChild(panel);
global.addEventListener('message', onMessage);
return {
open: open,
close: close,
toggle: toggle,
destroy: destroy,
isOpen: function () { return panelOpen; },
isReady: function () { return iframeReady; },
setContext: setContext,
openWithQuery: openWithQuery,
setLocale: setLocale,
};
}
var api = {
init: function (opts) {
if (instance) instance.destroy();
instance = createWidget(opts || {});
return instance;
},
open: function () { if (instance) instance.open(); },
close: function () { if (instance) instance.close(); },
toggle: function () { if (instance) instance.toggle(); },
destroy: function () { if (instance) instance.destroy(); },
on: function (event, handler) {
if (!handler || typeof handler !== 'function') return;
if (!listeners[event]) listeners[event] = [];
listeners[event].push(handler);
},
off: function (event, handler) {
if (!listeners[event]) return;
if (!handler) {
delete listeners[event];
return;
}
listeners[event] = listeners[event].filter(function (fn) { return fn !== handler; });
},
setContext: function (ctx) { if (instance) instance.setContext(ctx); },
openWithQuery: function (query) { if (instance) instance.openWithQuery(query); },
setLocale: function (locale) { if (instance) instance.setLocale(locale); },
};
global.WeKnora = api;
var legacyScript = document.currentScript;
if (legacyScript) {
var legacyChannel = legacyScript.getAttribute('data-channel');
var legacyToken = legacyScript.getAttribute('data-token');
var legacyTokenEndpoint = legacyScript.getAttribute('data-token-endpoint');
if (legacyChannel && (legacyToken || legacyTokenEndpoint)) {
api.init({
channel: legacyChannel,
token: legacyToken,
tokenEndpoint: legacyTokenEndpoint,
scriptEl: legacyScript,
position: legacyScript.getAttribute('data-position'),
primaryColor: legacyScript.getAttribute('data-primary-color'),
title: legacyScript.getAttribute('data-title'),
baseUrl: legacyScript.getAttribute('data-base-url'),
width: legacyScript.getAttribute('data-width'),
height: legacyScript.getAttribute('data-height'),
});
}
}
})(typeof window !== 'undefined' ? window : this);
+7 -13
View File
@@ -35,7 +35,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}>; images?: Array<{data: string}>; attachment_uploads?: Array<{data: string; file_name: string; file_size: number}>; 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}>; attachment_uploads?: Array<{data: string; file_name: string; file_size: number}>; method: string; url: string; embed_token?: string; embed_session_sig?: string }) => {
// 重置状态
output.value = '';
error.value = null;
@@ -45,8 +45,8 @@ export function useStream() {
// 获取API配置
const apiUrl = getApiBaseUrl();
// 获取JWT Token
const token = localStorage.getItem('weknora_token');
const embedToken = params.embed_token;
const token = embedToken || localStorage.getItem('weknora_token');
if (!token) {
error.value = i18n.global.t('error.tokenNotFound');
stopStream();
@@ -63,13 +63,6 @@ export function useStream() {
const selectedTenantId = localStorage.getItem('weknora_selected_tenant_id');
const tenantIdHeader: string | null = selectedTenantId || null;
// Validate knowledge_base_ids for agent-chat requests
// Note: knowledge_base_ids can be empty if user hasn't selected any, but we allow it
// The backend will handle the case when no knowledge bases are selected
const isAgentChat = params.url === '/api/v1/agent-chat';
// Removed validation - allow empty knowledge_base_ids array
// The backend should handle this case appropriately
// TTFB instrumentation: record the moment we kick off the request so
// we can compare it with the first answer chunk we receive from the
// server. This makes it possible to correlate the frontend-observed
@@ -132,7 +125,7 @@ export function useStream() {
if (params.attachment_uploads !== undefined && params.attachment_uploads.length > 0) {
postBody.attachment_uploads = params.attachment_uploads;
}
postBody.channel = "web";
postBody.channel = embedToken ? "embed" : "web";
lastStreamRequest.value = {
requestId: requestID,
@@ -146,10 +139,11 @@ export function useStream() {
method: params.method,
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`,
"Authorization": embedToken ? `Embed ${embedToken}` : `Bearer ${token}`,
"Accept-Language": i18n.global.locale?.value || localStorage.getItem('locale') || 'zh-CN',
"X-Request-ID": requestID,
...(tenantIdHeader ? { "X-Tenant-ID": tenantIdHeader } : {}),
...(!embedToken && tenantIdHeader ? { "X-Tenant-ID": tenantIdHeader } : {}),
...(params.embed_session_sig ? { "X-Embed-Session": params.embed_session_sig } : {}),
},
body:
params.method == "POST"
+516
View File
@@ -0,0 +1,516 @@
import { get, post, put, del } from '@/utils/request'
import { resolveEmbedBaseUrl } from '@/utils/embedBaseUrl'
export interface EmbedChannel {
id: string
tenant_id: number
agent_id: string
name: string
enabled: boolean
allowed_origins: string[]
welcome_message: string
rate_limit_per_minute: number
rate_limit_per_day?: number
primary_color?: string
page_title?: string
header_title_mode?: HeaderTitleMode
show_suggested_questions?: boolean
widget_position?: WidgetPosition
allow_web_search?: boolean
allow_memory?: boolean
allow_file_upload?: boolean
default_locale?: string
webhook_url?: string
has_webhook_secret?: boolean
publish_token?: string
created_at: string
updated_at: string
}
export interface EmbedChannelPublicConfig {
channel_id: string
name: string
display_title?: string
knowledge_base_ids?: string[]
agent_id: string
agent_name?: string
agent_avatar?: string
welcome_message: string
primary_color?: string
page_title?: string
header_title_mode?: HeaderTitleMode
show_suggested_questions?: boolean
widget_position?: WidgetPosition
allow_web_search?: boolean
allow_memory?: boolean
allow_file_upload?: boolean
agent_web_search_enabled?: boolean
agent_image_upload_enabled?: boolean
default_locale?: string
}
export type EmbedLocaleTag = 'zh-CN' | 'en-US' | 'ko-KR' | 'ru-RU' | ''
export interface EmbedChannelStats {
session_count: number
}
export type HeaderTitleMode = 'channel' | 'session'
export type WidgetPosition = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left'
/** Prefix of short-lived embed session tokens minted by the backend. */
export const EMBED_SESSION_TOKEN_PREFIX = 'ems_'
/** Whether a token is already a short-lived session token (secure mode). */
export function isEmbedSessionToken(token: string): boolean {
return typeof token === 'string' && token.trim().startsWith(EMBED_SESSION_TOKEN_PREFIX)
}
export async function listEmbedChannels(agentId: string) {
return get<{ success: boolean; data: EmbedChannel[] }>(`/api/v1/agents/${agentId}/embed-channels`)
}
export async function listAllEmbedChannels() {
return get<{ success: boolean; data: EmbedChannel[] }>('/api/v1/embed-channels')
}
export async function createEmbedChannel(agentId: string, data: Partial<EmbedChannel>) {
return post<{ success: boolean; data: EmbedChannel }>(`/api/v1/agents/${agentId}/embed-channels`, data)
}
export async function updateEmbedChannel(channelId: string, data: Partial<EmbedChannel>) {
return put<{ success: boolean; data: EmbedChannel }>(`/api/v1/embed-channels/${channelId}`, data)
}
export async function deleteEmbedChannel(channelId: string) {
return del(`/api/v1/embed-channels/${channelId}`)
}
export async function rotateEmbedToken(channelId: string) {
return post<{ success: boolean; data: EmbedChannel }>(`/api/v1/embed-channels/${channelId}/rotate-token`, {})
}
/** Short-lived session token for management UI preview (JWT auth, no publish token needed). */
export async function getEmbedChannelStats(channelId: string) {
return get<{ success: boolean; data: EmbedChannelStats }>(
`/api/v1/embed-channels/${channelId}/stats`,
)
}
export async function issueEmbedPreviewSession(channelId: string) {
return post<{ success: boolean; data: { session_token: string; expires_in: number } }>(
`/api/v1/embed-channels/${channelId}/preview-session`,
{},
)
}
export interface SuggestedQuestion {
question: string
source?: string
}
export async function getEmbedChunkById(channelId: string, token: string, chunkId: string) {
return get<{ success: boolean; data: { content?: string } }>(
`/api/v1/embed/${channelId}/chunks/${chunkId}`,
{ headers: { Authorization: `Embed ${token}` } },
)
}
export async function getEmbedSuggestedQuestions(channelId: string, token: string, limit = 6) {
return get<{ success: boolean; data: { questions: SuggestedQuestion[] } }>(
`/api/v1/embed/${channelId}/suggested-questions?limit=${limit}`,
{ headers: { Authorization: `Embed ${token}` } },
)
}
export async function getEmbedConfig(channelId: string, token: string) {
return get<{ success: boolean; data: EmbedChannelPublicConfig }>(
`/api/v1/embed/${channelId}/config`,
{ headers: { Authorization: `Embed ${token}` } },
)
}
export async function createEmbedSession(channelId: string, token: string) {
return post<{ success: boolean; data: { id: string; sig: string } }>(
`/api/v1/embed/${channelId}/sessions`,
{},
{ headers: { Authorization: `Embed ${token}` } },
)
}
export async function exchangeEmbedSession(channelId: string, publishToken: string) {
return post<{ success: boolean; data: { session_token: string; expires_in: number } }>(
`/api/v1/embed/${channelId}/exchange`,
{},
{ headers: { Authorization: `Embed ${publishToken}` } },
)
}
export async function stopEmbedSession(
channelId: string,
token: string,
sessionId: string,
messageId: string,
sessionSig: string,
) {
const headers: Record<string, string> = {
Authorization: `Embed ${token}`,
'X-Embed-Session': sessionSig,
}
return post(`/api/v1/embed/${channelId}/sessions/${sessionId}/stop`, { message_id: messageId }, { headers })
}
export async function getEmbedMessageList(
channelId: string,
token: string,
sessionId: string,
limit: number,
beforeTime?: string,
sig?: string,
) {
const params = new URLSearchParams({ limit: String(limit) })
if (beforeTime) {
params.set('before_time', beforeTime)
}
const headers: Record<string, string> = { Authorization: `Embed ${token}` }
// Signed session handle — sent as a header so it never lands in URL/access logs.
if (sig) headers['X-Embed-Session'] = sig
return get<{ success: boolean; data: unknown[] }>(
`/api/v1/embed/${channelId}/messages/${sessionId}/load?${params.toString()}`,
{ headers },
)
}
const EMBED_MSG_SOURCE = 'weknora-embed'
const EMBED_HOST_SOURCE = 'weknora-host'
// The exact parent origin, learned from the first trusted host message
// (trust-on-first-use). Once known, every inbound/outbound message is pinned to
// it so conversation content is never broadcast to an unexpected window.
let verifiedParentOrigin = ''
function referrerParentOrigin(): string {
if (window.parent === window) return ''
try {
if (document.referrer) {
return new URL(document.referrer).origin
}
} catch {
// ignore malformed referrer
}
return ''
}
/** Best-known parent origin: verified handshake first, then referrer. */
function knownParentOrigin(): string {
return verifiedParentOrigin || referrerParentOrigin()
}
function isTrustedParentMessage(event: MessageEvent): boolean {
if (window.parent === window) return false
if (event.source !== window.parent) return false
if (!event.data || event.data.source !== EMBED_HOST_SOURCE) return false
if (typeof event.origin !== 'string' || event.origin === 'null') return false
const expected = knownParentOrigin()
if (expected) {
if (event.origin !== expected) return false
} else {
// First trusted handshake with no referrer hint: pin to this origin.
verifiedParentOrigin = event.origin
}
return true
}
/**
* Post a message to the host page.
* `sensitive` payloads (conversation content) are dropped when the parent
* origin is unknown rather than broadcast to '*'. Non-sensitive handshake
* messages (bootstrap_request/ready) may fall back to '*' so token handoff can
* still bootstrap when the referrer is stripped.
*/
function postToParent(payload: Record<string, unknown>, opts?: { sensitive?: boolean }) {
if (window.parent === window) return
const target = knownParentOrigin()
if (!target) {
if (opts?.sensitive) return
window.parent.postMessage({ source: EMBED_MSG_SOURCE, ...payload }, '*')
return
}
window.parent.postMessage({ source: EMBED_MSG_SOURCE, ...payload }, target)
}
/** Notify the parent page that the embed widget is ready. */
export function postEmbedReady(channelId: string) {
postToParent({ type: 'ready', channel_id: channelId })
}
/** Request a publish token from the parent host page. */
export function postEmbedBootstrapRequest(channelId: string) {
postToParent({ type: 'bootstrap_request', channel_id: channelId })
}
/** Notify the parent page when a user message is sent. */
export function postEmbedMessageSent(channelId: string, sessionId: string, query: string) {
postToParent(
{
type: 'message_sent',
channel_id: channelId,
session_id: sessionId,
query,
},
{ sensitive: true },
)
}
/** Relay a chat event to the channel webhook (server-side, best-effort). */
export function relayEmbedWebhookEvent(
channelId: string,
token: string,
sessionId: string,
sessionSig: string,
body: { type: 'message_sent' | 'message_received'; query?: string; content?: string },
) {
const headers: Record<string, string> = {
Authorization: `Embed ${token}`,
'X-Embed-Session': sessionSig,
}
void post(
`/api/v1/embed/${channelId}/sessions/${sessionId}/events`,
{ type: body.type, session_id: sessionId, query: body.query, content: body.content },
{ headers },
).catch(() => {
// Webhook relay must not block chat.
})
}
/** Notify the parent page when an assistant reply completes. */
export function postEmbedMessageReceived(channelId: string, sessionId: string, content: string) {
postToParent(
{
type: 'message_received',
channel_id: channelId,
session_id: sessionId,
content,
},
{ sensitive: true },
)
}
export function parseEmbedTokenFromLocation(): string {
const queryToken = new URLSearchParams(window.location.search).get('token')
if (queryToken) return queryToken
const hash = window.location.hash.startsWith('#') ? window.location.hash.slice(1) : ''
if (!hash) return ''
return new URLSearchParams(hash).get('token') || ''
}
export function buildEmbedURL(
channelId: string,
token?: string,
opts?: { locale?: string; refreshKey?: number; baseUrl?: string },
) {
const base = safeBaseUrl(opts?.baseUrl) || resolveEmbedBaseUrl()
let path = `${base}/embed/${encodeURIComponent(channelId)}`
const params = new URLSearchParams()
if (opts?.locale?.trim()) params.set('locale', opts.locale.trim())
if (opts?.refreshKey) params.set('r', String(opts.refreshKey))
const qs = params.toString()
if (qs) path += `?${qs}`
if (token) path += `#token=${encodeURIComponent(token)}`
return path
}
/** Escape a value for safe interpolation inside an HTML double-quoted attribute. */
function escapeHtmlAttr(value: string): string {
return String(value)
.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
}
/** Validate that a base URL is a well-formed http(s) origin; fall back otherwise. */
function safeBaseUrl(raw?: string): string {
const fallback = window.location.origin
if (!raw) return fallback
try {
const u = new URL(raw, window.location.href)
if (u.protocol !== 'http:' && u.protocol !== 'https:') return fallback
return u.origin
} catch {
return fallback
}
}
export function buildEmbedSnippet(channelId: string, token?: string) {
// A bare iframe has no token-handoff host, so the snippet must carry the
// publish token in the URL hash, otherwise the embed page cannot bootstrap.
const url = escapeHtmlAttr(buildEmbedURL(channelId, token))
return `<iframe src="${url}" style="width:400px;height:600px;border:none;border-radius:12px" allow="clipboard-write"></iframe>`
}
export function buildWidgetSnippet(
channelId: string,
token: string,
opts?: { primaryColor?: string; title?: string; position?: WidgetPosition; baseUrl?: string },
) {
const base = safeBaseUrl(opts?.baseUrl)
const position = opts?.position || 'bottom-right'
const attrs = [
`src="${escapeHtmlAttr(`${base}/weknora-widget.js`)}"`,
`data-channel="${escapeHtmlAttr(channelId)}"`,
`data-token="${escapeHtmlAttr(token)}"`,
`data-position="${escapeHtmlAttr(position)}"`,
]
if (opts?.primaryColor) attrs.push(`data-primary-color="${escapeHtmlAttr(opts.primaryColor)}"`)
if (opts?.title) attrs.push(`data-title="${escapeHtmlAttr(opts.title)}"`)
// Cross-origin embed: add data-sandbox="true" when using a dedicated embed subdomain.
return `<script ${attrs.join('\n ')}></script>`
}
/** Default placeholder for the integrator's own token-minting endpoint. */
export const SECURE_TOKEN_ENDPOINT_PLACEHOLDER = 'https://your-backend.example.com/weknora/embed-token'
/**
* Secure-mode widget snippet: the page references an endpoint on the
* integrator's own backend (data-token-endpoint) instead of carrying the
* publish token. The publish token never reaches the browser.
*/
export function buildSecureWidgetSnippet(
channelId: string,
opts?: { primaryColor?: string; title?: string; position?: WidgetPosition; baseUrl?: string; tokenEndpoint?: string },
) {
const base = safeBaseUrl(opts?.baseUrl)
const position = opts?.position || 'bottom-right'
const endpoint = opts?.tokenEndpoint || SECURE_TOKEN_ENDPOINT_PLACEHOLDER
const attrs = [
`src="${escapeHtmlAttr(`${base}/weknora-widget.js`)}"`,
`data-channel="${escapeHtmlAttr(channelId)}"`,
`data-token-endpoint="${escapeHtmlAttr(endpoint)}"`,
`data-position="${escapeHtmlAttr(position)}"`,
]
if (opts?.primaryColor) attrs.push(`data-primary-color="${escapeHtmlAttr(opts.primaryColor)}"`)
if (opts?.title) attrs.push(`data-title="${escapeHtmlAttr(opts.title)}"`)
return `<script ${attrs.join('\n ')}></script>`
}
/**
* Server-side reference (Node/Express) for the token-minting endpoint that
* secure mode points at. The publish token stays on the server; the endpoint
* exchanges it for a short-lived session token and returns that to the page.
*/
export function buildSecureServerNodeExample(channelId: string, opts?: { baseUrl?: string }) {
const base = safeBaseUrl(opts?.baseUrl)
const exchangeUrl = `${base}/api/v1/embed/${channelId}/exchange`
return [
`// Node/Express — keep WEKNORA_PUBLISH_TOKEN only on the server (env var).`,
`app.get('/weknora/embed-token', async (req, res) => {`,
` // Only mint for logged-in visitors — e.g. session cookie or Bearer token.`,
` const auth = req.headers.authorization || ''`,
` const hasSession = Boolean(req.cookies?.session_id)`,
` if (!hasSession && !auth.startsWith('Bearer ')) {`,
` return res.status(401).json({ error: 'unauthorized' })`,
` }`,
` const r = await fetch('${exchangeUrl}', {`,
` method: 'POST',`,
` headers: {`,
` Authorization: 'Embed ' + process.env.WEKNORA_PUBLISH_TOKEN,`,
` Origin: 'https://your-site.example.com', // must match channel allowed_origins`,
` },`,
` })`,
` const body = await r.json()`,
` if (!body?.data?.session_token) return res.status(502).json({ error: 'mint failed' })`,
` res.json({ token: body.data.session_token, expiresIn: body.data.expires_in })`,
`})`,
].join('\n')
}
export function buildSecureServerGoExample(channelId: string, opts?: { baseUrl?: string }) {
const base = safeBaseUrl(opts?.baseUrl)
const exchangeUrl = `${base}/api/v1/embed/${channelId}/exchange`
return [
`// Go net/http — keep WEKNORA_PUBLISH_TOKEN only on the server (env var).`,
`func embedTokenHandler(w http.ResponseWriter, r *http.Request) {`,
` if r.Header.Get("Authorization") == "" && r.Header.Get("Cookie") == "" {`,
` http.Error(w, \`{"error":"unauthorized"}\`, http.StatusUnauthorized)`,
` return`,
` }`,
` req, _ := http.NewRequest(http.MethodPost, "${exchangeUrl}", nil)`,
` req.Header.Set("Authorization", "Embed "+os.Getenv("WEKNORA_PUBLISH_TOKEN"))`,
` req.Header.Set("Origin", "https://your-site.example.com") // must match channel allowed_origins`,
` resp, err := http.DefaultClient.Do(req)`,
` if err != nil || resp.StatusCode >= 300 {`,
` http.Error(w, \`{"error":"mint failed"}\`, http.StatusBadGateway)`,
` return`,
` }`,
` defer resp.Body.Close()`,
` var body struct { Data struct { SessionToken string \`json:"session_token"\` ExpiresIn int \`json:"expires_in"\` } \`json:"data"\` }`,
` if json.NewDecoder(resp.Body).Decode(&body) != nil || body.Data.SessionToken == "" {`,
` http.Error(w, \`{"error":"mint failed"}\`, http.StatusBadGateway)`,
` return`,
` }`,
` w.Header().Set("Content-Type", "application/json")`,
` json.NewEncoder(w).Encode(map[string]any{"token": body.Data.SessionToken, "expiresIn": body.Data.ExpiresIn})`,
`}`,
].join('\n')
}
/** @deprecated Use buildSecureServerNodeExample */
export function buildSecureServerExample(channelId: string, opts?: { baseUrl?: string }) {
return buildSecureServerNodeExample(channelId, opts)
}
export function buildSecureServerExamples(channelId: string, opts?: { baseUrl?: string }) {
return [
buildSecureServerNodeExample(channelId, opts),
'',
buildSecureServerGoExample(channelId, opts),
].join('\n')
}
/** Listen for context injected by the parent page (embed host). */
export function onEmbedHostContext(handler: (payload: Record<string, unknown>) => void) {
const listener = (e: MessageEvent) => {
if (!isTrustedParentMessage(e) || e.data.type !== 'set_context') return
handler(e.data.payload || {})
}
window.addEventListener('message', listener)
return () => window.removeEventListener('message', listener)
}
/** Listen for a publish token provided by the parent host page. */
export function onEmbedHostToken(handler: (token: string, channelId?: string) => void) {
const listener = (e: MessageEvent) => {
if (!isTrustedParentMessage(e) || e.data.type !== 'provide_token') return
const token = String(e.data.token || '').trim()
if (!token) return
handler(token, e.data.channel_id)
}
window.addEventListener('message', listener)
return () => window.removeEventListener('message', listener)
}
/** Listen for locale changes from the parent host page. */
export function onEmbedHostLocale(handler: (locale: string) => void) {
const listener = (e: MessageEvent) => {
if (!isTrustedParentMessage(e) || e.data.type !== 'set_locale') return
const locale = String(e.data.payload?.locale || e.data.locale || '').trim()
if (!locale) return
handler(locale)
}
window.addEventListener('message', listener)
return () => window.removeEventListener('message', listener)
}
/** Listen for a pre-filled query from the parent host page. */
export function onEmbedHostOpenWithQuery(handler: (query: string) => void) {
const listener = (e: MessageEvent) => {
if (!isTrustedParentMessage(e) || e.data.type !== 'open_with_query') return
const query = String(e.data.payload?.query || e.data.query || '').trim()
if (!query) return
handler(query)
}
window.addEventListener('message', listener)
return () => window.removeEventListener('message', listener)
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,325 @@
<template>
<t-drawer
:visible="visible"
:header="title || $t('embedPublish.preview')"
size="720px"
:footer="false"
class="embed-preview-drawer"
@close="emit('update:visible', false)"
>
<div class="preview-body">
<template v-if="mode === 'iframe'">
<p class="preview-hint">{{ $t('embedPublish.previewIframeHint') }}</p>
<div class="device-frame">
<div class="device-frame__chrome">
<span class="device-frame__dot" />
<span class="device-frame__dot" />
<span class="device-frame__dot" />
<span class="device-frame__url">{{ previewUrlLabel }}</span>
</div>
<div class="device-frame__screen">
<t-loading v-if="!iframeSrc || !iframeReady" size="small" :text="$t('embedPublish.previewLoading')" />
<iframe
v-else
:key="iframeSrc"
:src="iframeSrc"
class="preview-iframe"
allow="clipboard-write"
/>
</div>
</div>
</template>
<template v-else>
<p class="preview-hint">{{ $t('embedPublish.previewWidgetHint') }}</p>
<div class="widget-shell" :class="`pos-${position}`">
<div class="widget-mock-page">
<div class="widget-mock-page__title">{{ $t('embedPublish.previewMockPage') }}</div>
<div class="widget-mock-page__line" />
<div class="widget-mock-page__line widget-mock-page__line--short" />
</div>
<button
type="button"
class="widget-launcher"
:style="{ background: primaryColor || 'var(--td-brand-color)' }"
:aria-label="widgetOpen ? $t('common.close') : $t('embedPublish.preview')"
@click="widgetOpen = !widgetOpen"
>
<t-icon :name="widgetOpen ? 'close' : 'chat'" />
</button>
<transition name="widget-panel">
<div v-show="widgetOpen" class="widget-panel">
<iframe
v-if="iframeSrc && iframeReady"
:key="`widget-${iframeSrc}`"
:src="iframeSrc"
class="preview-iframe"
:title="title || $t('embedPublish.preview')"
allow="clipboard-write"
/>
</div>
</transition>
</div>
</template>
</div>
</t-drawer>
</template>
<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue'
import { buildEmbedURL, type WidgetPosition } from '@/api/embed'
const props = defineProps<{
visible: boolean
channelId: string
token: string
mode?: 'iframe' | 'widget'
title?: string
primaryColor?: string
position?: WidgetPosition
/**
* Bumped by the parent every time a preview is (re)opened. Folded into the
* iframe URL so the embed page fully reloads and re-fetches the latest saved
* config — otherwise re-previewing after an edit shows stale content until a
* full page refresh.
*/
refreshKey?: number
/** Channel default locale — passed in the iframe URL so the first paint uses the right language. */
locale?: string
}>()
const emit = defineEmits<{
(e: 'update:visible', value: boolean): void
}>()
const mode = computed(() => props.mode || 'iframe')
const widgetOpen = ref(true)
/** Defer iframe until the drawer has laid out — avoids embed autosize measuring a 0-size frame. */
const iframeReady = ref(false)
const iframeSrc = computed(() => {
if (!props.channelId || !props.token) return ''
return buildEmbedURL(props.channelId, props.token, {
locale: props.locale,
refreshKey: props.refreshKey,
})
})
const previewUrlLabel = computed(() => {
if (!props.channelId) return ''
try {
return new URL(buildEmbedURL(props.channelId)).pathname
} catch {
return `/embed/${props.channelId}`
}
})
watch(() => props.visible, async (open) => {
if (open) {
widgetOpen.value = true
iframeReady.value = false
await nextTick()
iframeReady.value = true
} else {
iframeReady.value = false
}
}, { immediate: true })
</script>
<style scoped lang="less">
.preview-body {
display: flex;
flex-direction: column;
height: 100%;
gap: 14px;
}
.preview-hint {
flex-shrink: 0;
margin: 0;
padding: 10px 12px;
border-radius: 8px;
font-size: 13px;
line-height: 1.55;
color: var(--td-text-color-secondary);
background: var(--td-bg-color-secondarycontainer);
border: 1px solid var(--td-component-stroke);
}
.device-frame {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
border: 1px solid var(--td-component-stroke);
border-radius: 12px;
overflow: hidden;
background: var(--td-bg-color-container);
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.06);
&__chrome {
display: flex;
align-items: center;
gap: 6px;
padding: 10px 14px;
background: var(--td-bg-color-secondarycontainer);
border-bottom: 1px solid var(--td-component-stroke);
}
&__dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--td-component-stroke);
&:nth-child(1) { background: #ff5f57; }
&:nth-child(2) { background: #febc2e; }
&:nth-child(3) { background: #28c840; }
}
&__url {
flex: 1;
margin-left: 8px;
padding: 4px 10px;
border-radius: 6px;
font-size: 12px;
color: var(--td-text-color-placeholder);
background: var(--td-bg-color-container);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
&__screen {
flex: 1;
min-height: 420px;
background: #f5f7fa;
display: flex;
align-items: center;
justify-content: center;
}
}
.preview-iframe {
width: 100%;
height: 100%;
border: none;
background: #fff;
display: block;
}
.widget-shell {
position: relative;
flex: 1;
min-height: 480px;
border: 1px solid var(--td-component-stroke);
border-radius: 12px;
overflow: hidden;
background: linear-gradient(180deg, #f8fafc 0%, #eef2f7 100%);
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.06);
}
.widget-mock-page {
padding: 28px 32px;
&__title {
font-size: 14px;
font-weight: 600;
color: var(--td-text-color-placeholder);
margin-bottom: 16px;
}
&__line {
height: 10px;
border-radius: 5px;
background: rgba(0, 0, 0, 0.06);
margin-bottom: 10px;
max-width: 72%;
&--short {
max-width: 48%;
}
}
}
.widget-launcher {
position: absolute;
display: inline-flex;
align-items: center;
justify-content: center;
width: 48px;
height: 48px;
border: none;
border-radius: 50%;
color: #fff;
font-size: 20px;
cursor: pointer;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.18);
z-index: 3;
transition: transform 0.15s ease;
&:hover {
transform: scale(1.04);
}
}
.widget-panel {
position: absolute;
width: 380px;
max-width: calc(100% - 32px);
height: 500px;
max-height: calc(100% - 88px);
border-radius: 12px;
overflow: hidden;
background: #fff;
box-shadow: 0 12px 40px rgba(15, 23, 42, 0.18);
z-index: 2;
border: 1px solid var(--td-component-stroke);
}
.widget-panel-enter-active,
.widget-panel-leave-active {
transition: opacity 0.18s ease, transform 0.18s ease;
}
.widget-panel-enter-from,
.widget-panel-leave-to {
opacity: 0;
transform: translateY(8px) scale(0.98);
}
.pos-bottom-right {
.widget-launcher { right: 20px; bottom: 20px; }
.widget-panel { right: 20px; bottom: 80px; }
}
.pos-bottom-left {
.widget-launcher { left: 20px; bottom: 20px; }
.widget-panel { left: 20px; bottom: 80px; }
}
.pos-top-right {
.widget-launcher { right: 20px; top: 20px; }
.widget-panel { right: 20px; top: 80px; }
}
.pos-top-left {
.widget-launcher { left: 20px; top: 20px; }
.widget-panel { left: 20px; top: 80px; }
}
</style>
<!--
Non-scoped: make the drawer body a full-height flex host so the device frame
/ widget shell can grow to fill the available space instead of sitting as a
fixed-height island. Namespaced under .embed-preview-drawer.
-->
<style lang="less">
.embed-preview-drawer {
.t-drawer__body {
display: flex;
flex-direction: column;
padding: 16px 18px;
}
}
</style>
+471
View File
@@ -0,0 +1,471 @@
<template>
<div class="embed-input-box" :class="{ 'is-replying': isReplying }">
<div v-if="uploadedAttachments.length" class="embed-input-box__files">
<div v-for="(att, index) in uploadedAttachments" :key="`${att.file.name}-${index}`" class="embed-file-chip">
<t-icon name="file" size="14px" />
<span class="embed-file-chip__name">{{ att.file.name }}</span>
<button type="button" class="embed-file-chip__remove" @click="removeAttachment(index)">
<t-icon name="close" size="12px" />
</button>
</div>
</div>
<div v-if="uploadedImages.length" class="embed-input-box__images">
<div v-for="(img, index) in uploadedImages" :key="img.preview" class="embed-image-thumb">
<img :src="img.preview" :alt="img.file.name" />
<button type="button" class="embed-image-thumb__remove" @click="removeImage(index)">
<t-icon name="close" size="12px" />
</button>
</div>
</div>
<t-textarea
v-if="textareaReady"
ref="textareaRef"
v-model="query"
class="embed-input-box__textarea"
:class="{ 'has-images': uploadedImages.length > 0 }"
:placeholder="t('input.placeholder')"
:autosize="{ minRows: 2, maxRows: 6 }"
@keydown="onKeydown"
@compositionstart="isComposing = true"
@compositionend="isComposing = false"
/>
<input
ref="imageInputRef"
type="file"
accept="image/jpeg,image/png,image/gif,image/webp"
multiple
class="embed-hidden-file-input"
@change="handleImageSelect"
/>
<input
ref="fileInputRef"
type="file"
accept=".pdf,.doc,.docx,.txt,.md,.csv,.xlsx,.xls,.ppt,.pptx,application/pdf,text/plain"
multiple
class="embed-hidden-file-input"
@change="handleFileSelect"
/>
<div class="embed-input-box__bar">
<div v-if="showWebSearchToggle || showFileUploadToggle" class="embed-input-box__controls">
<t-tooltip v-if="showWebSearchToggle" placement="top">
<template #content>
{{ webSearchEnabled ? t('input.webSearch.toggleOff') : t('input.webSearch.toggleOn') }}
</template>
<button
type="button"
class="embed-control-btn embed-websearch-btn"
:class="{ active: webSearchEnabled }"
:aria-label="t('input.webSearch.label')"
@click="toggleWebSearch"
>
<svg width="18" height="18" viewBox="0 0 18 18" fill="none" aria-hidden="true">
<circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.2" fill="none" />
<path d="M 9 2 A 3.5 7 0 0 0 9 16" stroke="currentColor" stroke-width="1.2" fill="none" />
<path d="M 9 2 A 3.5 7 0 0 1 9 16" stroke="currentColor" stroke-width="1.2" fill="none" />
<line x1="2.94" y1="5.5" x2="15.06" y2="5.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" />
<line x1="2.94" y1="12.5" x2="15.06" y2="12.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" />
</svg>
</button>
</t-tooltip>
<t-tooltip v-if="showFileUploadToggle" placement="top" :content="t('input.imageUpload.tooltip')">
<button
type="button"
class="embed-control-btn embed-image-btn"
:class="{ active: uploadedImages.length > 0 }"
:aria-label="t('input.imageUpload.label')"
@click="triggerImageUpload"
>
<t-icon name="image" size="18px" />
</button>
</t-tooltip>
<t-tooltip v-if="showFileUploadToggle" placement="top" :content="t('input.fileUpload.tooltip')">
<button
type="button"
class="embed-control-btn embed-file-btn"
:class="{ active: uploadedAttachments.length > 0 }"
:aria-label="t('input.fileUpload.label')"
@click="triggerFileUpload"
>
<t-icon name="attach" size="18px" />
</button>
</t-tooltip>
</div>
<div class="embed-input-box__actions">
<t-tooltip v-if="isReplying" :content="t('input.stopGeneration')" placement="top">
<button type="button" class="embed-stop-btn" @click="emit('stop-generation')">
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true">
<rect x="5" y="5" width="6" height="6" rx="1" />
</svg>
</button>
</t-tooltip>
<button
v-else
type="button"
class="embed-send-btn"
:class="{ disabled: !canSend }"
:aria-label="t('input.send')"
@click="submit"
>
<img src="@/assets/img/sending-aircraft.svg" :alt="t('input.send')" />
</button>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { embedToast } from '@/utils/embedToast'
import { isEmbedImageFile } from '@/utils/embedFile'
const props = defineProps<{
isReplying: boolean
showWebSearchToggle?: boolean
webSearchEnabled?: boolean
showFileUploadToggle?: boolean
}>()
const emit = defineEmits<{
(e: 'send-msg', query: string, imageFiles: File[], attachmentFiles: File[]): void
(e: 'stop-generation'): void
(e: 'update:webSearchEnabled', value: boolean): void
}>()
const { t } = useI18n()
const query = ref('')
const isComposing = ref(false)
const textareaReady = ref(false)
const textareaRef = ref<{ $el?: HTMLElement } | HTMLTextAreaElement | null>(null)
const getTextareaEl = (): HTMLTextAreaElement | null => {
const el = textareaRef.value
if (!el) return null
if (el instanceof HTMLTextAreaElement) return el
const inner = el.$el?.querySelector?.('textarea')
return inner instanceof HTMLTextAreaElement ? inner : null
}
onMounted(() => {
nextTick(() => {
textareaReady.value = true
})
})
const imageInputRef = ref<HTMLInputElement | null>(null)
const fileInputRef = ref<HTMLInputElement | null>(null)
const uploadedImages = ref<Array<{ file: File; preview: string }>>([])
const uploadedAttachments = ref<Array<{ file: File }>>([])
const canSend = computed(() =>
query.value.trim().length > 0 || uploadedImages.value.length > 0 || uploadedAttachments.value.length > 0)
const toggleWebSearch = () => {
const next = !props.webSearchEnabled
emit('update:webSearchEnabled', next)
embedToast(next ? t('input.messages.webSearchEnabled') : t('input.messages.webSearchDisabled'))
}
const triggerImageUpload = () => {
imageInputRef.value?.click()
}
const triggerFileUpload = () => {
fileInputRef.value?.click()
}
const addImageFiles = (files: File[]) => {
const allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
const maxSize = 10 * 1024 * 1024
for (const file of files) {
if (!isEmbedImageFile(file)) continue
if (uploadedImages.value.length >= 5) {
embedToast(t('chat.imageTooMany'))
break
}
if (!allowed.includes(file.type)) {
embedToast(t('chat.imageTypeSizeError'))
continue
}
if (file.size > maxSize) {
embedToast(t('chat.imageTypeSizeError'))
continue
}
uploadedImages.value.push({ file, preview: URL.createObjectURL(file) })
}
}
const handleImageSelect = (event: Event) => {
const input = event.target as HTMLInputElement
if (!input.files) return
addImageFiles(Array.from(input.files))
input.value = ''
}
const addAttachmentFiles = (files: File[]) => {
const maxSize = 20 * 1024 * 1024
for (const file of files) {
if (isEmbedImageFile(file)) continue
if (uploadedAttachments.value.length >= 5) {
embedToast(t('input.fileUpload.tooMany'))
break
}
if (file.size > maxSize) {
embedToast(t('input.fileUpload.tooLarge'))
continue
}
uploadedAttachments.value.push({ file })
}
}
const handleFileSelect = (event: Event) => {
const input = event.target as HTMLInputElement
if (!input.files) return
addAttachmentFiles(Array.from(input.files))
input.value = ''
}
const removeAttachment = (index: number) => {
uploadedAttachments.value.splice(index, 1)
}
const removeImage = (index: number) => {
const removed = uploadedImages.value.splice(index, 1)
if (removed.length > 0) URL.revokeObjectURL(removed[0].preview)
}
const submit = () => {
if (props.isReplying || !canSend.value) return
const val = query.value.trim()
const imageFiles = uploadedImages.value.map((img) => img.file)
const attachmentFiles = uploadedAttachments.value.map((att) => att.file)
const textarea = getTextareaEl()
if (textarea) textarea.blur()
emit('send-msg', val, imageFiles, attachmentFiles)
if (getTextareaEl()) query.value = ''
uploadedImages.value.forEach((img) => URL.revokeObjectURL(img.preview))
uploadedImages.value = []
uploadedAttachments.value = []
}
const onKeydown = (_val: string, ctx: { e: KeyboardEvent }) => {
const e = ctx?.e
if (!e || e.keyCode !== 13) return
if (isComposing.value) return
if (e.shiftKey || e.ctrlKey) return
e.preventDefault()
submit()
}
onUnmounted(() => {
uploadedImages.value.forEach((img) => URL.revokeObjectURL(img.preview))
})
</script>
<style scoped lang="less">
.embed-input-box {
position: relative;
width: 100%;
max-width: 800px;
margin: 0 auto;
background: var(--td-bg-color-container, #fff);
border-radius: 12px;
border: 0.5px solid var(--td-component-border, #e7e7e7);
box-shadow: 0 6px 6px rgba(0, 0, 0, 0.04), 0 12px 12px -1px rgba(0, 0, 0, 0.08);
transition: border-color 0.15s ease;
&:focus-within {
border-color: var(--embed-primary, var(--td-brand-color, #07c05f));
}
&__files {
display: flex;
flex-wrap: wrap;
gap: 8px;
padding: 12px 16px 0;
}
&__images {
display: flex;
flex-wrap: wrap;
gap: 8px;
padding: 12px 16px 0;
}
&__textarea {
width: 100%;
:deep(.t-textarea__inner) {
border: none;
box-shadow: none;
background: transparent;
padding: 14px 16px 52px;
font-size: 14px;
line-height: 1.5;
resize: none;
}
&.has-images :deep(.t-textarea__inner) {
padding-top: 8px;
}
}
&__bar {
position: absolute;
left: 12px;
right: 12px;
bottom: 12px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
pointer-events: none;
> * {
pointer-events: auto;
}
}
&__controls {
display: flex;
align-items: center;
gap: 6px;
}
&__actions {
margin-left: auto;
display: flex;
align-items: center;
}
}
.embed-hidden-file-input {
display: none;
}
.embed-file-chip {
display: inline-flex;
align-items: center;
gap: 6px;
max-width: 220px;
padding: 6px 10px;
border-radius: 8px;
background: var(--td-bg-color-secondarycontainer, #f3f3f3);
font-size: 12px;
&__name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
&__remove {
border: none;
background: transparent;
cursor: pointer;
padding: 0;
color: var(--td-text-color-placeholder);
}
}
.embed-image-thumb {
position: relative;
width: 56px;
height: 56px;
border-radius: 8px;
overflow: hidden;
border: 1px solid var(--td-component-border, #e7e7e7);
img {
width: 100%;
height: 100%;
object-fit: cover;
}
&__remove {
position: absolute;
top: 2px;
right: 2px;
width: 18px;
height: 18px;
border: none;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
color: #fff;
background: rgba(0, 0, 0, 0.55);
}
}
.embed-control-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
padding: 0;
border: none;
border-radius: 6px;
cursor: pointer;
color: var(--td-text-color-secondary);
background: transparent;
transition: color 0.15s ease, background 0.15s ease;
&:hover {
background: var(--td-bg-color-secondarycontainer);
color: var(--td-text-color-primary);
}
&.active {
color: var(--embed-primary, var(--td-brand-color, #07c05f));
background: color-mix(in srgb, var(--embed-primary, #07c05f) 12%, transparent);
}
}
.embed-send-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
padding: 0;
border: none;
border-radius: 6px;
cursor: pointer;
background: var(--embed-primary, var(--td-brand-color, #07c05f));
transition: background 0.15s ease, opacity 0.15s ease;
&:hover:not(.disabled) {
filter: brightness(0.94);
}
&.disabled {
cursor: not-allowed;
opacity: 0.45;
}
img {
width: 16px;
height: 16px;
}
}
.embed-stop-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
padding: 0;
border: none;
border-radius: 6px;
cursor: pointer;
color: var(--td-text-color-secondary);
background: var(--td-bg-color-secondarycontainer);
&:hover {
background: var(--td-bg-color-component-hover);
}
}
</style>
+263 -202
View File
@@ -1,88 +1,75 @@
<template>
<div class="section-content">
<!-- Channel list header -->
<div class="im-panel">
<div class="channels-section">
<div class="channels-header">
<span class="channels-title">{{ $t('agentEditor.im.addChannel') }}</span>
<span class="channels-title">{{ $t('agentEditor.im.channelsTitle') }}</span>
<span class="channels-count">{{ channels.length }}</span>
</div>
<div v-if="loading" class="channels-loading">
<t-loading size="small" />
<span>{{ $t('common.loading') }}</span>
</div>
<t-loading :loading="loading" size="small" class="channels-loading-wrap">
<div v-if="!loading && channels.length === 0" class="channels-empty">
<t-empty :description="$t('agentEditor.im.empty')" />
</div>
<div v-else-if="channels.length === 0" class="channels-empty">
<t-icon name="chat-message" class="empty-icon" />
<span>{{ $t('agentEditor.im.empty') }}</span>
</div>
<div v-else class="channels-list">
<div v-for="channel in channels" :key="channel.id" class="channel-item">
<div class="channel-item-header">
<div class="channel-info-top">
<div class="channel-main">
<span class="platform-badge" :class="channel.platform">
{{ platformLabel(channel.platform) }}
</span>
<span class="channel-name">{{ channel.name || $t('agentEditor.im.unnamed') }}</span>
</div>
<div v-else-if="!loading" class="channel-grid">
<button
v-for="channel in channels"
:key="channel.id"
type="button"
class="channel-card channel-card--clickable"
@click="openDrawer(channel)"
>
<div class="channel-card__badge">
<t-icon name="chat-message" size="18px" />
</div>
<div class="channel-actions">
<div class="channel-card__body">
<div class="channel-card__header">
<h3 class="channel-card__title">{{ channel.name || $t('agentEditor.im.unnamed') }}</h3>
<t-tag v-if="!channel.enabled" size="small" variant="light" theme="warning">
{{ $t('agentEditor.im.disabled') }}
</t-tag>
</div>
<p class="channel-card__subtitle">{{ channelSummary(channel) }}</p>
</div>
<div v-if="authStore.hasRole('admin')" class="channel-card__actions" @click.stop>
<t-switch
:value="channel.enabled"
size="small"
:disabled="!authStore.hasRole('admin')"
@change="handleToggle(channel)"
@change="() => handleToggle(channel)"
/>
<t-dropdown
v-if="authStore.hasRole('admin')"
trigger="click"
placement="bottom-right"
:options="[
{ content: $t('common.edit'), value: 'edit', onClick: () => editChannel(channel) },
{ content: $t('common.delete'), value: 'delete', theme: 'error' }
]"
@click="(data) => data.value === 'delete' && handleDelete(channel.id)"
:options="channelMenuOptions"
@click="(data) => data.value === 'delete' && confirmDelete(channel.id)"
>
<t-button variant="text" theme="default" size="small">
<t-icon name="more" />
<t-button
variant="text"
shape="square"
size="small"
class="channel-card__more"
@click.stop
>
<template #icon><t-icon name="ellipsis" /></template>
</t-button>
</t-dropdown>
</div>
</div>
<div class="channel-info">
<div class="channel-meta">
<span class="meta-tag">
<t-icon name="link" class="meta-icon" />
{{ channel.mode }}
</span>
<span class="meta-tag">
<t-icon name="play-circle" class="meta-icon" />
{{ channel.output_mode === 'stream' ? $t('agentEditor.im.outputStream') : $t('agentEditor.im.outputFull') }}
</span>
<span v-if="channel.session_mode === 'thread'" class="meta-tag">
<t-icon name="chat" class="meta-icon" />
{{ $t('agentEditor.im.sessionModeThread') }}
</span>
</div>
<div v-if="channel.mode === 'webhook'" class="callback-url-row">
<span class="url-label">{{ $t('agentEditor.im.callbackUrl') }}:</span>
<code class="url-value">{{ getCallbackUrl(channel) }}</code>
<t-button theme="default" size="small" variant="text" @click="copyUrl(channel)">
<t-icon name="file-copy" />
</t-button>
</div>
</div>
</div>
</div>
</div>
</button>
<!-- Add button -->
<t-button v-if="authStore.hasRole('admin')" theme="default" variant="dashed" block @click="showCreateDialog = true" class="add-btn">
<t-icon name="add" />
{{ $t('agentEditor.im.addChannel') }}
</t-button>
<button
v-if="authStore.hasRole('admin')"
type="button"
class="channel-card channel-card--add"
@click="openCreate"
>
<span class="channel-card--add__icon" aria-hidden="true">
<t-icon name="add" />
</span>
<span class="channel-card--add__label">{{ $t('agentEditor.im.addChannel') }}</span>
</button>
</div>
</t-loading>
</div>
<!-- Create/Edit drawer -->
<t-drawer
@@ -140,6 +127,21 @@
<p v-else class="form-hint">{{ $t('agentEditor.im.modeHint') }}</p>
</div>
<!-- Callback URL (webhook mode, edit only) -->
<div v-if="editingChannel && formData.mode === 'webhook'" class="form-item">
<label class="form-label">{{ $t('agentEditor.im.callbackUrl') }}</label>
<div class="callback-url-control">
<t-input
:model-value="getCallbackUrl(editingChannel)"
readonly
class="mono-text-input callback-url-input"
/>
<t-button size="small" variant="text" :title="$t('common.copy')" @click="copyUrl(editingChannel)">
<t-icon name="file-copy" />
</t-button>
</div>
</div>
<!-- Output mode (hidden for WeChat) -->
<div v-if="formData.platform !== 'wechat'" class="form-item">
<label class="form-label">{{ $t('agentEditor.im.outputMode') }}</label>
@@ -424,7 +426,7 @@
<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { MessagePlugin } from 'tdesign-vue-next';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import {
listIMChannels, createIMChannel, updateIMChannel, deleteIMChannel, toggleIMChannel,
getWeChatQRCode, pollWeChatQRCodeStatus,
@@ -469,6 +471,22 @@ const formData = ref({
credentials: defaultCredentials(),
});
const channelMenuOptions = computed(() => ([
{ content: t('common.delete'), value: 'delete', theme: 'error' },
]));
const channelSummary = (channel: IMChannel) => {
const parts = [
platformLabel(channel.platform),
channel.mode,
channel.output_mode === 'stream' ? t('agentEditor.im.outputStream') : t('agentEditor.im.outputFull'),
];
if (channel.session_mode === 'thread') {
parts.push(t('agentEditor.im.sessionModeThread'));
}
return parts.join(' · ');
};
function platformLabel(platform: string): string {
const key = `agentEditor.im.${platform}`;
return t(key);
@@ -632,6 +650,29 @@ async function copyUrl(channel: IMChannel) {
}
}
function openCreate() {
resetForm();
showCreateDialog.value = true;
}
function openDrawer(channel: IMChannel) {
editChannel(channel);
}
function confirmDelete(id: string) {
const dialog = DialogPlugin.confirm({
header: t('common.delete'),
body: t('agentEditor.im.deleteConfirm'),
confirmBtn: { content: t('common.delete'), theme: 'danger' },
cancelBtn: t('common.cancel'),
onConfirm: async () => {
dialog.destroy();
await handleDelete(id);
},
onClose: () => dialog.destroy(),
});
}
function editChannel(channel: IMChannel) {
editingChannel.value = channel;
formData.value = {
@@ -732,22 +773,16 @@ onUnmounted(() => {
</script>
<style scoped lang="less">
.section-content {
.im-panel {
display: flex;
flex-direction: column;
gap: 16px;
}
// --- Channel list section (matches AgentShareSettings pattern) ---
.channels-section {
margin-bottom: 8px;
}
.channels-header {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 16px;
margin-bottom: 12px;
.channels-title {
font-size: 14px;
@@ -764,83 +799,164 @@ onUnmounted(() => {
}
}
.channels-loading {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 32px;
color: var(--td-text-color-disabled);
font-size: 14px;
.channels-loading-wrap {
min-height: 80px;
}
.channels-empty {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
padding: 40px 20px;
background: var(--td-bg-color-secondarycontainer);
border-radius: 8px;
color: var(--td-text-color-disabled);
.empty-icon {
font-size: 32px;
opacity: 0.5;
}
padding: 32px 0;
}
.channels-list {
.channel-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 16px;
max-height: 400px;
overflow-y: auto;
gap: 12px;
}
.channel-item {
.channel-card {
position: relative;
display: flex;
flex-direction: column;
gap: 16px;
padding: 16px;
background: var(--td-bg-color-container);
border: 1px solid var(--td-component-stroke);
border-radius: 8px;
transition: all 0.2s cubic-bezier(0.38, 0, 0.24, 1);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
&:hover {
border-color: var(--td-brand-color);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}
}
.channel-item-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 12px;
}
padding: 14px 16px;
border: 1px solid var(--td-component-stroke);
border-radius: 10px;
background: var(--td-bg-color-container);
text-align: left;
font: inherit;
color: inherit;
transition: border-color 0.18s ease, box-shadow 0.18s ease;
.channel-info {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 8px;
}
&--clickable {
cursor: pointer;
width: 100%;
.channel-info-top {
display: flex;
align-items: center;
gap: 12px;
}
&:hover,
&:focus-visible {
border-color: var(--td-brand-color-3, var(--td-brand-color));
box-shadow: 0 4px 14px rgba(15, 23, 42, 0.06);
outline: none;
}
.channel-main {
display: flex;
align-items: center;
gap: 8px;
&:focus-visible {
outline: 2px solid var(--td-brand-color);
outline-offset: 2px;
}
}
&--add {
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
min-height: 68px;
border-style: dashed;
background: transparent;
color: var(--td-text-color-placeholder);
cursor: pointer;
width: 100%;
&:hover,
&:focus-visible {
color: var(--td-brand-color);
border-color: var(--td-brand-color);
background: color-mix(in srgb, var(--td-brand-color) 6%, transparent);
box-shadow: none;
}
&__icon {
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
border-radius: 8px;
background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
color: var(--td-brand-color);
font-size: 18px;
}
&__label {
font-size: 13px;
font-weight: 500;
line-height: 1.4;
}
}
&__badge {
flex-shrink: 0;
width: 36px;
height: 36px;
border-radius: 9px;
display: flex;
align-items: center;
justify-content: center;
background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
color: var(--td-brand-color);
}
&__body {
flex: 1;
min-width: 0;
}
&__header {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
}
&__title {
flex: 1;
min-width: 0;
margin: 0;
font-size: 14px;
font-weight: 600;
line-height: 1.4;
color: var(--td-text-color-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
&__subtitle {
margin: 2px 0 0;
font-size: 12px;
line-height: 1.5;
color: var(--td-text-color-secondary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
&__actions {
flex-shrink: 0;
display: flex;
align-items: center;
gap: 2px;
padding-top: 2px;
}
&__more {
flex-shrink: 0;
padding: 2px;
opacity: 0;
color: var(--td-text-color-placeholder);
transition: opacity 0.15s ease;
&:hover,
&:focus-visible {
background: var(--td-bg-color-secondarycontainer);
color: var(--td-text-color-primary);
}
}
&:hover .channel-card__more,
&:focus-within .channel-card__more,
&__actions:focus-within .channel-card__more {
opacity: 1;
}
}
.platform-badge {
@@ -887,75 +1003,20 @@ onUnmounted(() => {
}
}
.channel-name {
font-size: 14px;
font-weight: 500;
color: var(--td-text-color-primary);
}
.channel-meta {
.callback-url-control {
display: flex;
align-items: center;
gap: 6px;
gap: 4px;
}
.callback-url-input {
flex: 1;
min-width: 0;
}
.mono-text-input :deep(input) {
font-family: var(--app-font-family-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
font-size: 12px;
color: var(--td-text-color-placeholder);
.meta-tag {
display: inline-flex;
align-items: center;
gap: 3px;
padding: 2px 6px;
background: var(--td-bg-color-secondarycontainer);
border-radius: 4px;
}
.meta-icon {
font-size: 12px;
flex-shrink: 0;
}
}
.callback-url-row {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
padding-top: 4px;
border-top: 1px dashed var(--td-component-stroke);
.url-label {
color: var(--td-text-color-secondary);
white-space: nowrap;
}
.url-value {
background: var(--td-bg-color-container);
padding: 2px 8px;
border-radius: 4px;
font-size: 11px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
min-width: 0;
}
}
.channel-actions {
display: flex;
align-items: center;
gap: 6px;
flex-shrink: 0;
}
.add-btn {
margin-top: 4px;
:deep(.t-button__text) {
display: inline-flex;
align-items: center;
gap: 4px;
}
}
.drawer-form {
+40 -11
View File
@@ -1483,6 +1483,9 @@ let resizeHandler: (() => void) | null = null;
let scrollHandler: (() => void) | null = null;
onMounted(() => {
// Embed 渠道由宿主注入 agent/KB,勿拉取需 JWT 的平台资源
if (props.embeddedMode) return;
// 并行拉取;若 platform 已预取且缓存未过期则直接复用
initChatModelSelection();
void Promise.all([
@@ -1592,6 +1595,16 @@ const createSession = async (val: string) => {
if (props.isReplying) {
return MessagePlugin.error(t('input.messages.replying'));
}
// Embed 渠道由后端绑定 agent/KB,勿走平台侧 agent 列表与就绪校验
if (props.embeddedMode) {
const textarea = getTextareaEl();
if (textarea) textarea.blur();
emit('send-msg', val, selectedModelId.value || '', [], [], []);
clearvalue();
return;
}
// 发送前校验当前选中的智能体(含默认快速问答)是否已配置完成
const agentToCheck = selectedAgent.value;
let actualAgent = agentToCheck;
@@ -2092,7 +2105,7 @@ defineExpose({
</script>
<template>
<div class="answers-input" @drop="onDrop" @dragover="onDragOver">
<div class="answers-input" :class="{ 'is-embedded': embeddedMode }" @drop="onDrop" @dragover="onDragOver">
<!-- Hidden file input for image upload -->
<input ref="imageInputRef" type="file" accept="image/jpeg,image/png,image/gif,image/webp" multiple
style="display:none" @change="handleImageSelect" />
@@ -2136,17 +2149,9 @@ defineExpose({
<t-textarea ref="textareaRef" v-model="query" :placeholder="inputPlaceholder" name="description" :autosize="true"
@keydown="onKeydown" @input="onInput" @compositionstart="onCompositionStart" @compositionend="onCompositionEnd"
@paste="onPaste" />
</div>
<!-- Mention Selector -->
<Teleport to="body">
<MentionSelector :visible="showMention" :style="mentionStyle" :items="mentionItems" :hasMore="mentionHasMore"
:loading="mentionLoading" :emptyHint="mentionEmptyHint" v-model:activeIndex="mentionActiveIndex"
@select="onMentionSelect" @loadMore="loadMoreMentionItems" />
</Teleport>
<!-- 控制栏 -->
<div class="control-bar">
<!-- 控制栏(放在 rich-input-container 内,相对输入框边框定位) -->
<div class="control-bar" :class="{ 'is-embedded': embeddedMode }">
<!-- 左侧控制按钮 -->
<div class="control-left" v-if="!embeddedMode">
<!-- Agent 模式切换按钮 -->
@@ -2335,8 +2340,16 @@ defineExpose({
<img src="../assets/img/sending-aircraft.svg" :alt="$t('input.send')" />
</div>
</div>
</div>
</div>
<!-- Mention Selector -->
<Teleport to="body">
<MentionSelector :visible="showMention" :style="mentionStyle" :items="mentionItems" :hasMore="mentionHasMore"
:loading="mentionLoading" :emptyHint="mentionEmptyHint" v-model:activeIndex="mentionActiveIndex"
@select="onMentionSelect" @loadMore="loadMoreMentionItems" />
</Teleport>
<!-- 知识库选择下拉(使用 Teleport 传送到 body,避免父容器定位影响) -->
<Teleport to="body">
<KnowledgeBaseSelector v-model:visible="showKbSelector" :anchorEl="atButtonRef" @close="showKbSelector = false" />
@@ -2358,6 +2371,18 @@ const getImgSrc = (url: string) => {
width: 100%;
display: flex;
justify-content: center;
&.is-embedded {
position: relative;
bottom: auto;
left: auto;
transform: none;
z-index: auto;
.rich-input-container {
max-width: 100%;
}
}
}
/* 富文本输入框容器 */
@@ -2597,6 +2622,10 @@ const getImgSrc = (url: string) => {
background: linear-gradient(to bottom, rgba(255, 255, 255, 0) 0%, var(--td-bg-color-container, #fff) 40%, var(--td-bg-color-container, #fff) 100%);
pointer-events: auto;
padding-top: 8px;
&.is-embedded {
justify-content: flex-end;
}
}
.control-left {
@@ -0,0 +1,855 @@
import { markRaw, nextTick, type Ref } from 'vue'
import { useI18n } from 'vue-i18n'
export type ChatMessage = Record<string, unknown>
export interface UseChatStreamHandlerOptions {
messagesList: ChatMessage[]
loading: Ref<boolean>
isReplying: Ref<boolean>
currentAssistantMessageId: Ref<string>
fullContent: Ref<string>
isAgentStreamSession: () => boolean
scrollToBottom: (force?: boolean) => void
onReplyComplete?: (content: string) => void
onError?: (message: string) => void
/** Main chat: keep the last incomplete message reactive for continue-stream. */
preserveIncompleteStreamReactive?: boolean
isFirstEnter?: Ref<boolean>
scrollContainer?: Ref<HTMLElement | null>
onAfterMsgList?: () => void | Promise<void>
onAgentQuery?: (
data: ChatMessage,
existingMessage: ChatMessage | undefined,
created: boolean,
) => void
onMessageCreated?: (message: ChatMessage) => void
onMessageUpdated?: (message: ChatMessage, payload?: ChatMessage) => void
onAgentAnswerDone?: (message: ChatMessage) => void
onAgentChunkBound?: (message: ChatMessage, created: boolean) => void
debug?: boolean
}
export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
const { t } = useI18n()
const {
messagesList,
loading,
isReplying,
currentAssistantMessageId,
fullContent,
isAgentStreamSession,
scrollToBottom,
onReplyComplete,
onError,
preserveIncompleteStreamReactive = false,
isFirstEnter,
scrollContainer,
onAfterMsgList,
onAgentQuery,
onMessageCreated,
onMessageUpdated,
onAgentAnswerDone,
onAgentChunkBound,
debug = false,
} = options
const log = (...args: unknown[]) => {
if (debug) console.log(...args)
}
const findLastMessage = (predicate: (item: ChatMessage) => boolean) => {
for (let i = messagesList.length - 1; i >= 0; i--) {
const item = messagesList[i]
if (predicate(item)) return item
}
return undefined
}
const ensureAgentMessageShell = (message: ChatMessage, requestId?: string) => {
message.isAgentMode = true
if (!message.agentEventStream) message.agentEventStream = []
if (!message._eventMap) message._eventMap = new Map()
if (!message._pendingToolCalls) message._pendingToolCalls = new Map()
if (requestId) {
if (!message.id) message.id = requestId
if (!message.request_id) message.request_id = requestId
}
}
const shouldRenderAssistantMessage = (session: ChatMessage) => {
if (!session?.isAgentMode) return true
const stream = session.agentEventStream
return Array.isArray(stream) && stream.length > 0
}
const recomposeAgentAnswer = (message: ChatMessage) => {
const stream = message.agentEventStream as Array<{
type?: string
superseded?: boolean
content?: string
}> | undefined
if (!stream) return ''
let out = ''
for (const e of stream) {
if (e.type === 'answer' && !e.superseded && e.content) {
out += e.content
}
}
return out
}
const reconstructEventStreamFromSteps = (
agentSteps: unknown[],
messageContent: string,
isCompleted = false,
isFallback = false,
agentDurationMs = 0,
) => {
const events: ChatMessage[] = []
if (agentSteps && Array.isArray(agentSteps) && agentSteps.length > 0) {
agentSteps.forEach((step: ChatMessage) => {
const stepTimestamp = step.timestamp ? new Date(String(step.timestamp)).getTime() : 0
const toolCalls = step.tool_calls
const hasToolCalls = toolCalls && Array.isArray(toolCalls) && toolCalls.length > 0
const reasoningText =
step.reasoning_content && String(step.reasoning_content).trim()
? String(step.reasoning_content)
: ''
if (reasoningText) {
events.push({
type: 'thinking',
event_id: `step-${step.iteration}-thought`,
content: reasoningText,
done: true,
thinking: false,
timestamp: stepTimestamp || undefined,
duration_ms: step.duration || undefined,
})
}
const preambleText = step.thought && String(step.thought).trim() ? String(step.thought) : ''
if (preambleText && hasToolCalls) {
events.push({
type: 'answer',
event_id: `step-${step.iteration}-preamble`,
content: preambleText,
done: true,
superseded: true,
timestamp: stepTimestamp || undefined,
})
}
if (toolCalls && Array.isArray(toolCalls)) {
toolCalls.forEach((toolCall: ChatMessage) => {
if (toolCall.name === 'final_answer') return
const result = toolCall.result as ChatMessage | undefined
const resultData = result?.data as ChatMessage | undefined
events.push({
type: 'tool_call',
tool_call_id: toolCall.id,
tool_name: toolCall.name,
arguments: toolCall.args,
pending: false,
success: result?.success !== false,
output: result?.output || '',
error: result?.error || undefined,
timestamp: stepTimestamp || undefined,
duration: toolCall.duration,
duration_ms: toolCall.duration,
display_type: resultData?.display_type,
tool_data: result?.data,
})
})
}
})
}
if (agentDurationMs > 0) {
events.push({
type: 'agent_complete',
total_duration_ms: agentDurationMs,
})
}
if (messageContent && messageContent.trim()) {
const answerEvent: ChatMessage = {
type: 'answer',
content: messageContent,
done: true,
}
if (isFallback) answerEvent.is_fallback = true
events.push(answerEvent)
} else if (isCompleted) {
events.push({
type: 'stop',
timestamp: Date.now(),
reason: 'user_requested',
})
}
return events
}
const handleMsgList = async (
data: ChatMessage[],
isScrollType = false,
newScrollHeight?: number,
) => {
const chatlist = [...data]
const existingIds = new Set(messagesList.map((m) => m.id).filter(Boolean))
const processed: ChatMessage[] = []
for (const raw of chatlist) {
const item = preserveIncompleteStreamReactive ? raw : { ...raw }
if (item.id && existingIds.has(item.id)) continue
if (item.id) existingIds.add(item.id)
item.isAgentMode = false
const willContinueStream = preserveIncompleteStreamReactive && !item.is_completed
if (willContinueStream) {
item.agentEventStream = item.agentEventStream || []
item._eventMap = new Map()
item._pendingToolCalls = new Map()
} else {
item.agent_steps = item.agent_steps ? markRaw(item.agent_steps as object) : item.agent_steps
item.agentEventStream = markRaw((item.agentEventStream as unknown[]) || [])
item._eventMap = markRaw(new Map())
item._pendingToolCalls = markRaw(new Map())
}
if (item.agent_steps && Array.isArray(item.agent_steps) && item.agent_steps.length > 0) {
item.isAgentMode = true
item.agentEventStream = markRaw(
reconstructEventStreamFromSteps(
item.agent_steps as unknown[],
String(item.content || ''),
Boolean(item.is_completed),
Boolean(item.is_fallback),
Number(item.agent_duration_ms) || 0,
),
)
item.hideContent = true
}
if (item.content) {
const content = String(item.content)
const thinkCloseTag = '</think>'
if (!content.includes('<think>') && !content.includes(thinkCloseTag)) {
item.thinkContent = ''
item.showThink = false
item.thinking = false
} else if (content.includes(thinkCloseTag)) {
item.showThink = true
item.thinking = false
const index = content.trim().lastIndexOf(thinkCloseTag)
item.thinkContent = content.trim().substring(0, index).replace('<think>', '').trim()
item.content = content.trim().substring(index + thinkCloseTag.length)
} else if (content.includes('<think>')) {
item.showThink = true
item.thinking = true
item.thinkContent = content.replace('<think>', '').trim()
item.content = ''
}
}
processed.push(item)
}
if (processed.length > 0) {
if (isScrollType) {
for (let i = processed.length - 1; i >= 0; i--) {
messagesList.unshift(processed[i])
}
} else {
messagesList.push(...processed)
}
}
if (isFirstEnter?.value) {
scrollToBottom(true)
} else if (isScrollType && scrollContainer?.value && typeof newScrollHeight === 'number') {
nextTick(() => {
if (!scrollContainer.value) return
const { scrollHeight } = scrollContainer.value
scrollContainer.value.scrollTop = scrollHeight - newScrollHeight
})
}
if (onAfterMsgList) {
await onAfterMsgList()
}
}
const updateAssistantSession = (payload: ChatMessage) => {
const message = findLastMessage((item) => {
if (item.request_id === payload.id) return true
return item.id === payload.id
})
if (message) {
if (payload.id && !message.request_id) message.request_id = payload.id
message.content = payload.content
message.thinking = payload.thinking
message.thinkContent = payload.thinkContent
message.showThink = payload.showThink
if (!message.knowledge_references) {
message.knowledge_references = payload.knowledge_references
}
if (payload.is_fallback) message.is_fallback = true
if (payload.is_completed) message.is_completed = true
onMessageUpdated?.(message, payload)
} else {
const entry = { ...payload }
if (entry.id && !entry.request_id) entry.request_id = entry.id
messagesList.push(entry)
onMessageCreated?.(entry)
onMessageUpdated?.(entry, payload)
}
scrollToBottom()
}
const reportError = (errorMsg: string) => {
if (onError) {
onError(errorMsg)
}
}
const handleAgentChunk = (data: ChatMessage) => {
const dataId = data.id as string | undefined
let message = findLastMessage(
(item) => item.request_id === dataId || item.id === dataId,
)
let created = false
if (!message) {
const newMsg: ChatMessage = {
id: dataId,
request_id: dataId,
role: 'assistant',
content: '',
isAgentMode: true,
agentEventStream: [],
_eventMap: new Map(),
knowledge_references: [],
}
messagesList.push(newMsg)
onMessageCreated?.(newMsg)
loading.value = false
scrollToBottom(true)
message = newMsg
created = true
} else {
onAgentChunkBound?.(message, false)
}
if (created) {
onAgentChunkBound?.(message, true)
}
message.isAgentMode = true
if (
loading.value &&
(data.response_type === 'thinking' ||
data.response_type === 'answer' ||
data.response_type === 'tool_call' ||
data.response_type === 'tool_approval_required')
) {
log('[Agent Chunk] Closing loading for continued stream')
loading.value = false
}
const responseType = data.response_type as string
const dataPayload = data.data as ChatMessage | undefined
switch (responseType) {
case 'thinking': {
const eventId = dataPayload?.event_id as string | undefined
log('[Thinking Event]', {
event_id: eventId,
done: data.done,
content_length: (data.content as string | undefined)?.length || 0,
})
if (!message.agentEventStream) message.agentEventStream = []
if (!message._eventMap) message._eventMap = new Map()
const eventMap = message._eventMap as Map<string, ChatMessage>
const stream = message.agentEventStream as ChatMessage[]
if (!data.done) {
let thinkingEvent = eventMap.get(eventId || '')
if (!thinkingEvent) {
log('[Thinking] Creating new thinking event, event_id:', eventId)
thinkingEvent = {
type: 'thinking',
event_id: eventId,
content: '',
done: false,
startTime: Date.now(),
thinking: true,
}
stream.push(thinkingEvent)
if (eventId) eventMap.set(eventId, thinkingEvent)
}
if (data.content) {
thinkingEvent.content = String(thinkingEvent.content || '') + String(data.content)
log('[Thinking] Event', eventId, 'accumulated:', String(thinkingEvent.content).length, 'chars')
}
} else {
const thinkingEvent = eventMap.get(eventId || '')
if (thinkingEvent) {
thinkingEvent.done = true
thinkingEvent.thinking = false
thinkingEvent.duration_ms =
dataPayload?.duration_ms || Date.now() - Number(thinkingEvent.startTime || Date.now())
thinkingEvent.completed_at = dataPayload?.completed_at || Date.now()
log('[Thinking] Event completed, duration:', thinkingEvent.duration_ms, 'ms')
} else {
console.warn('[Thinking] Received done for unknown event_id:', eventId)
}
}
break
}
case 'tool_approval_required': {
if (!message.agentEventStream) message.agentEventStream = []
const d = dataPayload || {}
;(message.agentEventStream as ChatMessage[]).push({
type: 'tool_approval_required',
pending_id: d.pending_id,
service_name: d.service_name,
mcp_tool_name: d.mcp_tool_name,
description: d.description,
args_json: d.args_json,
timeout_seconds: d.timeout_seconds,
requested_at: d.requested_at,
tool_call_id: d.tool_call_id,
resolved: false,
})
break
}
case 'tool_approval_resolved': {
const d = dataPayload || {}
const pid = d.pending_id
const ev = (message.agentEventStream as ChatMessage[] | undefined)?.find(
(e) => e.type === 'tool_approval_required' && e.pending_id === pid,
)
if (ev) {
ev.resolved = true
ev.approved = d.approved
ev.resolve_reason = d.reason
ev.timed_out = d.timed_out
ev.canceled = d.canceled
}
break
}
case 'tool_call': {
if (dataPayload?.tool_name === 'final_answer') break
if (message.agentEventStream) {
let retracted = false
for (const ev of message.agentEventStream as ChatMessage[]) {
if (ev.type === 'answer' && !ev.superseded && ev.content && String(ev.content).trim()) {
ev.superseded = true
ev.done = true
retracted = true
}
}
if (retracted) {
message.content = recomposeAgentAnswer(message)
fullContent.value = String(message.content || '')
}
}
if (dataPayload && (dataPayload.tool_name || dataPayload.tool_call_id)) {
if (!message.agentEventStream) message.agentEventStream = []
if (!message._pendingToolCalls) message._pendingToolCalls = new Map()
const pending = message._pendingToolCalls as Map<string, ChatMessage>
const stream = message.agentEventStream as ChatMessage[]
const incomingToolName = dataPayload.tool_name as string | undefined
const incomingArguments = dataPayload.arguments
const toolCallId =
(dataPayload.tool_call_id as string) ||
(incomingToolName ? `${incomingToolName}_${Date.now()}` : null)
if (!toolCallId) {
console.warn('[Tool Call] Received event without identifiable tool_call_id:', dataPayload)
break
}
log('[Tool Call]', {
tool_call_id: toolCallId,
tool_name: incomingToolName,
has_arguments: Boolean(incomingArguments),
})
let toolCallEvent = pending.get(toolCallId)
if (!toolCallEvent) {
toolCallEvent = stream.find(
(event) => event.type === 'tool_call' && event.tool_call_id === toolCallId,
)
}
if (toolCallEvent) {
if (incomingToolName) toolCallEvent.tool_name = incomingToolName
if (incomingArguments) toolCallEvent.arguments = incomingArguments
toolCallEvent.pending = true
if (!toolCallEvent.timestamp) toolCallEvent.timestamp = Date.now()
pending.set(toolCallId, toolCallEvent)
} else {
const newToolCallEvent = {
type: 'tool_call',
tool_call_id: toolCallId,
tool_name: incomingToolName,
arguments: incomingArguments,
timestamp: Date.now(),
pending: true,
}
stream.push(newToolCallEvent)
pending.set(toolCallId, newToolCallEvent)
}
}
break
}
case 'tool_result':
case 'error': {
if (dataPayload) {
const toolCallId = dataPayload.tool_call_id as string | undefined
const toolName = dataPayload.tool_name as string | undefined
const success = responseType !== 'error' && dataPayload.success !== false
log('[Tool Result]', {
tool_call_id: toolCallId,
tool_name: toolName,
success,
})
let toolCallEvent: ChatMessage | undefined
const pending = message._pendingToolCalls as Map<string, ChatMessage> | undefined
if (pending) {
if (toolCallId && pending.has(toolCallId)) {
toolCallEvent = pending.get(toolCallId)
pending.delete(toolCallId)
} else {
Array.from(pending.entries()).some(([key, value]) => {
if (value.tool_name === toolName) {
toolCallEvent = value
pending.delete(key)
return true
}
return false
})
}
}
if (toolCallEvent) {
toolCallEvent.pending = false
toolCallEvent.success = success
toolCallEvent.output = success
? dataPayload.output || data.content
: dataPayload.error || data.content
toolCallEvent.error = !success ? dataPayload.error || data.content : undefined
const duration =
dataPayload.duration_ms !== undefined ? dataPayload.duration_ms : dataPayload.duration
toolCallEvent.duration = duration
toolCallEvent.duration_ms = duration
toolCallEvent.display_type = dataPayload.display_type
toolCallEvent.tool_data = dataPayload
log('[Tool Result] Updated event in stream')
} else {
console.warn('[Tool Result] No pending tool call found for', toolCallId || toolName)
}
if (responseType === 'error' && !toolName) {
const errorMsg = String(data.content || t('chat.processError'))
message.content = errorMsg
message.is_completed = true
isReplying.value = false
loading.value = false
fullContent.value = ''
currentAssistantMessageId.value = ''
reportError(errorMsg)
console.error('[Chat Error]', errorMsg)
}
} else if (responseType === 'error') {
const errorMsg = String(data.content || t('chat.processError'))
message.content = errorMsg
message.is_completed = true
isReplying.value = false
loading.value = false
fullContent.value = ''
currentAssistantMessageId.value = ''
reportError(errorMsg)
console.error('[Chat Error]', errorMsg)
}
break
}
case 'references': {
if (dataPayload?.references) {
message.knowledge_references = dataPayload.references
} else if (data.knowledge_references) {
message.knowledge_references = data.knowledge_references
}
break
}
case 'answer': {
message.thinking = false
const eventId = dataPayload?.event_id as string | undefined
if (!message.agentEventStream) message.agentEventStream = []
if (!message._eventMap) message._eventMap = new Map()
const eventMap = message._eventMap as Map<string, ChatMessage>
const stream = message.agentEventStream as ChatMessage[]
let answerEvent = eventId
? eventMap.get(eventId)
: stream.find((e) => e.type === 'answer' && !e.event_id)
if (!answerEvent) {
answerEvent = { type: 'answer', event_id: eventId, content: '', done: false }
stream.push(answerEvent)
if (eventId) eventMap.set(eventId, answerEvent)
}
if (!answerEvent.content && message.content && String(message.content).trim()) {
answerEvent.content = message.content
}
if (data.content) {
answerEvent.content = String(answerEvent.content || '') + String(data.content)
message.content = recomposeAgentAnswer(message)
fullContent.value = String(message.content || '')
}
if (dataPayload?.is_fallback) {
answerEvent.is_fallback = true
message.is_fallback = true
}
if (data.done && !answerEvent.done) {
answerEvent.done = true
onAgentAnswerDone?.(message)
loading.value = false
isReplying.value = false
fullContent.value = ''
currentAssistantMessageId.value = ''
}
break
}
case 'complete': {
log('[Agent] Complete event received')
loading.value = false
isReplying.value = false
message.is_completed = true
onReplyComplete?.(String(message.content || ''))
fullContent.value = ''
currentAssistantMessageId.value = ''
if (message.agentEventStream) {
;(message.agentEventStream as ChatMessage[]).push({
type: 'agent_complete',
total_duration_ms: dataPayload?.total_duration_ms || 0,
total_steps: dataPayload?.total_steps || 0,
})
}
break
}
case 'stop': {
log('[Agent] Stop event received')
if (!message.agentEventStream) message.agentEventStream = []
;(message.agentEventStream as ChatMessage[]).push({
type: 'stop',
timestamp: Date.now(),
reason: dataPayload?.reason || 'user_requested',
})
isReplying.value = false
fullContent.value = ''
break
}
}
scrollToBottom()
}
const processStreamChunk = (data: ChatMessage) => {
log('[Agent Event Received]', {
response_type: data.response_type,
id: data.id,
done: data.done,
content_length: (data.content as string | undefined)?.length || 0,
content_preview: data.content ? String(data.content).substring(0, 50) : '',
data: data.data,
session_id: data.session_id,
assistant_message_id: data.assistant_message_id,
})
if (data.response_type === 'agent_query') {
if (data.id) {
const earlyMsg = findLastMessage(
(item) => item.role === 'assistant' && !item.is_completed,
)
if (earlyMsg) earlyMsg.request_id = data.id
}
if (data.assistant_message_id) {
currentAssistantMessageId.value = data.assistant_message_id as string
log('[Agent Query] Saved assistant message ID:', data.assistant_message_id)
}
log('[Agent Query Event]', {
session_id: data.session_id || (data.data as ChatMessage | undefined)?.session_id,
assistant_message_id: data.assistant_message_id,
query: (data.data as ChatMessage | undefined)?.query,
request_id: (data.data as ChatMessage | undefined)?.request_id,
})
let existingMessage = findLastMessage(
(item) => item.id === data.id || item.request_id === data.id,
)
const created = !existingMessage
if (!existingMessage) {
existingMessage = {
id: data.id,
request_id: data.id,
role: 'assistant',
content: '',
isAgentMode: true,
is_completed: false,
agentEventStream: [],
_eventMap: new Map(),
_pendingToolCalls: new Map(),
knowledge_references: [],
}
messagesList.push(existingMessage)
onMessageCreated?.(existingMessage)
scrollToBottom(true)
log('[Agent Query] Created agent placeholder message')
} else {
ensureAgentMessageShell(existingMessage, data.id as string | undefined)
log('[Agent Query] Continuing stream for existing message')
}
onAgentQuery?.(data, existingMessage, created)
return
}
const isAgentOnlyResponse =
data.response_type === 'thinking' ||
data.response_type === 'tool_call' ||
data.response_type === 'tool_result' ||
data.response_type === 'reflection'
const lastMessage = messagesList[messagesList.length - 1]
const isCurrentlyAgentMode = lastMessage?.isAgentMode === true
const targetsActiveAgentRequest =
isAgentStreamSession() &&
!!data.id &&
(data.id === currentAssistantMessageId.value ||
lastMessage?.request_id === data.id ||
lastMessage?.id === data.id)
const isAgentAnswerChunk =
data.response_type === 'answer' && (isAgentStreamSession() || targetsActiveAgentRequest)
const isAgentCompleteChunk =
data.response_type === 'complete' && (isAgentStreamSession() || targetsActiveAgentRequest)
const shouldHandleAsAgent =
isAgentOnlyResponse ||
isCurrentlyAgentMode ||
isAgentAnswerChunk ||
isAgentCompleteChunk
if (data.response_type === 'references') {
if (isCurrentlyAgentMode) {
handleAgentChunk(data)
return
}
let existingMessage = findLastMessage(
(item) => item.request_id === data.id || item.id === data.id,
)
if (!existingMessage) {
existingMessage = {
id: data.id,
request_id: data.id,
role: 'assistant',
content: '',
showThink: false,
thinkContent: '',
thinking: false,
is_completed: false,
knowledge_references: [],
}
messagesList.push(existingMessage)
onMessageCreated?.(existingMessage)
loading.value = false
scrollToBottom(true)
}
const refs =
data.knowledge_references ||
(data.data as ChatMessage | undefined)?.references ||
[]
existingMessage.knowledge_references = refs
log('[References] Saved to message, count:', Array.isArray(refs) ? refs.length : 0)
return
}
if (shouldHandleAsAgent) {
handleAgentChunk(data)
if (data.response_type === 'stop') {
log('[Stop Event] Generation stopped')
loading.value = false
isReplying.value = false
currentAssistantMessageId.value = ''
}
return
}
if (data.response_type === 'stop') {
log('[Stop Event] Non-agent generation stopped')
const stoppedMessage = findLastMessage((item) => {
if (item.request_id === data.id) return true
return item.id === data.id
})
if (stoppedMessage) stoppedMessage.is_completed = true
loading.value = false
isReplying.value = false
fullContent.value = ''
currentAssistantMessageId.value = ''
return
}
const existingMessage = findLastMessage((item) => {
if (item.request_id === data.id) return true
return item.id === data.id
})
if (existingMessage?.is_completed && data.done && !data.content) {
log('[Non-Agent] Ignoring duplicate completion event for completed message')
return
}
fullContent.value += (data.content as string) || ''
const obj: ChatMessage = {
...data,
content: '',
role: 'assistant',
showThink: false,
is_completed: false,
}
if ((data.data as ChatMessage | undefined)?.is_fallback) obj.is_fallback = true
const thinkCloseTag = '</think>'
if (fullContent.value.includes('<think>') && !fullContent.value.includes(thinkCloseTag)) {
obj.thinking = true
obj.showThink = true
obj.content = ''
obj.thinkContent = fullContent.value.replace('<think>', '').trim()
} else if (fullContent.value.includes('<think>') && fullContent.value.includes(thinkCloseTag)) {
obj.thinking = false
obj.showThink = true
const index = fullContent.value.lastIndexOf(thinkCloseTag)
obj.thinkContent = fullContent.value.substring(0, index).replace('<think>', '').trim()
obj.content = fullContent.value.substring(index + thinkCloseTag.length).trim()
} else {
obj.content = fullContent.value
}
if (!existingMessage) loading.value = false
if (data.done) {
obj.is_completed = true
onReplyComplete?.(String(obj.content || ''))
isReplying.value = false
fullContent.value = ''
currentAssistantMessageId.value = ''
}
updateAssistantSession(obj)
}
return {
findLastMessage,
shouldRenderAssistantMessage,
handleMsgList,
processStreamChunk,
}
}
+253
View File
@@ -0,0 +1,253 @@
import { onMounted, onUnmounted, ref, type Ref } from 'vue'
import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import {
createEmbedSession,
exchangeEmbedSession,
getEmbedConfig,
getEmbedMessageList,
isEmbedSessionToken,
onEmbedHostContext,
onEmbedHostLocale,
onEmbedHostToken,
parseEmbedTokenFromLocation,
postEmbedBootstrapRequest,
postEmbedReady,
type EmbedChannelPublicConfig,
} from '@/api/embed'
import { applyEmbedLocale, readEmbedLocaleFromUrl, syncEmbedLocaleFromUrl } from '@/i18n/embed'
// Persist the chat session id per channel so a page refresh resumes the same
// conversation (and its history) instead of silently starting a new session.
const EMBED_SESSION_STORAGE_PREFIX = 'weknora-embed-session:'
const sessionStorageKey = (channelId: string) => `${EMBED_SESSION_STORAGE_PREFIX}${channelId}`
interface StoredSession {
id: string
sig: string
}
function readStoredSession(channelId: string): StoredSession | null {
try {
const raw = window.localStorage.getItem(sessionStorageKey(channelId))
if (!raw) return null
const parsed = JSON.parse(raw)
if (parsed && typeof parsed.id === 'string' && typeof parsed.sig === 'string' && parsed.id) {
return { id: parsed.id, sig: parsed.sig }
}
} catch {
// Malformed / legacy (plain-string) entry: ignore so a fresh signed
// session is created below.
}
return null
}
function writeStoredSession(channelId: string, session: StoredSession | null) {
try {
if (session?.id) {
window.localStorage.setItem(sessionStorageKey(channelId), JSON.stringify(session))
} else {
window.localStorage.removeItem(sessionStorageKey(channelId))
}
} catch {
// localStorage may be unavailable (private mode / disabled cookies).
// Persistence is best-effort; the session still works for this load.
}
}
// A stored session may have been deleted/expired server-side, or its signed
// handle invalidated by a channel token rotation. Probe it cheaply (limit=1)
// with the stored signature before reusing — the backend rejects stale/foreign
// ids and bad signatures with 4xx, which surfaces here as a thrown error.
async function isStoredSessionValid(
channelId: string,
apiToken: string,
session: StoredSession,
): Promise<boolean> {
try {
await getEmbedMessageList(channelId, apiToken, session.id, 1, undefined, session.sig)
return true
} catch {
return false
}
}
export function useEmbedBridge(channelId: Ref<string>) {
const { locale: activeLocale, t } = useI18n()
const route = useRoute()
const token = ref('')
const config = ref<EmbedChannelPublicConfig | null>(null)
const sessionId = ref('')
const sessionSig = ref('')
const loadError = ref('')
const awaitingToken = ref(false)
const bootstrapping = ref(false)
const hostContext = ref<Record<string, unknown>>({})
let removeHostListener: (() => void) | null = null
let removeLocaleListener: (() => void) | null = null
let removeTokenListener: (() => void) | null = null
let bootstrapped = false
let hostLocalePinned = false
if (typeof window !== 'undefined') {
hostLocalePinned = Boolean(readEmbedLocaleFromUrl())
if (hostLocalePinned) {
syncEmbedLocaleFromUrl(activeLocale)
}
}
const bootstrap = async (embedToken: string) => {
const id = channelId.value
if (!id || !embedToken || bootstrapped) return
bootstrapped = true
awaitingToken.value = false
bootstrapping.value = true
token.value = embedToken
try {
let apiToken = embedToken
// Secure mode: the host already handed us a short-lived session token
// (minted server-side from the publish token). Use it directly — the
// exchange endpoint only accepts publish tokens and would reject this.
if (!isEmbedSessionToken(embedToken)) {
try {
const exchangeRes = await exchangeEmbedSession(id, embedToken)
if (exchangeRes?.data?.session_token) {
apiToken = exchangeRes.data.session_token
} else if (!import.meta.env.DEV) {
// Fail closed in production: a missing session token must not silently
// fall back to the long-lived publish token.
throw new Error('embed session exchange returned no token')
}
} catch (exchangeErr) {
// In production we refuse to downgrade to the publish token; only the
// dev build keeps the convenience fallback for local testing.
if (!import.meta.env.DEV) {
throw exchangeErr
}
}
}
const res = await getEmbedConfig(id, apiToken)
if (!res?.success || !res.data) {
loadError.value = t('embedPublish.invalidChannel')
return
}
config.value = res.data
if (res.data.default_locale && !hostLocalePinned) {
applyEmbedLocale(res.data.default_locale, activeLocale)
}
// Resume a persisted session when still valid; otherwise create a fresh one.
let resolved: StoredSession | null = null
const stored = readStoredSession(id)
if (stored && (await isStoredSessionValid(id, apiToken, stored))) {
resolved = stored
} else {
const sessionRes = await createEmbedSession(id, apiToken)
const newId = sessionRes?.data?.id || ''
if (newId) resolved = { id: newId, sig: sessionRes?.data?.sig || '' }
}
if (!resolved) {
loadError.value = t('embedPublish.sessionFailed')
return
}
sessionId.value = resolved.id
sessionSig.value = resolved.sig
writeStoredSession(id, resolved)
token.value = apiToken
postEmbedReady(id)
} catch (e: unknown) {
bootstrapped = false
const msg = String((e as { message?: string })?.message || '')
if (msg.includes('disabled')) {
loadError.value = t('embedPublish.channelDisabled')
} else if (msg.includes('failed to create session')) {
loadError.value = t('embedPublish.sessionFailed')
} else {
loadError.value = msg || t('embedPublish.loadError')
}
} finally {
bootstrapping.value = false
}
}
// Discard the current conversation and start a fresh signed session. Backing
// the "新建对话" affordance — also the privacy escape hatch on shared devices.
const startNewSession = async () => {
const id = channelId.value
const apiToken = token.value
if (!id || !apiToken) return
try {
const sessionRes = await createEmbedSession(id, apiToken)
const newId = sessionRes?.data?.id || ''
if (!newId) return
const next: StoredSession = { id: newId, sig: sessionRes?.data?.sig || '' }
sessionSig.value = next.sig
sessionId.value = next.id
writeStoredSession(id, next)
} catch {
// Non-fatal: keep the current session if creating a new one fails.
}
}
const start = async () => {
removeHostListener = onEmbedHostContext((payload) => {
hostContext.value = { ...hostContext.value, ...payload }
})
removeLocaleListener = onEmbedHostLocale((locale) => {
hostLocalePinned = true
applyEmbedLocale(locale, activeLocale)
})
removeTokenListener = onEmbedHostToken((providedToken, providedChannelId) => {
if (providedChannelId && providedChannelId !== channelId.value) return
bootstrap(providedToken)
})
if (!channelId.value) {
loadError.value = t('embedPublish.missingChannel')
return
}
const initialToken = String(route.query.token || '') || parseEmbedTokenFromLocation()
if (initialToken) {
await bootstrap(initialToken)
return
}
if (window.parent !== window) {
awaitingToken.value = true
postEmbedBootstrapRequest(channelId.value)
return
}
loadError.value = t('embedPublish.missingChannel')
}
onMounted(() => {
start()
})
onUnmounted(() => {
removeHostListener?.()
removeLocaleListener?.()
removeTokenListener?.()
})
return {
token,
config,
sessionId,
sessionSig,
loadError,
awaitingToken,
bootstrapping,
hostContext,
startNewSession,
}
}
@@ -0,0 +1,369 @@
import {
ref,
reactive,
watch,
nextTick,
onMounted,
onUnmounted,
type Ref,
} from 'vue'
import { useStream } from '@/api/chat/streame'
import {
getEmbedMessageList,
postEmbedMessageSent,
postEmbedMessageReceived,
relayEmbedWebhookEvent,
stopEmbedSession,
} from '@/api/embed'
import { embedToast } from '@/utils/embedToast'
import { buildQueryWithHostContext } from '@/utils/embedContext'
import { fileToDataURI } from '@/utils/embedFile'
import { useI18n } from 'vue-i18n'
import { useChatStreamHandler } from '@/composables/useChatStreamHandler'
export function useEmbedChatSession(options: {
sessionId: Ref<string>
sessionSig: Ref<string>
channelId: string
token: string
agentId: string
kbIds: string[]
allowWebSearch?: boolean
allowFileUpload?: boolean
hostContext?: Ref<Record<string, unknown>>
onMessagesChange?: (has: boolean) => void
onSessionTitle?: (title: string) => void
}) {
const { t } = useI18n()
const { onChunk, error, startStream, stopStream } = useStream()
const isAgentStreamSession = () =>
!!(options.agentId && options.agentId !== 'builtin-quick-answer')
const limit = ref(20)
const messagesList = reactive<Record<string, unknown>[]>([])
watch(
() => messagesList.length,
(len) => options.onMessagesChange?.(len > 0),
{ immediate: true },
)
const isReplying = ref(false)
const currentAssistantMessageId = ref('')
const isFirstEnter = ref(true)
const loading = ref(false)
const historyLoading = ref(true)
const historyLoadingMore = ref(false)
const hasMoreHistory = ref(true)
const created_at = ref('')
const fullContent = ref('')
const scrollContainer = ref<HTMLElement | null>(null)
const userHasScrolledUp = ref(false)
const SCROLL_BOTTOM_THRESHOLD = 80
const isNearBottom = () => {
if (!scrollContainer.value) return true
const { scrollTop, scrollHeight, clientHeight } = scrollContainer.value
return scrollHeight - scrollTop - clientHeight < SCROLL_BOTTOM_THRESHOLD
}
const getUserQuery = (index: number) => {
if (index <= 0) return ''
const previous = messagesList[index - 1]
if (previous && previous.role === 'user') {
return String(previous.content || '')
}
return ''
}
const scrollToBottom = (force = false) => {
if (!force && userHasScrolledUp.value) return
nextTick(() => {
if (scrollContainer.value) {
scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight
}
})
}
const onClickScrollToBottom = () => {
userHasScrolledUp.value = false
scrollToBottom(true)
}
const debounce = <T extends (...args: never[]) => void>(fn: T, delay: number) => {
let timer: ReturnType<typeof setTimeout>
return (...args: Parameters<T>) => {
clearTimeout(timer)
timer = setTimeout(() => fn(...args), delay)
}
}
const notifyEmbedReceived = (content: string) => {
if (!content?.trim()) return
postEmbedMessageReceived(options.channelId, options.sessionId.value, content)
relayEmbedWebhookEvent(
options.channelId,
options.token,
options.sessionId.value,
options.sessionSig.value,
{ type: 'message_received', content },
)
}
const {
shouldRenderAssistantMessage,
handleMsgList,
processStreamChunk,
} = useChatStreamHandler({
messagesList,
loading,
isReplying,
currentAssistantMessageId,
fullContent,
isAgentStreamSession,
scrollToBottom,
onReplyComplete: notifyEmbedReceived,
onError: embedToast,
isFirstEnter,
scrollContainer,
})
const onChatScrollTop = () => {
if (historyLoadingMore.value || !hasMoreHistory.value) return
if (!scrollContainer.value) return
const { scrollTop, scrollHeight } = scrollContainer.value
isFirstEnter.value = false
if (scrollTop <= 0) {
getmsgList(
{
session_id: options.sessionId.value,
created_at: created_at.value,
limit: limit.value,
},
true,
scrollHeight,
)
}
}
const debouncedScrollTop = debounce(onChatScrollTop, 500)
const handleScroll = () => {
userHasScrolledUp.value = !isNearBottom()
debouncedScrollTop()
}
const getmsgList = (
data: { session_id: string; created_at?: string; limit: number },
isScrollType = false,
scrollHeight?: number,
) => {
if (isScrollType) {
if (historyLoadingMore.value || !hasMoreHistory.value) return
historyLoadingMore.value = true
}
getEmbedMessageList(
options.channelId,
options.token,
data.session_id,
data.limit,
data.created_at || undefined,
options.sessionSig.value,
)
.then(async (res) => {
const batch = res?.data as Record<string, unknown>[] | undefined
if (!batch?.length) {
// No (more) server history. Crucially this also covers the initial
// load of a brand-new session: leaving hasMoreHistory true here would
// let a later scroll-to-top re-fetch with an empty cursor (= "latest"),
// pulling back the just-sent messages and duplicating them.
hasMoreHistory.value = false
return
}
const nextCursor = String(batch[0].created_at)
if (isScrollType && created_at.value && nextCursor === created_at.value) {
hasMoreHistory.value = false
return
}
if (batch.length < limit.value) hasMoreHistory.value = false
created_at.value = nextCursor
await handleMsgList(batch, isScrollType, scrollHeight)
})
.catch((err) => {
console.error('Failed to load messages:', err)
if (isScrollType) hasMoreHistory.value = false
})
.finally(() => {
historyLoading.value = false
historyLoadingMore.value = false
})
}
const handleStopGeneration = () => {
stopStream()
const messageId = currentAssistantMessageId.value
if (messageId) {
stopEmbedSession(
options.channelId,
options.token,
options.sessionId.value,
messageId,
options.sessionSig.value,
).catch((err) => console.error('Failed to stop embed generation:', err))
}
loading.value = false
isReplying.value = false
}
const sendMsg = async (
value: string,
opts: { webSearchEnabled?: boolean; imageFiles?: File[]; attachmentFiles?: File[] } = {},
) => {
const outboundQuery = buildQueryWithHostContext(value, options.hostContext?.value)
const visitorWebSearchEnabled = opts.webSearchEnabled ?? false
const imageFiles = (options.allowFileUpload ? opts.imageFiles : undefined) || []
const attachmentFiles = (options.allowFileUpload ? opts.attachmentFiles : undefined) || []
isReplying.value = true
loading.value = true
const imageAttachments: Array<{ data: string }> = []
const displayImages: Array<{ url: string }> = []
const attachmentUploads: Array<{ data: string; file_name: string; file_size: number }> = []
const displayAttachments: Array<{ file_name: string; file_size: number }> = []
try {
for (const file of imageFiles) {
const dataURI = String(await fileToDataURI(file))
imageAttachments.push({ data: dataURI })
displayImages.push({ url: dataURI })
}
for (const file of attachmentFiles) {
const dataURI = String(await fileToDataURI(file))
attachmentUploads.push({ data: dataURI, file_name: file.name, file_size: file.size })
displayAttachments.push({ file_name: file.name, file_size: file.size })
}
} catch (err) {
console.error('Failed to read attachment:', err)
embedToast(t('chat.imageReadFailed'))
isReplying.value = false
loading.value = false
return
}
messagesList.push({
content: value,
role: 'user',
mentioned_items: [],
images: displayImages,
attachments: displayAttachments,
channel: 'embed',
})
postEmbedMessageSent(options.channelId, options.sessionId.value, value)
relayEmbedWebhookEvent(
options.channelId,
options.token,
options.sessionId.value,
options.sessionSig.value,
{ type: 'message_sent', query: value },
)
userHasScrolledUp.value = false
scrollToBottom(true)
const agentEnabled = isAgentStreamSession()
const endpoint = agentEnabled
? `/api/v1/embed/${options.channelId}/agent-chat`
: `/api/v1/embed/${options.channelId}/knowledge-chat`
await startStream({
session_id: options.sessionId.value,
knowledge_base_ids: options.kbIds,
knowledge_ids: [],
agent_enabled: agentEnabled,
agent_id: options.agentId,
web_search_enabled: (options.allowWebSearch ?? false) && visitorWebSearchEnabled,
enable_memory: false,
summary_model_id: '',
mcp_service_ids: [],
mentioned_items: [],
images: imageAttachments.length > 0 ? imageAttachments : undefined,
attachment_uploads: attachmentUploads.length > 0 ? attachmentUploads : undefined,
query: outboundQuery,
method: 'POST',
url: endpoint,
embed_token: options.token,
embed_session_sig: options.sessionSig.value,
})
}
watch(error, (newError) => {
if (newError) {
embedToast(newError)
isReplying.value = false
loading.value = false
currentAssistantMessageId.value = ''
}
})
onChunk((data) => {
if (data.response_type === 'session_title') {
const title = String(data.content || (data.data as { title?: string })?.title || '').trim()
if (title) {
options.onSessionTitle?.(title)
}
return
}
processStreamChunk(data)
})
const resetAndLoad = (sid: string) => {
messagesList.splice(0)
historyLoading.value = true
historyLoadingMore.value = false
hasMoreHistory.value = true
created_at.value = ''
loading.value = false
isReplying.value = false
currentAssistantMessageId.value = ''
userHasScrolledUp.value = false
isFirstEnter.value = true
fullContent.value = ''
if (!sid) {
historyLoading.value = false
return
}
getmsgList({ session_id: sid, created_at: '', limit: limit.value })
}
watch(
() => options.sessionId.value,
(sid) => resetAndLoad(sid),
{ immediate: true },
)
onMounted(() => {
loading.value = false
isReplying.value = false
})
onUnmounted(() => {
stopStream()
fullContent.value = ''
})
return {
messagesList,
loading,
isReplying,
historyLoading,
scrollContainer,
userHasScrolledUp,
isFirstEnter,
shouldRenderAssistantMessage,
getUserQuery,
handleScroll,
scrollToBottom,
onClickScrollToBottom,
sendMsg,
handleStopGeneration,
}
}
@@ -0,0 +1,168 @@
import { onBeforeUnmount, ref, unref, watch, type MaybeRef, type Ref } from 'vue'
import { getEmbedChunkById } from '@/api/embed'
type FloatState = {
visible: boolean
type: 'kb' | 'web'
top: number
left: number
title: string
content: string
url: string
loading: boolean
error: string
}
const chunkCache = new Map<string, { content: string; error?: string }>()
export function useEmbedCitationPopover(
rootRef: Ref<HTMLElement | null>,
channelId: MaybeRef<string>,
token: MaybeRef<string>,
) {
const float = ref<FloatState>({
visible: false,
type: 'kb',
top: 0,
left: 0,
title: '',
content: '',
url: '',
loading: false,
error: '',
})
let hoverTimer: number | null = null
let closeTimer: number | null = null
const positionFor = (el: HTMLElement, offsetY = 0) => {
const rect = el.getBoundingClientRect()
float.value.top = rect.bottom + window.scrollY + 6 + offsetY
float.value.left = Math.min(rect.left + window.scrollX, window.innerWidth - 320)
}
const openWeb = (el: HTMLElement) => {
const url = el.getAttribute('data-url') || ''
float.value.type = 'web'
float.value.url = url
float.value.title = el.querySelector('.tip-title')?.textContent || ''
float.value.content = ''
float.value.loading = false
float.value.error = ''
float.value.visible = true
positionFor(el)
}
const openKb = async (el: HTMLElement) => {
const chunkId = el.getAttribute('data-chunk-id') || ''
const title = el.getAttribute('data-doc') || ''
if (!chunkId) return
float.value.type = 'kb'
float.value.title = title
float.value.url = ''
float.value.visible = true
positionFor(el, 4)
const cached = chunkCache.get(chunkId)
if (cached) {
float.value.content = cached.content
float.value.error = cached.error || ''
float.value.loading = false
return
}
float.value.loading = true
float.value.error = ''
float.value.content = ''
try {
const res = await getEmbedChunkById(unref(channelId), unref(token), chunkId)
const content = String(res?.data?.content || '').trim()
chunkCache.set(chunkId, { content })
float.value.content = content
} catch {
const msg = 'Failed to load'
chunkCache.set(chunkId, { content: '', error: msg })
float.value.error = msg
} finally {
float.value.loading = false
}
}
const scheduleClose = () => {
if (closeTimer) window.clearTimeout(closeTimer)
closeTimer = window.setTimeout(() => {
float.value.visible = false
}, 120)
}
const onMouseOver = (e: Event) => {
const target = e.target as HTMLElement
const kbEl = target.closest?.('.citation-kb') as HTMLElement | null
const webEl = target.closest?.('.citation-web') as HTMLElement | null
if (!kbEl && !webEl) return
if (closeTimer) {
window.clearTimeout(closeTimer)
closeTimer = null
}
if (hoverTimer) window.clearTimeout(hoverTimer)
hoverTimer = window.setTimeout(() => {
if (kbEl) void openKb(kbEl)
else if (webEl) openWeb(webEl)
}, kbEl ? 80 : 40)
}
const onMouseOut = (e: Event) => {
const rt = (e as MouseEvent).relatedTarget as HTMLElement | null
if (rt?.closest?.('.citation-kb, .citation-web, .embed-citation-float')) return
if (hoverTimer) {
window.clearTimeout(hoverTimer)
hoverTimer = null
}
scheduleClose()
}
const onClick = (e: Event) => {
const target = e.target as HTMLElement
const kbEl = target.closest?.('.citation-kb') as HTMLElement | null
if (kbEl) {
e.preventDefault()
e.stopPropagation()
void openKb(kbEl)
return
}
const wikiEl = target.closest?.('.citation-wiki') as HTMLElement | null
if (wikiEl) {
e.preventDefault()
e.stopPropagation()
}
}
const bind = () => {
const root = rootRef.value
if (!root) return
root.addEventListener('mouseover', onMouseOver, true)
root.addEventListener('mouseout', onMouseOut, true)
root.addEventListener('click', onClick, true)
}
const unbind = () => {
const root = rootRef.value
if (!root) return
root.removeEventListener('mouseover', onMouseOver, true)
root.removeEventListener('mouseout', onMouseOut, true)
root.removeEventListener('click', onClick, true)
}
watch(rootRef, () => {
unbind()
bind()
}, { flush: 'post' })
onBeforeUnmount(() => {
unbind()
if (hoverTimer) window.clearTimeout(hoverTimer)
if (closeTimer) window.clearTimeout(closeTimer)
})
return { float, rebind: () => { unbind(); bind() } }
}
+34
View File
@@ -0,0 +1,34 @@
import { createApp, h } from 'vue'
import { createPinia } from 'pinia'
import { createRouter, createWebHistory, RouterView } from 'vue-router'
import TDesign from 'tdesign-vue-next'
import 'tdesign-vue-next/es/style/index.css'
import '@/assets/theme/theme.css'
import { installTDesignIconOfflineGuard } from '@/utils/tdesign-icon-offline'
import i18n from './i18n/embed'
import EmbedPage from '@/views/embed/EmbedPage.vue'
installTDesignIconOfflineGuard()
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/embed/:channelId',
name: 'embed',
component: EmbedPage,
},
],
})
// Runtime-only Vue build cannot compile string templates — use a render fn.
const app = createApp({ render: () => h(RouterView) })
app.use(TDesign)
app.use(createPinia())
app.use(router)
app.use(i18n)
router.isReady().finally(() => {
app.mount('#embed-app')
})
File diff suppressed because it is too large Load Diff
+16
View File
@@ -0,0 +1,16 @@
/**
* Embed i18n entry point.
*
* - Visitor UI strings: `frontend/src/i18n/embed.ts` (loaded by embed-main.ts)
* - Admin `embedPublish` strings: `frontend/src/i18n/locales/*.ts`
*
* Re-export locale helpers so feature code can import from one path.
*/
export {
applyEmbedLocale,
EMBED_LOCALE_STORAGE_KEY,
normalizeEmbedLocale,
readEmbedLocaleFromUrl,
syncEmbedLocaleFromUrl,
type EmbedLocale,
} from '@/i18n/embed'
+202 -6
View File
@@ -28,7 +28,16 @@ export default {
expandSidebar: 'Expand Sidebar',
logoutSuccess: 'Logged out successfully',
myChats: 'My chats',
embedChats: 'Web embed',
embedChannelNamed: 'Web embed · {name}',
groupBy: 'Group by',
groupNone: 'None',
groupDate: 'Date',
channelsSection: 'Channel chats',
chatsSection: 'Web chats',
otherSources: 'Other sources',
noSessions: 'No conversations yet',
loadMoreSessions: 'Load more',
},
newUserGuide: {
stepOf: '{current} / {total}',
@@ -357,6 +366,7 @@ export default {
description: 'Description',
files: 'Files',
settings: 'Settings',
publishToWeb: 'Publish to Web',
documentCategoryTitle: 'Document Categories',
tagUpdateSuccess: 'Tag updated successfully',
category: 'Category',
@@ -970,15 +980,17 @@ export default {
createTitle: 'Create Agent',
editTitle: 'Edit Agent',
basicInfo: 'Basic Info',
basicInfoDesc: 'Configure agent basic information',
basicInfoDesc: 'Configure agent name, description, and run mode',
promptsConfig: 'Prompts',
promptsConfigDesc: 'Configure system, context, intent, rewrite, and fallback prompts',
modelConfig: 'Model Config',
modelConfigDesc: 'Configure agent model parameters',
modelConfigDesc: 'Configure chat model, auxiliary models (ReRank), and generation parameters',
capabilities: 'Capabilities',
capabilitiesDesc: 'Configure agent capabilities and tools',
toolsConfig: 'Tools',
toolsConfigDesc: 'Configure tools available to the Agent',
knowledgeConfig: 'Knowledge Base',
knowledgeConfigDesc: 'Configure knowledge bases for the agent',
knowledgeConfigDesc: 'Configure knowledge base scope and FAQ strategy for the agent',
webSearchConfig: 'Web Search',
webSearchConfigDesc: 'Configure web search capabilities for the agent',
configuration: 'Configuration',
@@ -2265,9 +2277,167 @@ export default {
unknownKb: 'Knowledge Base {id}',
}
},
embedPublish: {
title: 'Web Page Embed',
description: 'Embed this agent on your website so visitors can chat via an in-page window or a floating launcher.',
create: 'New embed channel',
channelsTitle: 'Embed channels',
disabled: 'Disabled',
empty: 'No embed channels yet',
unnamed: 'Unnamed channel',
agent: 'Agent',
rateLimit: 'Rate limit',
rateLimitUnit: '/min',
allowedOrigins: 'Allowed origins',
embedCode: 'Embed code',
widgetCode: 'Widget script',
copyCode: 'Copy code',
rotateToken: 'Rotate token',
rotatePublishToken: 'Rotate publish token',
channelKey: 'Channel key',
channelKeyDesc: 'Long-lived secret for third-party site integration—store it safely',
channelKeyHint: 'For security, channel keys are not returned in list APIs. If you did not save it, reset to generate a new key (stored for this browser session).',
channelKeyUnavailable: 'Key unavailable',
resetKeyTitle: 'Reset channel key',
resetKeyConfirmOk: 'Reset',
resetKeyConfirmBody: 'After reset, the old channel key is revoked immediately. Every deployed embed snippet must use the new key to keep working. This cannot be undone.',
resetKeySuccess: 'Channel key reset—the new key is shown in the input field',
resetKeyFailed: 'Failed to reset channel key',
copyChannelKeyTitle: 'Copy channel key',
revealKey: 'Reveal key',
hideKey: 'Hide key',
delete: 'Delete',
edit: 'Edit',
createTitle: 'New embed channel',
editTitle: 'Edit embed channel',
name: 'Name',
nameDesc: 'For admin lists and channel identification',
namePlaceholder: 'e.g. Website support',
welcomeMessage: 'Welcome message',
welcomePlaceholder: 'Hi! How can I help you?',
showSuggestedQuestions: 'Suggested questions',
showSuggestedQuestionsDesc: 'Show starter prompts before the first visitor message, from agent config and linked knowledge bases',
originsLabel: 'Allowed origins (one per line, at least one required)',
originsHint: 'One full origin per line (e.g. https://shop.example.com), at least one required; *.example.com subdomain wildcards supported',
originsRequired: 'At least one allowed origin is required',
originsInvalid: 'Invalid origin: {origin}',
originsWildcardProd: "Wildcard origin '*' is not allowed in production",
originsCount: '{n} allowed origins',
originsPlaceholder: 'https://shop.example.com',
rateLimitLabel: 'Requests per minute',
rateLimitDesc: 'Per visitor IP, max embed API requests per minute; excess requests are temporarily rejected. Default 30.',
rateLimitDayLabel: 'Daily request cap',
rateLimitDayDesc: 'Channel-wide total requests allowed per day (across all visitor IPs); bounds abuse cost if the publish token is copied. Default 10000.',
publishTokenWarning: 'The publish token appears in plain text in the embed page source — anyone visiting the host site can read it. Treat it as a publishable key, not a secret: never embed an agent that exposes sensitive data, always configure the origin allowlist and request caps, and rotate the token immediately if it leaks.',
debug: 'Debug preview',
createdDebugHint: 'Embed channel created — use Debug preview to open it in a new tab',
primaryColor: 'Primary color',
pageTitle: 'Page title',
pageTitleDesc: 'Shown to visitors in chat header and browser tab; takes priority over name',
pageTitlePlaceholder: 'AI Assistant',
headerTitleMode: 'Header title',
headerTitleModeChannel: 'Fixed channel title',
headerTitleModeSession: 'Follow session title',
headerTitleModeDesc: 'Fixed: always show the page title. Session: auto-title from the first message; falls back to page title until generated.',
tokenHint: 'For security, channel keys are not returned in list APIs. Save the key when creating or resetting before copying the widget snippet (stored for this browser session).',
createdWithToken: 'Embed channel created — the new key is shown in the input field; copy and store it now',
created: 'Embed channel created',
updated: 'Embed channel updated',
saveFailed: 'Save failed',
deleted: 'Deleted',
tokenRotated: 'Channel key reset',
copied: 'Embed code copied',
loadError: 'Failed to load',
missingChannel: 'Missing embed channel or token',
invalidChannel: 'Invalid embed channel',
sessionFailed: 'Failed to create chat session, please try again',
channelDisabled: 'This embed channel is disabled. Re-enable it under Agent editor → Web Page Embed',
loading: 'Loading...',
tabIframe: 'iframe',
tabWidget: 'Widget',
tabSecure: 'Secure mode',
widgetPosition: 'Widget position',
widgetPreview: 'Widget preview',
positionBottomRight: 'Bottom right',
positionBottomLeft: 'Bottom left',
positionTopRight: 'Top right',
positionTopLeft: 'Top left',
publishToken: 'Channel key',
publishTokenHelp: 'The channel key (em_…) is a long-lived secret for this embed channel—like an API key. It is shown only when created or reset and must be placed in the host site widget script; list APIs never return it.',
sessionTokenHelp: 'After a visitor opens chat, the iframe exchanges the channel key for a short-lived session credential (ems_…, ~30 min). Later API calls use the session credential so the channel key is not kept in the URL.',
rotateTokenHelp: 'Resetting invalidates the previous channel key. Every deployed embed snippet must be updated or third-party sites will lose access.',
revealToken: 'Reveal',
hideToken: 'Hide',
copyToken: 'Copy channel key',
tokenCopied: 'Channel key copied',
awaitingToken: 'Waiting for host page to provide token…',
preview: 'Preview',
previewIframeHint: 'Shows how the iframe embed looks on a third-party page (same as the copied snippet).',
previewWidgetHint: 'Shows the floating widget on a mock host page. On a real site the host passes the token via postMessage.',
previewMockPage: 'Mock host page',
previewLoading: 'Loading preview…',
previewUnavailable: 'Preview is unavailable. Ensure the channel is enabled and Redis is available.',
defaultChatTitle: 'AI Assistant',
newChat: 'New chat',
channelsPanelIntro: 'Create embed channels for this agent, configure appearance and security, then deploy to third-party sites.',
sectionChannel: 'Channel info',
sectionSecurity: 'Security & rate limit',
sectionCapabilities: 'Chat capabilities',
allowWebSearch: 'Show web search toggle',
allowWebSearchDesc: 'When enabled, visitors see a web search button in the input area and can turn it on or off themselves; it stays off by default. The button appears only if the bound agent has web search enabled.',
allowMemory: 'Allow memory',
allowMemoryDesc: 'When enabled, anonymous visitors retain context within the same session; memory is lost when they clear browser data or start a new chat. Off by default.',
allowFileUpload: 'Show file upload',
allowFileUploadDesc: 'When enabled, visitors can upload images and document attachments. Requires the bound agent to support image upload.',
webhookUrl: 'Webhook URL',
webhookUrlPlaceholder: 'https://your-server.example.com/weknora/embed-events',
webhookUrlDesc: 'Optional. WeKnora POSTs message_sent / message_received events to this HTTPS endpoint.',
webhookSecret: 'Webhook secret',
webhookSecretPlaceholder: 'HMAC-SHA256 secret (X-WeKnora-Signature header)',
webhookSecretKeep: 'Leave blank to keep the saved secret',
webhookSecretDesc: 'Optional. When set, request bodies are signed for verification on your server.',
secureModeDocHint: 'See docs/embed-secure-mode.md for the full integration guide',
agentWebSearchDisabledHint: 'This agent does not have web search enabled. Visitors will not see the web search button until you enable it in agent settings.',
agentImageUploadDisabledHint: 'This agent does not have image upload enabled. Visitors will not see the upload button until you enable it in agent settings.',
sectionAppearance: 'Appearance',
sectionDeploy: 'Deploy to site',
sectionWebhook: 'Event callbacks',
deployIntro: 'After saving, follow these two steps to embed chat on your website.',
deployStepToken: 'Channel key',
deployStepTokenDesc: 'Long-lived secret (em_…), like an API key. Shown on this page only when created or reset—store it safely.',
deployStepEmbed: 'Copy embed code',
deployStepEmbedDesc: 'Pick an embed style and paste the snippet into your site.',
embedIframeDesc: 'Embed the full chat in a fixed page area.',
embedWidgetDesc: 'Floating launcher in a corner; click to open the chat panel.',
embedSecureDesc: 'Recommended: the publish token stays on your own backend and the page only receives short-lived tokens, so the long-lived secret never reaches the browser.',
deployAfterSaveHint: 'After saving, you can copy the channel key and embed code here.',
widgetTokenNote: 'Widget scripts must include the channel key; iframe embeds exchange credentials automatically on load.',
secureTokenNote: 'The page no longer carries the publish token; it points at a token endpoint on your backend (data-token-endpoint). Your backend exchanges the publish token for a 30-minute short-lived token and returns it to the page; the widget auto-refreshes before expiry.',
secureServerLabel: 'Server-side token endpoint example (publish token stays on the server)',
secureServerCode: 'Server example',
tabServerNode: 'Node.js',
tabServerGo: 'Go',
sectionBasic: 'Basic settings',
sectionToken: 'Channel key',
sectionEmbed: 'Embed code',
enabled: 'Enable channel',
deleteConfirm: 'Delete this embed channel? Deployed snippets will stop working.',
rotateConfirmTitle: 'Reset channel key?',
rotateConfirmBody: 'The old channel key stops working immediately. Update every deployed embed snippet.',
defaultLocale: 'Default language',
defaultLocaleDesc: 'Visitor UI language when chat opens; empty follows the browser or host Widget setLocale().',
defaultLocaleBrowser: 'Browser / host default',
sessionCountLabel: '{n} sessions',
},
knowledgeEditor: {
titleCreate: 'Create Knowledge Base',
titleEdit: 'Knowledge Base Settings',
navGroups: {
basic: 'Basics',
processing: 'Indexing & Parsing',
data: 'Storage & Data',
integration: 'Publishing',
},
sidebar: {
basic: 'Basic Information',
models: 'Model Configuration',
@@ -4765,6 +4935,12 @@ export default {
},
agentEditor: {
builtinHint: 'This is a built-in agent. Name and description cannot be modified, but configuration parameters can be adjusted.',
navGroups: {
basic: 'Basics',
knowledge: 'Knowledge & Retrieval',
capability: 'Extensions',
integration: 'Publish & Integrate',
},
placeholders: {
available: 'Available variables: ',
clickToInsert: '(click to insert)',
@@ -4779,6 +4955,19 @@ export default {
customized: 'Customized',
empty: 'No intent templates available',
},
promptNav: {
ariaLabel: 'Prompt outline',
itemCount: '{n} items',
groupCore: 'Core prompts',
groupConversation: 'Conversation understanding',
groupFallback: 'Retrieval fallback',
system: 'System prompt',
context: 'Context template',
intent: 'Intent prompts',
rewriteSystem: 'Rewrite · System',
rewriteUser: 'Rewrite · User',
fallback: 'Retrieval fallback',
},
selection: {
all: 'All',
selected: 'Selected',
@@ -4809,7 +4998,7 @@ export default {
webSearchMaxResults: 'Maximum number of results returned per search',
webFetchEnabled: 'After reranking, auto-fetch full page content from top web results for better answers',
webFetchTopN: 'Maximum number of web pages to fetch after reranking',
retrievalSection: 'Configure knowledge base retrieval and ranking parameters',
retrievalSection: 'Configure knowledge base retrieval, ranking, and FAQ priority strategy',
queryExpansion: 'Automatically expand query terms to improve recall',
embeddingTopK: 'Maximum number of results from vector retrieval',
keywordThreshold: 'Minimum relevance score for keyword retrieval',
@@ -4890,6 +5079,10 @@ export default {
effectiveDesc: 'Computed from the current config — these are the tools the agent will actually be able to call',
effectiveEmpty: 'No tool available — the agent will fall back to plain model chat',
},
embed: {
title: 'Web Page Embed',
description: 'Embed this agent on your website so visitors can chat via an in-page window or floating launcher. Knowledge scope follows this agent.',
},
im: {
title: 'IM Integration',
description: 'Connect agent to instant messaging platforms like WeCom, Feishu, Slack, Telegram, DingTalk, Mattermost and WeChat',
@@ -4901,6 +5094,8 @@ export default {
wecom: 'WeCom',
wechat: 'WeChat',
addChannel: 'Add Channel',
channelsTitle: 'IM Channels',
disabled: 'Disabled',
editChannel: 'Edit Channel',
deleteConfirm: 'Are you sure you want to delete this channel? This action cannot be undone.',
channelName: 'Channel Name',
@@ -4911,7 +5106,7 @@ export default {
outputStream: 'Streaming',
outputFull: 'Full Response',
callbackUrl: 'Callback URL',
empty: 'No IM channels yet. Click the button below to add one.',
empty: 'No IM channels yet',
unnamed: 'Unnamed Channel',
docLink: 'Integration Guide',
feishuConsole: 'Feishu Open Platform',
@@ -4974,7 +5169,7 @@ export default {
imageUpload: {
navLabel: 'Multimodal',
sectionTitle: 'Multimodal Configuration',
sectionDesc: 'Configure image upload and vision-language model for multimodal conversations',
sectionDesc: 'Configure image/audio upload and their VLM and ASR models',
label: 'Image Upload',
desc: 'Allow users to upload images for multimodal Q&A in conversations',
vlmModel: 'VLM Model',
@@ -5065,6 +5260,7 @@ export default {
datasource: {
title: 'Data Sources',
description: 'Configure external data sources to sync content into this knowledge base',
channelsTitle: 'Data sources',
add: 'Add Data Source',
addFirst: 'Add your first data source',
empty: 'No data sources configured',
+193 -6
View File
@@ -28,7 +28,16 @@ export default {
expandSidebar: "사이드바 펼치기",
logoutSuccess: "로그아웃되었습니다",
myChats: "내 대화",
embedChats: "웹 임베드",
embedChannelNamed: "웹 임베드 · {name}",
groupBy: "그룹화",
groupNone: "없음",
groupDate: "날짜",
channelsSection: "채널 대화",
chatsSection: "웹 대화",
otherSources: "기타 출처",
noSessions: "대화가 없습니다",
loadMoreSessions: "더 보기",
},
newUserGuide: {
stepOf: "{current} / {total}",
@@ -1957,15 +1966,17 @@ export default {
createTitle: "에이전트 만들기",
editTitle: "에이전트 편집",
basicInfo: "기본정보",
basicInfoDesc: "에이전트 기본 정보 구성",
basicInfoDesc: "에이전트 이름, 설명 및 실행 모드 구성",
promptsConfig: "프롬프트",
promptsConfigDesc: "시스템/컨텍스트/의도/재작성/폴백 프롬프트 구성",
modelConfig: "모델 구성",
modelConfigDesc: "에이전트의 모델 매개변수 구성",
modelConfigDesc: "대화 모델, ReRank 등 보조 모델 및 생성 매개변수 구성",
capabilities: "능력과 도구",
capabilitiesDesc: "에이전트 구성을 위한 기능 및 도구",
toolsConfig: "도구 구성",
toolsConfigDesc: "에이전트가 사용할 수 있는 도구 구성",
knowledgeConfig: "지식베이스",
knowledgeConfigDesc: "에이전트가 액세스할 수 있는 지식베이스 구성",
knowledgeConfigDesc: "에이전트가 액세스할 수 있는 지식베이스 범위 및 FAQ 전략 구성",
webSearchConfig: "웹 검색",
webSearchConfigDesc: "에이전트의 네트워크 검색 기능 구성",
configuration: "구성 항목",
@@ -3129,9 +3140,159 @@ export default {
unknownKb: "지식베이스 {id}",
},
},
embedPublish: {
title: '웹 페이지 임베드',
description: '에이전트를 웹 페이지에 임베드하여 방문자가 페이지 내 채팅창 또는 우측 하단 플로팅 버튼으로 대화할 수 있게 합니다.',
create: '새 임베드 채널',
channelsTitle: '임베드 채널',
disabled: '비활성화',
empty: '임베드 채널 없음',
unnamed: '이름 없는 채널',
agent: '에이전트',
rateLimit: '속도 제한',
rateLimitUnit: '회/분',
allowedOrigins: '허용 도메인',
embedCode: '임베드 코드',
widgetCode: '위젯 스크립트',
copyCode: '코드 복사',
rotateToken: '토큰 교체',
rotatePublishToken: '게시 토큰 교체',
channelKey: '채널 키',
channelKeyDesc: '외부 사이트 연동용 장기 비밀키 — 안전하게 보관하세요',
channelKeyHint: '보안상 채널 키는 목록 API에서 반환되지 않습니다. 저장하지 않았다면 재설정하여 새 키를 생성하세요(현재 브라우저 세션에 임시 저장).',
channelKeyUnavailable: '키를 사용할 수 없음',
resetKeyTitle: '채널 키 재설정',
resetKeyConfirmOk: '재설정',
resetKeyConfirmBody: '재설정 후 이전 채널 키는 즉시 무효화됩니다. 배포된 모든 임베드 코드를 새 키로 교체해야 합니다. 되돌릴 수 없습니다.',
resetKeySuccess: '채널 키가 재설정되었습니다 — 입력란에 새 키가 표시됩니다',
resetKeyFailed: '채널 키 재설정 실패',
copyChannelKeyTitle: '채널 키 복사',
revealKey: '키 표시',
hideKey: '키 숨기기',
delete: '삭제',
edit: '편집',
createTitle: '새 임베드 채널',
editTitle: '임베드 채널 편집',
name: '이름',
nameDesc: '관리 목록 및 채널 식별용',
namePlaceholder: '예: 웹사이트 고객센터',
welcomeMessage: '환영 메시지',
welcomePlaceholder: '안녕하세요! 무엇을 도와드릴까요?',
showSuggestedQuestions: '추천 질문',
showSuggestedQuestionsDesc: '방문자 첫 메시지 전에 빠른 질문을 표시합니다(에이전트 설정 및 연결된 지식베이스에서 가져옴)',
originsLabel: '허용 도메인(한 줄에 하나, 최소 1개)',
originsHint: '한 줄에 하나의 전체 출처(예: https://shop.example.com), 최소 1개; *.example.com 서브도메인 와일드카드 지원',
originsRequired: '허용 도메인을 최소 1개 입력하세요',
originsInvalid: '잘못된 도메인: {origin}',
originsWildcardProd: "프로덕션에서는 와일드카드 '*'를 사용할 수 없습니다",
originsCount: '허용 도메인 {n}개',
originsPlaceholder: 'https://shop.example.com',
rateLimitLabel: '분당 요청 상한',
rateLimitDesc: '방문자 IP 기준, 분당 최대 임베드 API 요청 수; 초과 시 일시 거부. 기본 30.',
rateLimitDayLabel: '일일 요청 총 상한',
rateLimitDayDesc: '채널 전체 일일 요청 총량(모든 방문자 IP 합산); 게시 토큰 유출 시 남용 비용 제한. 기본 10000.',
publishTokenWarning: '게시 토큰은 임베드 페이지 소스에 평문으로 노출됩니다 — 호스트 사이트 방문자가 읽을 수 있습니다. 기밀 키가 아닌 공개 가능 키로 취급하세요: 민감 데이터 에이전트는 임베드하지 말고, 도메인 화이트리스트와 요청 상한을 설정하며, 유출 시 즉시 토큰을 교체하세요.',
debug: '디버그 미리보기',
createdDebugHint: '임베드 채널이 생성되었습니다 — 디버그 미리보기로 새 탭에서 확인하세요',
primaryColor: '테마 색상',
pageTitle: '페이지 제목',
pageTitleDesc: '방문자 채팅 헤더 및 브라우저 탭에 표시; 이름보다 우선',
pageTitlePlaceholder: 'AI 어시스턴트',
headerTitleMode: '헤더 제목',
headerTitleModeChannel: '고정 채널 제목',
headerTitleModeSession: '세션 제목 따르기',
headerTitleModeDesc: '고정: 항상 페이지 제목 표시. 세션: 첫 메시지 후 자동 제목; 생성 전까지 페이지 제목 사용.',
tokenHint: '보안상 채널 키는 목록 API에서 반환되지 않습니다. 위젯 스크립트 복사 전 생성 또는 재설정 시 키를 저장하세요(현재 브라우저 세션에 임시 저장).',
createdWithToken: '임베드 채널 생성됨 — 입력란에 새 키가 표시됩니다. 지금 복사하여 보관하세요',
created: '임베드 채널이 생성되었습니다',
updated: '임베드 채널이 업데이트되었습니다',
saveFailed: '저장 실패',
deleted: '삭제됨',
tokenRotated: '채널 키가 재설정되었습니다',
copied: '임베드 코드가 복사되었습니다',
loadError: '로드 실패',
missingChannel: '임베드 채널 또는 토큰 없음',
invalidChannel: '잘못된 임베드 채널',
sessionFailed: '대화 세션을 생성할 수 없습니다. 나중에 다시 시도하세요',
channelDisabled: '임베드 채널이 비활성화되었습니다. 에이전트 편집기 → 웹 페이지 임베드에서 다시 활성화하세요',
loading: '로딩 중...',
tabIframe: 'iframe',
tabWidget: '위젯',
tabSecure: '보안 모드',
widgetPosition: '위젯 위치',
widgetPreview: '위젯 미리보기',
positionBottomRight: '오른쪽 하단',
positionBottomLeft: '왼쪽 하단',
positionTopRight: '오른쪽 상단',
positionTopLeft: '왼쪽 상단',
publishToken: '채널 키',
publishTokenHelp: '채널 키(em_…)는 이 임베드 채널의 장기 비밀키(API Key와 유사)입니다. 생성 또는 재설정 시에만 표시되며 호스트 사이트 위젯 스크립트에 넣어야 합니다.',
sessionTokenHelp: '방문자가 채팅을 열면 iframe이 채널 키를 단기 세션 자격증명(ems_…, ~30분)으로 교환합니다. 이후 요청은 세션 자격증명을 사용합니다.',
rotateTokenHelp: '재설정하면 이전 채널 키가 무효화됩니다. 배포된 모든 임베드 코드를 업데이트해야 합니다.',
revealToken: '표시',
hideToken: '숨기기',
copyToken: '채널 키 복사',
tokenCopied: '채널 키가 복사되었습니다',
awaitingToken: '호스트 페이지에서 토큰 제공 대기 중…',
preview: '미리보기',
previewIframeHint: 'iframe 임베드가 외부 페이지에서 어떻게 보이는지 시뮬레이션합니다(복사한 코드와 동일).',
previewWidgetHint: '모의 호스트 페이지에서 플로팅 위젯을 표시합니다. 실제 사이트에서는 postMessage로 토큰을 전달합니다.',
previewMockPage: '모의 호스트 페이지',
previewLoading: '미리보기 로딩 중…',
previewUnavailable: '미리보기를 사용할 수 없습니다. 채널이 활성화되어 있고 Redis가 사용 가능한지 확인하세요.',
defaultChatTitle: 'AI 어시스턴트',
newChat: '새 대화',
channelsPanelIntro: '이 에이전트용 임베드 채널을 만들고, 외관 및 보안을 설정한 뒤 외부 사이트에 배포하세요.',
sectionChannel: '채널 정보',
sectionSecurity: '보안 및 속도 제한',
sectionCapabilities: '대화 기능',
allowWebSearch: '웹 검색 토글 표시',
allowWebSearchDesc: '활성화하면 방문자 입력창에 웹 검색 버튼이 표시되며, 방문자가 직접 켜거나 끌 수 있습니다. 기본값은 꺼짐입니다. 연결된 에이전트에서 웹 검색이 활성화된 경우에만 버튼이 나타납니다.',
allowMemory: '메모리 허용',
allowMemoryDesc: '활성화하면 익명 방문자가 동일 세션 내에서 컨텍스트를 유지합니다. 브라우저 데이터 삭제 또는 새 대화 시작 시 메모리가 사라집니다. 기본값은 꺼짐.',
allowFileUpload: '이미지 업로드 버튼 표시',
allowFileUploadDesc: '활성화하면 방문자 입력창에 이미지 업로드 버튼이 표시됩니다. 연결된 에이전트에서 이미지 업로드가 활성화된 경우에만 버튼이 나타납니다.',
agentWebSearchDisabledHint: '현재 에이전트에서 웹 검색이 활성화되지 않았습니다. 방문자에게 웹 검색 버튼이 표시되지 않습니다. 에이전트 설정에서 웹 검색을 먼저 활성화하세요.',
agentImageUploadDisabledHint: '현재 에이전트에서 이미지 업로드가 활성화되지 않았습니다. 방문자에게 업로드 버튼이 표시되지 않습니다. 에이전트 설정에서 이미지 업로드를 먼저 활성화하세요.',
sectionAppearance: '외관 및 표시',
sectionDeploy: '사이트에 배포',
deployIntro: '저장 후 다음 두 단계로 웹사이트에 채팅을 임베드하세요.',
deployStepToken: '채널 키',
deployStepTokenDesc: '장기 비밀키(em_…), API Key와 유사. 생성 또는 재설정 시 이 페이지에서만 표시 — 안전하게 보관하세요.',
deployStepEmbed: '임베드 코드 복사',
deployStepEmbedDesc: '임베드 방식을 선택하고 코드를 사이트에 붙여넣으세요.',
embedIframeDesc: '페이지 고정 영역에 전체 채팅을 임베드합니다.',
embedWidgetDesc: '모서리 플로팅 런처; 클릭하여 채팅 패널을 엽니다.',
embedSecureDesc: '권장: 게시 토큰은 자체 백엔드에만 두고 페이지는 단기 토큰만 받아 브라우저에 장기 비밀키가 노출되지 않습니다.',
deployAfterSaveHint: '저장 후 여기에서 채널 키와 임베드 코드를 복사할 수 있습니다.',
widgetTokenNote: '위젯 스크립트에는 채널 키가 포함되어야 합니다; iframe은 로드 시 자동으로 자격증명을 교환합니다.',
secureTokenNote: '페이지에 게시 토큰이 없고 백엔드 토큰 엔드포인트(data-token-endpoint)를 가리킵니다. 백엔드가 30분 단기 토큰을 반환하고 위젯은 만료 전 자동 갱신합니다.',
secureServerLabel: '서버 측 토큰 엔드포인트 예시(게시 토큰은 서버에만 보관)',
secureServerCode: '서버 예시 코드',
tabServerNode: 'Node.js',
tabServerGo: 'Go',
sectionBasic: '기본 설정',
sectionToken: '채널 키',
sectionEmbed: '임베드 코드',
enabled: '채널 활성화',
deleteConfirm: '이 임베드 채널을 삭제하시겠습니까? 배포된 코드가 작동하지 않습니다.',
rotateConfirmTitle: '채널 키를 재설정하시겠습니까?',
rotateConfirmBody: '이전 채널 키는 즉시 무효화됩니다. 배포된 모든 임베드 코드를 업데이트하세요.',
defaultLocale: '기본 언어',
defaultLocaleDesc: '방문자가 채팅을 열 때 사용할 UI 언어; 비우면 브라우저 또는 Widget setLocale()을 따릅니다.',
defaultLocaleBrowser: '브라우저 / 호스트 기본값',
sessionCountLabel: '세션 {n}개',
},
knowledgeEditor: {
titleCreate: "지식베이스 생성",
titleEdit: "지식베이스 설정",
navGroups: {
basic: "기본",
processing: "인덱싱 및 파싱",
data: "스토리지 및 데이터",
integration: "게시 및 통합",
},
sidebar: {
basic: "기본 정보",
models: "모델 설정",
@@ -4803,6 +4964,12 @@ export default {
},
agentEditor: {
builtinHint: '내장 에이전트입니다. 이름과 설명은 수정할 수 없지만, 설정 매개변수는 조정할 수 있습니다.',
navGroups: {
basic: '기본',
knowledge: '지식 검색',
capability: '기능 확장',
integration: '게시 및 통합',
},
placeholders: {
available: '사용 가능한 변수: ',
clickToInsert: '(클릭하여 삽입)',
@@ -4817,6 +4984,19 @@ export default {
customized: '사용자 정의됨',
empty: '사용 가능한 의도 템플릿이 없습니다',
},
promptNav: {
ariaLabel: '프롬프트 목차',
itemCount: '총 {n}개',
groupCore: '핵심 프롬프트',
groupConversation: '대화 이해',
groupFallback: '검색 폴백',
system: '시스템 프롬프트',
context: '컨텍스트 템플릿',
intent: '의도 프롬프트',
rewriteSystem: '재작성 · 시스템',
rewriteUser: '재작성 · 사용자',
fallback: '검색 폴백',
},
selection: {
all: '전체',
selected: '지정',
@@ -4847,7 +5027,7 @@ export default {
webSearchMaxResults: '검색당 반환되는 최대 결과 수',
webFetchEnabled: 'Rerank 후 상위 웹 페이지의 전체 콘텐츠를 자동으로 가져와 답변 품질을 향상시킵니다',
webFetchTopN: 'Rerank 후 전체 콘텐츠를 가져올 최대 웹 페이지 수',
retrievalSection: '지식베이스 검색 및 순위 매개변수 설정',
retrievalSection: '지식베이스 검색·순위 및 FAQ 우선 전략 설정',
queryExpansion: '쿼리 용어를 자동으로 확장하여 재현율 향상',
embeddingTopK: '벡터 검색에서 반환되는 최대 결과 수',
keywordThreshold: '키워드 검색의 최소 관련성 점수',
@@ -4858,6 +5038,10 @@ export default {
fallbackResponse: '응답할 수 없을 때 반환할 고정 텍스트',
fallbackPrompt: '지식베이스에서 답변을 찾을 수 없을 때 모델 응답을 유도하는 프롬프트',
},
embed: {
title: '웹 페이지 임베드',
description: '에이전트를 웹 페이지에 임베드하여 방문자가 페이지 내 채팅창 또는 플로팅 버튼으로 대화할 수 있게 합니다. 지식베이스 범위는 이 에이전트 설정을 따릅니다.',
},
im: {
title: "IM 통합",
description: "에이전트를 Feishu, Slack, Telegram, DingTalk, Mattermost 등 인스턴트 메시징 플랫폼에 연결",
@@ -4869,6 +5053,8 @@ export default {
mattermost: "Mattermost",
wechat: "WeChat",
addChannel: "채널 추가",
channelsTitle: "IM 채널",
disabled: "비활성",
editChannel: "채널 편집",
deleteConfirm: "이 채널을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.",
channelName: "채널 이름",
@@ -4879,7 +5065,7 @@ export default {
outputStream: "스트리밍",
outputFull: "전체 응답",
callbackUrl: "콜백 URL",
empty: "IM 채널이 없습니다. 아래 버튼을 클릭하여 추가하세요.",
empty: "IM 채널이 없습니다",
unnamed: "이름 없는 채널",
docLink: "통합 가이드 보기",
feishuConsole: "Feishu 개발 플랫폼",
@@ -5012,7 +5198,7 @@ export default {
imageUpload: {
navLabel: '멀티모달',
sectionTitle: '멀티모달 설정',
sectionDesc: '이미지 업로드 및 비전 언어 모델을 설정하여 대화에서 멀티모달 기능을 활성화합니다',
sectionDesc: '이미지/오디오 업로드와 VLM·ASR 모델을 설정합니다',
label: '이미지 업로드',
desc: '활성화하면 사용자가 대화에서 이미지를 업로드하여 멀티모달 질의응답을 할 수 있습니다',
vlmModel: 'VLM 모델',
@@ -5103,6 +5289,7 @@ export default {
datasource: {
title: "데이터 소스 관리",
description: "외부 데이터 소스를 구성하여 콘텐츠를 지식베이스에 자동 동기화",
channelsTitle: "데이터 소스",
add: "데이터 소스 추가",
addFirst: "첫 번째 데이터 소스 추가",
empty: "구성된 데이터 소스가 없습니다",
+193 -6
View File
@@ -26,7 +26,16 @@ export default {
expandSidebar: 'Развернуть боковую панель',
logoutSuccess: 'Вы вышли из системы',
myChats: 'Мои чаты',
embedChats: 'Веб-встраивание',
embedChannelNamed: 'Веб-встраивание · {name}',
groupBy: 'Группировать',
groupNone: 'Нет',
groupDate: 'Дата',
channelsSection: 'Чаты каналов',
chatsSection: 'Веб-чаты',
otherSources: 'Другие источники',
noSessions: 'Пока нет диалогов',
loadMoreSessions: 'Загрузить ещё',
agents: 'Агенты',
organizations: 'Общие пространства'
},
@@ -793,15 +802,17 @@ export default {
createTitle: 'Create Agent',
editTitle: 'Edit Agent',
basicInfo: 'Basic Info',
basicInfoDesc: 'Configure agent basic information',
basicInfoDesc: 'Настройка имени, описания и режима работы агента',
promptsConfig: 'Промпты',
promptsConfigDesc: 'Настройка системных, контекстных, intent/rewrite/fallback промптов',
modelConfig: 'Model Config',
modelConfigDesc: 'Configure agent model parameters',
modelConfigDesc: 'Модель чата, вспомогательные модели (ReRank) и параметры генерации',
capabilities: 'Capabilities',
capabilitiesDesc: 'Configure agent capabilities and tools',
toolsConfig: 'Tools',
toolsConfigDesc: 'Configure tools available to the Agent',
knowledgeConfig: 'Knowledge Base',
knowledgeConfigDesc: 'Configure knowledge bases for the agent',
knowledgeConfigDesc: 'Настройка области баз знаний и стратегии FAQ для агента',
webSearchConfig: 'Web Search',
webSearchConfigDesc: 'Configure web search capabilities for the agent',
configuration: 'Configuration',
@@ -2636,9 +2647,159 @@ export default {
disabled: 'Disabled'
}
},
embedPublish: {
title: 'Встраивание на веб-страницу',
description: 'Встройте агента на свою веб-страницу: посетители смогут общаться через встроенное окно чата или плавающую кнопку.',
create: 'Новый канал встраивания',
channelsTitle: 'Каналы встраивания',
disabled: 'Отключено',
empty: 'Каналов встраивания пока нет',
unnamed: 'Без названия',
agent: 'Агент',
rateLimit: 'Лимит',
rateLimitUnit: '/мин',
allowedOrigins: 'Разрешённые домены',
embedCode: 'Код встраивания',
widgetCode: 'Скрипт виджета',
copyCode: 'Копировать код',
rotateToken: 'Сменить токен',
rotatePublishToken: 'Сменить токен публикации',
channelKey: 'Ключ канала',
channelKeyDesc: 'Долгоживущий секрет для интеграции на сторонних сайтах — храните в безопасности',
channelKeyHint: 'Из соображений безопасности ключи каналов не возвращаются в API списка. Если не сохранили — сбросьте для нового ключа (временно в сессии браузера).',
channelKeyUnavailable: 'Ключ недоступен',
resetKeyTitle: 'Сбросить ключ канала',
resetKeyConfirmOk: 'Сбросить',
resetKeyConfirmBody: 'После сброса старый ключ канала немедленно отзывается. Все развёрнутые фрагменты встраивания должны использовать новый ключ. Отменить нельзя.',
resetKeySuccess: 'Ключ канала сброшен — новый ключ показан в поле ввода',
resetKeyFailed: 'Не удалось сбросить ключ канала',
copyChannelKeyTitle: 'Копировать ключ канала',
revealKey: 'Показать ключ',
hideKey: 'Скрыть ключ',
delete: 'Удалить',
edit: 'Редактировать',
createTitle: 'Новый канал встраивания',
editTitle: 'Редактировать канал встраивания',
name: 'Название',
nameDesc: 'Для админ-списков и идентификации канала',
namePlaceholder: 'напр. Поддержка на сайте',
welcomeMessage: 'Приветствие',
welcomePlaceholder: 'Здравствуйте! Чем могу помочь?',
showSuggestedQuestions: 'Рекомендуемые вопросы',
showSuggestedQuestionsDesc: 'Показывать быстрые вопросы до первого сообщения посетителя — из настроек агента и связанных баз знаний',
originsLabel: 'Разрешённые домены (по одному в строке, минимум один)',
originsHint: 'Один полный origin в строке (напр. https://shop.example.com), минимум один; поддерживаются поддомены *.example.com',
originsRequired: 'Укажите хотя бы один разрешённый домен',
originsInvalid: 'Неверный домен: {origin}',
originsWildcardProd: "В production запрещён wildcard '*'",
originsCount: '{n} разрешённых доменов',
originsPlaceholder: 'https://shop.example.com',
rateLimitLabel: 'Запросов в минуту',
rateLimitDesc: 'На IP посетителя, макс. запросов к API встраивания в минуту; избыток временно отклоняется. По умолчанию 30.',
rateLimitDayLabel: 'Дневной лимит запросов',
rateLimitDayDesc: 'Суточный лимит запросов канала (все IP); ограничивает злоупотребление при утечке токена публикации. По умолчанию 10000.',
publishTokenWarning: 'Токен публикации виден в исходном коде страницы встраивания — любой посетитель сайта может его прочитать. Считайте его публикуемым ключом, а не секретом: не встраивайте агентов с чувствительными данными, настройте whitelist доменов и лимиты, при утечке немедленно смените токен.',
debug: 'Отладочный предпросмотр',
createdDebugHint: 'Канал создан — откройте отладочный предпросмотр в новой вкладке',
primaryColor: 'Основной цвет',
pageTitle: 'Заголовок страницы',
pageTitleDesc: 'В шапке чата и вкладке браузера; приоритетнее названия',
pageTitlePlaceholder: 'AI-ассистент',
headerTitleMode: 'Заголовок шапки',
headerTitleModeChannel: 'Фиксированный заголовок канала',
headerTitleModeSession: 'Следовать заголовку сессии',
headerTitleModeDesc: 'Фиксированный: всегда заголовок страницы. Сессия: авто-заголовок из первого сообщения; до генерации — заголовок страницы.',
tokenHint: 'Из соображений безопасности ключи не возвращаются в API списка. Сохраните ключ при создании или сбросе перед копированием виджета (в сессии браузера).',
createdWithToken: 'Канал создан — новый ключ в поле ввода; скопируйте и сохраните сейчас',
created: 'Канал встраивания создан',
updated: 'Канал встраивания обновлён',
saveFailed: 'Не удалось сохранить',
deleted: 'Удалено',
tokenRotated: 'Ключ канала сброшен',
copied: 'Код встраивания скопирован',
loadError: 'Не удалось загрузить',
missingChannel: 'Отсутствует канал встраивания или токен',
invalidChannel: 'Недействительный канал встраивания',
sessionFailed: 'Не удалось создать сессию чата, попробуйте позже',
channelDisabled: 'Канал встраивания отключён. Включите в редакторе агента → Встраивание на веб-страницу',
loading: 'Загрузка...',
tabIframe: 'iframe',
tabWidget: 'Виджет',
tabSecure: 'Безопасный режим',
widgetPosition: 'Позиция виджета',
widgetPreview: 'Предпросмотр виджета',
positionBottomRight: 'Справа внизу',
positionBottomLeft: 'Слева внизу',
positionTopRight: 'Справа вверху',
positionTopLeft: 'Слева вверху',
publishToken: 'Ключ канала',
publishTokenHelp: 'Ключ канала (em_…) — долгоживущий секрет канала, как API Key. Показывается только при создании или сбросе; вставляется в скрипт виджета на сайте.',
sessionTokenHelp: 'После открытия чата iframe обменивает ключ канала на краткосрочный сеансовый (ems_…, ~30 мин). Дальнейшие запросы используют сеансовый, ключ не остаётся в URL.',
rotateTokenHelp: 'Сброс отзывает предыдущий ключ. Обновите все развёрнутые фрагменты встраивания.',
revealToken: 'Показать',
hideToken: 'Скрыть',
copyToken: 'Копировать ключ канала',
tokenCopied: 'Ключ канала скопирован',
awaitingToken: 'Ожидание токена от страницы-хоста…',
preview: 'Предпросмотр',
previewIframeHint: 'Как iframe выглядит на сторонней странице (как в скопированном коде).',
previewWidgetHint: 'Плавающий виджет на mock-странице. На реальном сайте токен передаётся через postMessage.',
previewMockPage: 'Mock-страница хоста',
previewLoading: 'Загрузка предпросмотра…',
previewUnavailable: 'Предпросмотр недоступен. Убедитесь, что канал включён и Redis доступен.',
defaultChatTitle: 'AI-ассистент',
newChat: 'Новый чат',
channelsPanelIntro: 'Создайте каналы встраивания для агента, настройте внешний вид и безопасность, затем разверните на сторонних сайтах.',
sectionChannel: 'Информация о канале',
sectionSecurity: 'Безопасность и лимиты',
sectionCapabilities: 'Возможности чата',
allowWebSearch: 'Показывать переключатель веб-поиска',
allowWebSearchDesc: 'При включении посетители видят кнопку веб-поиска в поле ввода и могут включать или выключать его сами; по умолчанию выключен. Кнопка появляется только если у привязанного агента включён веб-поиск.',
allowMemory: 'Разрешить память',
allowMemoryDesc: 'При включении анонимные посетители сохраняют контекст в рамках одной сессии; память теряется при очистке данных браузера или новом чате. По умолчанию выключено.',
allowFileUpload: 'Показывать кнопку загрузки изображений',
allowFileUploadDesc: 'При включении посетители видят кнопку загрузки изображений в поле ввода. Кнопка появляется только если у привязанного агента включена загрузка изображений.',
agentWebSearchDisabledHint: 'У этого агента не включён веб-поиск. Посетители не увидят кнопку веб-поиска, пока вы не включите его в настройках агента.',
agentImageUploadDisabledHint: 'У этого агента не включена загрузка изображений. Посетители не увидят кнопку загрузки, пока вы не включите её в настройках агента.',
sectionAppearance: 'Внешний вид',
sectionDeploy: 'Развернуть на сайте',
deployIntro: 'После сохранения выполните два шага для встраивания чата на сайт.',
deployStepToken: 'Ключ канала',
deployStepTokenDesc: 'Долгоживущий секрет (em_…), как API Key. Только на этой странице при создании/сбросе — храните надёжно.',
deployStepEmbed: 'Копировать код встраивания',
deployStepEmbedDesc: 'Выберите способ встраивания и вставьте код на сайт.',
embedIframeDesc: 'Встроить полный чат в фиксированную область страницы.',
embedWidgetDesc: 'Плавающая кнопка в углу; по клику открывается панель чата.',
embedSecureDesc: 'Рекомендуется: токен публикации только на вашем backend, страница получает краткосрочные токены — долгоживущий секрет не попадает в браузер.',
deployAfterSaveHint: 'После сохранения здесь можно скопировать ключ канала и код встраивания.',
widgetTokenNote: 'Скрипт виджета должен содержать ключ канала; iframe обменивает учётные данные при загрузке.',
secureTokenNote: 'На странице нет токена публикации — только endpoint вашего backend (data-token-endpoint). Backend обменивает токен на 30-минутный; виджет обновляет до истечения.',
secureServerLabel: 'Пример server-side endpoint токена (токен публикации только на сервере)',
secureServerCode: 'Пример для сервера',
tabServerNode: 'Node.js',
tabServerGo: 'Go',
sectionBasic: 'Основные настройки',
sectionToken: 'Ключ канала',
sectionEmbed: 'Код встраивания',
enabled: 'Включить канал',
deleteConfirm: 'Удалить этот канал? Развёрнутые фрагменты перестанут работать.',
rotateConfirmTitle: 'Сбросить ключ канала?',
rotateConfirmBody: 'Старый ключ немедленно перестанет работать. Обновите все развёрнутые фрагменты.',
defaultLocale: 'Язык по умолчанию',
defaultLocaleDesc: 'Язык интерфейса при открытии чата; пусто — браузер или setLocale() виджета.',
defaultLocaleBrowser: 'Браузер / хост',
sessionCountLabel: '{n} сессий',
},
knowledgeEditor: {
titleCreate: 'Создать базу знаний',
titleEdit: 'Настройки базы знаний',
navGroups: {
basic: 'Основное',
processing: 'Индексация и разбор',
data: 'Хранение и данные',
integration: 'Публикация',
},
sidebar: {
basic: 'Основная информация',
models: 'Конфигурация моделей',
@@ -4303,6 +4464,12 @@ export default {
},
agentEditor: {
builtinHint: 'Это встроенный агент. Имя и описание нельзя изменить, но можно настроить параметры конфигурации.',
navGroups: {
basic: 'Основное',
knowledge: 'Знания и поиск',
capability: 'Расширения',
integration: 'Публикация и интеграция',
},
placeholders: {
available: 'Доступные переменные: ',
clickToInsert: '(нажмите для вставки)',
@@ -4317,6 +4484,19 @@ export default {
customized: 'Настроено',
empty: 'Нет доступных шаблонов намерений',
},
promptNav: {
ariaLabel: 'Оглавление промптов',
itemCount: '{n} разделов',
groupCore: 'Основные промпты',
groupConversation: 'Понимание диалога',
groupFallback: 'Запасной ответ при поиске',
system: 'Системный промпт',
context: 'Шаблон контекста',
intent: 'Промпты намерений',
rewriteSystem: 'Перефраз · Система',
rewriteUser: 'Перефраз · Пользователь',
fallback: 'Запасной ответ',
},
selection: {
all: 'Все',
selected: 'Выбранные',
@@ -4347,7 +4527,7 @@ export default {
webSearchMaxResults: 'Максимальное количество результатов на один поиск',
webFetchEnabled: 'Автоматически загружать полное содержимое лучших страниц после Rerank для повышения качества ответов',
webFetchTopN: 'Максимальное количество страниц для загрузки полного содержимого после Rerank',
retrievalSection: 'Настройка параметров поиска и ранжирования базы знаний',
retrievalSection: 'Настройка поиска, ранжирования и стратегии приоритета FAQ',
queryExpansion: 'Автоматическое расширение поисковых запросов для улучшения полноты',
embeddingTopK: 'Максимальное количество результатов векторного поиска',
keywordThreshold: 'Минимальная оценка релевантности для поиска по ключевым словам',
@@ -4428,6 +4608,10 @@ export default {
effectiveDesc: 'Рассчитано на основе текущей конфигурации — это набор инструментов, которые агент сможет вызывать после сохранения',
effectiveEmpty: 'Нет доступных инструментов — агент перейдёт к простому чату с моделью'
},
embed: {
title: 'Встраивание на веб-страницу',
description: 'Встройте агента на свою веб-страницу: посетители смогут общаться через встроенное окно чата или плавающую кнопку. Область баз знаний следует настройкам этого агента.',
},
im: {
title: 'Интеграция IM',
description: 'Подключите агента к платформам мгновенных сообщений, таким как Feishu, Slack, Telegram, DingTalk и Mattermost',
@@ -4439,6 +4623,8 @@ export default {
mattermost: 'Mattermost',
wechat: 'WeChat',
addChannel: 'Добавить канал',
channelsTitle: 'IM-каналы',
disabled: 'Отключено',
editChannel: 'Редактировать канал',
deleteConfirm: 'Вы уверены, что хотите удалить этот канал? Это действие не может быть отменено.',
channelName: 'Имя канала',
@@ -4449,7 +4635,7 @@ export default {
outputStream: 'Стриминг',
outputFull: 'Полное выходное значение',
callbackUrl: 'URL обратного вызова',
empty: 'Нет IM каналов. Нажмите кнопку ниже, чтобы добавить один.',
empty: 'Нет IM-каналов',
unnamed: 'Неименованный канал',
docLink: 'Руководство по интеграции',
feishuConsole: 'Платформа Feishu',
@@ -4512,7 +4698,7 @@ export default {
imageUpload: {
navLabel: 'Мультимодальность',
sectionTitle: 'Настройка мультимодальности',
sectionDesc: 'Настройте загрузку изображений и визуально-языковую модель для мультимодальных диалогов',
sectionDesc: 'Настройте загрузку изображений/аудио и соответствующие модели VLM и ASR',
label: 'Загрузка изображений',
desc: 'Разрешить пользователям загружать изображения для мультимодальных вопросов и ответов',
vlmModel: 'Модель VLM',
@@ -4925,6 +5111,7 @@ export default {
datasource: {
title: 'Источники данных',
description: 'Настройте внешние источники данных для автоматической синхронизации контента',
channelsTitle: 'Источники данных',
add: 'Добавить источник',
addFirst: 'Добавить первый источник данных',
empty: 'Источники данных не настроены',
+203 -7
View File
@@ -28,7 +28,16 @@ export default {
expandSidebar: "展开侧边栏",
logoutSuccess: "已退出登录",
myChats: "我的对话",
embedChats: "网页嵌入",
embedChannelNamed: "网页嵌入 · {name}",
groupBy: "分组方式",
groupNone: "无",
groupDate: "日期",
channelsSection: "渠道对话",
chatsSection: "网页对话",
otherSources: "其他来源",
noSessions: "暂无对话",
loadMoreSessions: "加载更多",
},
newUserGuide: {
stepOf: "{current} / {total}",
@@ -357,6 +366,7 @@ export default {
description: "描述",
files: "文件",
settings: "设置",
publishToWeb: "发布到网站",
documentCategoryTitle: "文档分类",
faqCategoryTitle: "问题分类",
untagged: "未分类",
@@ -1961,15 +1971,17 @@ export default {
createTitle: "创建智能体",
editTitle: "编辑智能体",
basicInfo: "基本信息",
basicInfoDesc: "配置智能体的基本信息",
basicInfoDesc: "配置智能体的名称、描述与运行模式",
promptsConfig: "提示词",
promptsConfigDesc: "配置系统提示词、上下文模板、意图/改写/兜底提示词",
modelConfig: "模型配置",
modelConfigDesc: "配置智能体的模型参数",
modelConfigDesc: "配置对话模型、ReRank 等辅助模型及生成参数",
capabilities: "能力与工具",
capabilitiesDesc: "配置智能体的能力和工具",
toolsConfig: "工具配置",
toolsConfigDesc: "配置 Agent 可以使用的工具",
knowledgeConfig: "知识库",
knowledgeConfigDesc: "配置智能体可访问的知识库",
knowledgeConfigDesc: "配置智能体可访问的知识库范围与 FAQ 策略",
webSearchConfig: "网络搜索",
webSearchConfigDesc: "配置智能体的网络搜索能力",
configuration: "配置项",
@@ -3126,9 +3138,167 @@ export default {
unknownKb: "知识库 {id}",
},
},
embedPublish: {
title: "网页嵌入",
description: "将智能体嵌入到您的网页,访客可通过页面内聊天窗口或右下角浮窗发起对话。",
create: "新建嵌入渠道",
channelsTitle: "嵌入渠道",
disabled: "已停用",
empty: "暂无嵌入渠道",
unnamed: "未命名渠道",
agent: "智能体",
rateLimit: "限流",
rateLimitUnit: "次/分钟",
allowedOrigins: "域名白名单",
embedCode: "嵌入代码",
widgetCode: "浮窗脚本",
copyCode: "复制代码",
rotateToken: "轮换 Token",
rotatePublishToken: "轮换发布 Token",
channelKey: "渠道密钥",
channelKeyDesc: "用于第三方网站接入的长期密钥,请妥善保管",
channelKeyHint: "渠道密钥出于安全考虑不会在列表中返回。若未保存,请点击重置获取新密钥(当前浏览器会话内会暂存)。",
channelKeyUnavailable: "密钥不可用",
resetKeyTitle: "重置渠道密钥",
resetKeyConfirmOk: "确认重置",
resetKeyConfirmBody: "重置后,旧的渠道密钥会立即失效,所有已部署的嵌入代码必须更换为新密钥才能继续访问。此操作不可撤销。",
resetKeySuccess: "渠道密钥已重置,新密钥已显示在输入框中",
resetKeyFailed: "重置渠道密钥失败",
copyChannelKeyTitle: "复制渠道密钥",
revealKey: "显示密钥",
hideKey: "隐藏密钥",
delete: "删除",
edit: "编辑",
createTitle: "新建嵌入渠道",
editTitle: "编辑嵌入渠道",
name: "名称",
nameDesc: "后台管理用,用于列表与渠道识别",
namePlaceholder: "例如:官网客服",
welcomeMessage: "欢迎语",
welcomePlaceholder: "你好,有什么可以帮您?",
showSuggestedQuestions: "推荐问题",
showSuggestedQuestionsDesc: "访客未发言前展示快捷提问,内容来自智能体配置与关联知识库",
originsLabel: "域名白名单(每行一个,至少填写一个)",
originsHint: "每行一个完整来源地址(如 https://shop.example.com),至少填写一个;支持 *.example.com 子域通配",
originsRequired: "请至少填写一个域名白名单",
originsInvalid: "域名格式无效:{origin}",
originsWildcardProd: "生产环境不允许使用通配符 *",
originsCount: "白名单 {n} 个",
originsPlaceholder: "https://shop.example.com",
rateLimitLabel: "每分钟请求上限",
rateLimitDesc: "按访客 IP 统计,每分钟最多允许的嵌入接口请求次数;超出后暂时拒绝访问,默认 30。",
rateLimitDayLabel: "每日请求总上限",
rateLimitDayDesc: "整个渠道每天(跨所有访客 IP)允许的请求总数;用于限制发布 Token 被复制后被刷量的成本,默认 10000。",
publishTokenWarning: "发布 Token 会以明文出现在嵌入页面源码中,任何访问该网站的人都能看到,请将其视为「可公开密钥」而非机密:切勿把含敏感数据的智能体做成嵌入渠道;务必配置域名白名单与请求上限;Token 泄露时可随时「重置 Token」作废旧值。",
debug: "调试预览",
createdDebugHint: "嵌入渠道已创建,可点击「调试预览」在新标签页体验",
primaryColor: "主题色",
pageTitle: "页面标题",
pageTitleDesc: "访客聊天页标题与浏览器标签;优先于名称展示",
pageTitlePlaceholder: "AI 客服",
headerTitleMode: "顶栏标题",
headerTitleModeChannel: "固定渠道标题",
headerTitleModeSession: "跟随会话标题",
headerTitleModeDesc: "固定渠道标题:始终显示页面标题;跟随会话标题:首条消息后按对话内容自动命名,未生成前显示页面标题",
tokenHint: "渠道密钥出于安全考虑不会在列表中返回。复制浮窗脚本前,请在创建或重置时保存密钥(当前浏览器会话内会暂存)。",
createdWithToken: "嵌入渠道已创建,新密钥已显示在输入框中,请立即复制并妥善保存",
created: "嵌入渠道已创建",
updated: "嵌入渠道已更新",
saveFailed: "保存失败",
deleted: "已删除",
tokenRotated: "渠道密钥已重置",
copied: "已复制嵌入代码",
loadError: "加载失败",
missingChannel: "缺少嵌入渠道或 Token",
invalidChannel: "无效的嵌入渠道",
sessionFailed: "无法创建对话会话,请稍后重试",
channelDisabled: "嵌入渠道已停用,请在 Agent 编辑器的「网页嵌入」中重新启用",
loading: "加载中...",
tabIframe: "iframe",
tabWidget: "浮窗",
tabSecure: "安全模式",
widgetPosition: "浮窗位置",
widgetPreview: "浮窗预览",
positionBottomRight: "右下角",
positionBottomLeft: "左下角",
positionTopRight: "右上角",
positionTopLeft: "左上角",
publishToken: "渠道密钥",
publishTokenHelp: "渠道密钥(em_…)是嵌入渠道的长期密钥,相当于 API Key。创建或重置时只显示一次,需写入第三方网站的浮窗脚本;列表接口不会返回,防止泄露。",
sessionTokenHelp: "访客打开聊天后,iframe 会用渠道密钥换取短期会话凭证(ems_…,约 30 分钟),后续请求使用会话凭证,避免在 URL 中长期暴露渠道密钥。",
rotateTokenHelp: "重置会作废旧渠道密钥,所有已部署的嵌入代码需同步更新,否则第三方站点将无法访问。",
revealToken: "显示",
hideToken: "隐藏",
copyToken: "复制渠道密钥",
tokenCopied: "渠道密钥已复制",
awaitingToken: "等待宿主页面提供 Token…",
preview: "预览",
previewIframeHint: "模拟第三方网站用 iframe 嵌入的效果(与复制代码一致)。",
previewWidgetHint: "模拟第三方网站加载浮窗脚本后的效果;真实站点由宿主页面通过 postMessage 传递 Token。",
previewMockPage: "模拟宿主页面",
previewLoading: "正在加载预览…",
previewUnavailable: "预览暂时不可用,请确认渠道已启用且 Redis 可用",
defaultChatTitle: "AI 助手",
newChat: "新建对话",
channelsPanelIntro: "为 Agent 创建独立的网页嵌入渠道,配置外观与安全策略后部署到您的网站。",
sectionChannel: "渠道信息",
sectionSecurity: "安全与限流",
sectionCapabilities: "对话能力",
allowWebSearch: "显示联网搜索开关",
allowWebSearchDesc: "开启后,访客输入框会显示联网搜索按钮,可自行打开或关闭;不会默认开启。仅当绑定的智能体已启用联网搜索时按钮才会出现。",
allowMemory: "允许记忆",
allowMemoryDesc: "开启后,匿名访客可在同一会话内保留上下文记忆;访客清除浏览器数据或新建对话后记忆会丢失。默认关闭。",
allowFileUpload: "显示文件上传",
allowFileUploadDesc: "开启后,访客可上传图片与文档附件。仅当绑定的智能体已启用图片上传时才会生效。",
webhookUrl: "Webhook 地址",
webhookUrlPlaceholder: "https://your-server.example.com/weknora/embed-events",
webhookUrlDesc: "可选。访客发消息与助手回复完成时,WeKnora 会向该 HTTPS 地址 POST 事件(message_sent / message_received)。",
webhookSecret: "Webhook 签名密钥",
webhookSecretPlaceholder: "用于 HMAC-SHA256 签名(X-WeKnora-Signature)",
webhookSecretKeep: "留空表示不修改已保存的密钥",
webhookSecretDesc: "可选。配置后请求体会带 sha256 签名头,便于你的服务端校验来源。",
secureModeDocHint: "完整集成说明见项目文档 docs/embed-secure-mode.md",
agentWebSearchDisabledHint: "当前智能体未启用联网搜索,访客端不会显示联网按钮。请先在智能体设置中开启联网搜索。",
agentImageUploadDisabledHint: "当前智能体未启用图片上传,访客端不会显示上传按钮。请先在智能体设置中开启图片上传。",
sectionAppearance: "外观与展示",
sectionDeploy: "嵌入到网页",
sectionWebhook: "事件回调",
deployIntro: "保存设置后,按以下两步将聊天嵌入到您的网站。",
deployStepToken: "渠道密钥",
deployStepTokenDesc: "长期密钥(em_…),相当于 API Key。创建或重置时仅在本页显示,请妥善保存。",
deployStepEmbed: "复制嵌入代码",
deployStepEmbedDesc: "选择嵌入方式,将代码粘贴到第三方页面即可。",
embedIframeDesc: "适合在页面固定区域嵌入整页聊天。",
embedWidgetDesc: "适合右下角浮窗,点击图标展开聊天面板。",
embedSecureDesc: "推荐:发布 Token 只保存在你自己的后端,页面只拿到短时令牌,浏览器永远看不到长期密钥。",
deployAfterSaveHint: "保存渠道后,可在此复制渠道密钥与嵌入代码。",
widgetTokenNote: "浮窗脚本需包含渠道密钥;iframe 会在加载时自动完成凭证交换。",
secureTokenNote: "页面不再包含发布 Token,而是指向你后端的取令牌接口(data-token-endpoint)。你的后端用发布 Token 换取 30 分钟的短时令牌返回给页面,浮窗会在到期前自动刷新。",
secureServerLabel: "服务端取令牌接口示例(发布 Token 仅保存在服务端)",
secureServerCode: "服务端示例代码",
tabServerNode: "Node.js",
tabServerGo: "Go",
sectionBasic: "基本设置",
sectionToken: "渠道密钥",
sectionEmbed: "嵌入代码",
enabled: "启用渠道",
deleteConfirm: "确定删除该嵌入渠道?已部署的网站代码将失效。",
rotateConfirmTitle: "确认重置渠道密钥?",
rotateConfirmBody: "重置后旧渠道密钥立即失效,已部署的嵌入代码需同步更新。",
defaultLocale: "默认语言",
defaultLocaleDesc: "访客打开聊天时使用的界面语言;留空则跟随浏览器或宿主页面通过 Widget 设置的 locale。",
defaultLocaleBrowser: "跟随浏览器 / 宿主",
sessionCountLabel: "{n} 个会话",
},
knowledgeEditor: {
titleCreate: "新建知识库",
titleEdit: "知识库设置",
navGroups: {
basic: "基础",
processing: "索引与解析",
data: "存储与数据",
integration: "发布集成",
},
sidebar: {
basic: "基本信息",
models: "模型配置",
@@ -4759,6 +4929,12 @@ export default {
},
agentEditor: {
builtinHint: "这是内置智能体,名称和描述不可修改,但可以调整配置参数",
navGroups: {
basic: "基础",
knowledge: "知识检索",
capability: "能力扩展",
integration: "发布集成",
},
placeholders: {
available: "可用变量:",
clickToInsert: "(点击插入)",
@@ -4773,6 +4949,19 @@ export default {
customized: "已自定义",
empty: "暂无可用的意图模板",
},
promptNav: {
ariaLabel: "提示词目录",
itemCount: "共 {n} 项",
groupCore: "核心提示词",
groupConversation: "对话理解",
groupFallback: "检索兜底",
system: "系统提示词",
context: "上下文模板",
intent: "意图提示词",
rewriteSystem: "改写 · 系统",
rewriteUser: "改写 · 用户",
fallback: "检索兜底",
},
selection: {
all: "全部",
selected: "指定",
@@ -4788,7 +4977,7 @@ export default {
temperature: "控制输出的随机性,0 最确定,1 最随机",
maxTokens: "模型生成回复的最大Token数量",
thinking: "启用模型的扩展思考能力(需要模型支持)",
conversationSection: "配置多轮对话和问题改写相关参数",
conversationSection: "配置多轮对话开关与问题改写开关(改写提示词见「提示词」)",
multiTurn: "开启后将保留历史对话上下文",
historyRounds: "保留最近几轮对话作为上下文",
rewrite: "多轮对话时自动改写用户问题,消解指代和补全省略",
@@ -4803,7 +4992,7 @@ export default {
webSearchMaxResults: "每次搜索返回的最大结果数量",
webFetchEnabled: "Rerank 后自动抓取排名靠前的网页完整内容,提升回答质量",
webFetchTopN: "Rerank 后最多抓取几个网页的完整内容",
retrievalSection: "配置知识库检索和排序的参数",
retrievalSection: "配置知识库检索召回、排序与 FAQ 优先策略(ReRank 模型见「模型配置」)",
queryExpansion: "自动扩展查询词以提高召回率",
embeddingTopK: "向量检索返回的最大结果数量",
keywordThreshold: "关键词检索的最低相关性分数",
@@ -4814,6 +5003,10 @@ export default {
fallbackResponse: "当无法回答时返回的固定文本",
fallbackPrompt: "当无法从知识库找到答案时,引导模型生成回复的提示词",
},
embed: {
title: "网页嵌入",
description: "将智能体嵌入到您的网页,访客可通过页面内聊天窗口或右下角浮窗发起对话,知识库范围跟随本智能体配置。",
},
im: {
title: "IM 集成",
description: "将智能体接入即时通讯平台,支持企业微信、飞书、Slack、Telegram、钉钉、Mattermost和微信",
@@ -4825,6 +5018,8 @@ export default {
mattermost: "Mattermost",
wechat: "微信",
addChannel: "添加渠道",
channelsTitle: "IM 渠道",
disabled: "已停用",
editChannel: "编辑渠道",
deleteConfirm: "确定删除该渠道?删除后无法恢复。",
channelName: "渠道名称",
@@ -4835,7 +5030,7 @@ export default {
outputStream: "流式输出",
outputFull: "完整输出",
callbackUrl: "回调地址",
empty: "暂无 IM 渠道,点击下方按钮添加",
empty: "暂无 IM 渠道",
unnamed: "未命名渠道",
docLink: "查看接入文档",
feishuConsole: "飞书开放平台",
@@ -4968,7 +5163,7 @@ export default {
imageUpload: {
navLabel: "多模态",
sectionTitle: "多模态配置",
sectionDesc: "配置图片上传和视觉语言模型,启用后用户可在对话中上传图片",
sectionDesc: "配置图片/音频上传及对应的 VLM、ASR 模型",
label: "图片上传",
desc: "启用后用户可在对话中上传图片进行多模态问答",
vlmModel: "VLM 模型",
@@ -5059,6 +5254,7 @@ export default {
datasource: {
title: "数据源管理",
description: "配置外部数据源,自动同步内容到知识库",
channelsTitle: "数据源",
add: "添加数据源",
addFirst: "添加第一个数据源",
empty: "暂无数据源",
+1
View File
@@ -51,6 +51,7 @@ const router = createRouter({
component: () => import("../views/auth/Login.vue"),
meta: { requiresAuth: false, requiresInit: false }
},
// Embed chat is a separate entry (embed.html + embed-main.ts), not this SPA.
{
path: "/register",
name: "registerByInvite",
+121
View File
@@ -0,0 +1,121 @@
/** Shared citation tag preprocessing for chat markdown (QA + agent). */
const ATTRIBUTE_REGEX = /([\w-]+)\s*=\s*"([^"]*)"/g
function parseTagAttributes(attrString: string): Record<string, string> {
const attributes: Record<string, string> = {}
if (!attrString) return attributes
ATTRIBUTE_REGEX.lastIndex = 0
let match: RegExpExecArray | null
while ((match = ATTRIBUTE_REGEX.exec(attrString)) !== null) {
attributes[match[1]] = match[2]
}
return attributes
}
function escapeHtml(text: string): string {
return String(text)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
}
function truncateMiddle(text: string, maxLength = 13): string {
if (!text) return ''
if (text.length <= maxLength) return text
const half = Math.floor((maxLength - 3) / 2)
const start = text.slice(0, half + ((maxLength - 3) % 2))
const end = text.slice(-half)
return `${start}...${end}`
}
/** Convert <web/> / <kb/> / [[wiki]] tags into inline citation HTML. */
export function preprocessCitationTags(contentStr: string): string {
if (!contentStr.trim()) return ''
return contentStr
.replace(/<web\b([^>]*)\/>/g, (_m, attrString: string) => {
const attrs = parseTagAttributes(attrString)
const url = attrs.url || ''
const title = attrs.title || ''
if (!url) return ''
let domain = url
try {
const u = new URL(url)
const host = u.hostname || ''
const parts = host.split('.')
domain = parts.length >= 2 ? parts.slice(-2).join('.') : host || url
} catch {
// keep original
}
const safeTitle = escapeHtml(title)
const safeUrl = escapeHtml(url)
return `<a class="citation citation-web" data-url="${safeUrl}" href="${safeUrl}" target="_blank" rel="noopener noreferrer"><span class="citation-icon web"></span><span class="citation-domain">${domain}</span><span class="citation-tip"><span class="tip-title">${safeTitle}</span><span class="tip-url">${safeUrl}</span></span></a>`
})
.replace(/<kb\b([^>]*)\/>/g, (_m, attrString: string) => {
const attrs = parseTagAttributes(attrString)
const doc = attrs.doc || ''
const chunkId = attrs.chunk_id || attrs.chunkId || ''
const kbId = attrs.kb_id || attrs.kbId || ''
if (!doc || !chunkId) return ''
const safeDoc = escapeHtml(doc)
const safeKbId = escapeHtml(kbId)
const safeChunkId = escapeHtml(chunkId)
const displayDoc = escapeHtml(truncateMiddle(doc))
return `<span class="citation citation-kb" data-kb-id="${safeKbId}" data-chunk-id="${safeChunkId}" data-doc="${safeDoc}" role="button" tabindex="0"><span class="citation-icon kb"></span><span class="citation-text">${displayDoc}</span><span class="citation-tip"><span class="tip-loading">…</span></span></span>`
})
.replace(/\[\[([^\]]+)\]\]/g, (match, inner: string) => {
const pipeIdx = inner.indexOf('|')
const slug = pipeIdx > 0 ? inner.substring(0, pipeIdx).trim() : inner.trim()
if (!slug) return match
let display = slug
if (pipeIdx > 0) {
display = inner.substring(pipeIdx + 1).trim()
} else {
const parts = slug.split('/')
display = parts.length > 1 ? parts.slice(1).join('/') : slug
}
return `<a href="#" class="wiki-content-link citation-wiki" data-slug="${escapeHtml(slug)}">${escapeHtml(display)}</a>`
})
}
const HTML_PLACEHOLDER_RE = /@@WEKNORA_HTML_PLACEHOLDER_(\d+)@@/g
/** Protect citation HTML from markdown parser; restore after marked.parse. */
export function extractCitationHtmlPlaceholders(contentStr: string): { content: string; htmlSnippets: string[] } {
const htmlSnippets: string[] = []
const storeHtml = (html: string): string => {
const idx = htmlSnippets.length
htmlSnippets.push(html)
return `@@WEKNORA_HTML_PLACEHOLDER_${idx}@@`
}
const content = contentStr
.replace(/<(?:kb|web)\b[^>]*\/>/g, (match) => storeHtml(preprocessCitationTags(match)))
.replace(/\[\[([^\]]+)\]\]/g, (match) => storeHtml(preprocessCitationTags(match)))
return { content, htmlSnippets }
}
export function restoreCitationHtmlPlaceholders(html: string, htmlSnippets: string[]): string {
if (!htmlSnippets.length) return html
return html.replace(HTML_PLACEHOLDER_RE, (_match, idx) => htmlSnippets[Number(idx)] || '')
}
/** Preserve raw <kb>/<web> tags before sanitizers that would strip them. */
export function preserveCitationTags(contentStr: string): { text: string; tags: string[] } {
const tags: string[] = []
const text = contentStr.replace(/<(?:kb|web)\b[^>]*\/>/g, (match) => {
const idx = tags.length
tags.push(match)
return `\x00TAG${idx}\x00`
})
return { text, tags }
}
export function restoreCitationTags(text: string, tags: string[]): string {
return text.replace(/\x00TAG(\d+)\x00/g, (_, idx) => tags[Number(idx)] || '')
}
+43
View File
@@ -0,0 +1,43 @@
export type AllowedOriginsValidationError =
| { code: 'required' }
| { code: 'wildcard_prod' }
| { code: 'invalid'; origin: string }
/** Mirrors backend validateAllowedOrigins in internal/handler/embed_channel.go */
export function parseAllowedOrigins(text: string): string[] {
return text
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
}
export function validateAllowedOrigins(
origins: string[],
prod = import.meta.env.PROD,
): { ok: true; origins: string[] } | { ok: false; error: AllowedOriginsValidationError } {
const cleaned = parseAllowedOrigins(origins.join('\n'))
if (cleaned.length === 0) {
return { ok: false, error: { code: 'required' } }
}
for (const origin of cleaned) {
if (origin === '*') {
if (prod) {
return { ok: false, error: { code: 'wildcard_prod' } }
}
continue
}
let host = origin
if (origin.startsWith('*.')) {
host = `https://${origin.slice(2)}`
}
try {
const url = new URL(host)
if ((url.protocol !== 'http:' && url.protocol !== 'https:') || !url.host) {
return { ok: false, error: { code: 'invalid', origin } }
}
} catch {
return { ok: false, error: { code: 'invalid', origin } }
}
}
return { ok: true, origins: cleaned }
}
+24
View File
@@ -0,0 +1,24 @@
/** Resolve the public origin used in embed iframe / widget URLs. */
export function resolveEmbedBaseUrl(): string {
if (typeof window === 'undefined') return ''
const runtime = (window as Window & { __RUNTIME_CONFIG__?: { EMBED_BASE_URL?: string } }).__RUNTIME_CONFIG__
const fromRuntime = runtime?.EMBED_BASE_URL?.trim()
if (fromRuntime) {
try {
const u = new URL(fromRuntime, window.location.href)
if (u.protocol === 'http:' || u.protocol === 'https:') return u.origin
} catch {
// fall through
}
}
const fromEnv = import.meta.env.VITE_EMBED_BASE_URL?.trim()
if (fromEnv) {
try {
const u = new URL(fromEnv, window.location.href)
if (u.protocol === 'http:' || u.protocol === 'https:') return u.origin
} catch {
// fall through
}
}
return window.location.origin
}
+12
View File
@@ -0,0 +1,12 @@
/** Prefix host-injected context onto the user query for embed chat. */
export function buildQueryWithHostContext(
query: string,
hostContext?: Record<string, unknown>,
): string {
if (!hostContext || !Object.keys(hostContext).length) return query
const lines = Object.entries(hostContext)
.filter(([, v]) => v !== undefined && v !== null && v !== '')
.map(([k, v]) => `${k}: ${typeof v === 'string' ? v : JSON.stringify(v)}`)
if (!lines.length) return query
return `[Host context]\n${lines.join('\n')}\n\n${query}`
}
+14
View File
@@ -0,0 +1,14 @@
export function isEmbedImageFile(file: File): boolean {
if (file.type.startsWith('image/')) return true
const name = file.name.toLowerCase()
return ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'].some((ext) => name.endsWith(ext))
}
export function fileToDataURI(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => resolve(String(reader.result || ''))
reader.onerror = reject
reader.readAsDataURL(file)
})
}
+25
View File
@@ -0,0 +1,25 @@
/** Lightweight toast for embed bundle (no TDesign). */
export function embedToast(message: string, type: 'error' | 'info' = 'error') {
if (!message || typeof document === 'undefined') return
const el = document.createElement('div')
el.textContent = message
el.setAttribute('role', 'alert')
Object.assign(el.style, {
position: 'fixed',
left: '50%',
top: '16px',
transform: 'translateX(-50%)',
zIndex: '2147483647',
maxWidth: 'min(90vw, 420px)',
padding: '10px 14px',
borderRadius: '8px',
fontSize: '14px',
lineHeight: '1.4',
boxShadow: '0 4px 16px rgba(0,0,0,.12)',
background: type === 'error' ? '#fff1f0' : '#f6ffed',
color: type === 'error' ? '#cf1322' : '#389e0d',
border: `1px solid ${type === 'error' ? '#ffccc7' : '#b7eb8f'}`,
})
document.body.appendChild(el)
window.setTimeout(() => el.remove(), 4000)
}
+87 -50
View File
@@ -1,12 +1,11 @@
import mermaid from 'mermaid';
import type {Tokens} from 'marked';
import {openMermaidFullscreen} from "@/utils/mermaidViewer.ts";
import hljs from "highlight.js";
import "highlight.js/styles/github.css";
import type { Tokens } from 'marked'
import { openMermaidFullscreen } from '@/utils/mermaidViewer.ts'
hljs.registerAliases("mermaid", { languageName: "plaintext" });
let mermaidInitialized = false;
let mermaidMod: typeof import('mermaid') | null = null
let hljsMod: typeof import('highlight.js') | null = null
let mermaidInitialized = false
let initPromise: Promise<void> | null = null
let hljsPromise: Promise<typeof import('highlight.js').default> | null = null
const MERMAID_CONFIG = {
startOnLoad: false,
@@ -34,63 +33,101 @@ const MERMAID_CONFIG = {
barGap: 4,
topPadding: 50,
},
};
}
async function getMermaid() {
if (!mermaidMod) {
mermaidMod = await import('mermaid')
}
return mermaidMod.default
}
async function getHljs() {
if (!hljsMod) {
hljsMod = await import('highlight.js')
await import('highlight.js/styles/github.css')
hljsMod.default.registerAliases('mermaid', { languageName: 'plaintext' })
}
return hljsMod.default
}
function escapeHtml(text: string) {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
}
export const ensureMermaidInitialized = () => {
if (mermaidInitialized) return;
mermaid.initialize(MERMAID_CONFIG as any);
mermaidInitialized = true;
};
if (!initPromise) {
initPromise = (async () => {
const mermaid = await getMermaid()
if (!mermaidInitialized) {
mermaid.initialize(MERMAID_CONFIG as Parameters<typeof mermaid.initialize>[0])
mermaidInitialized = true
}
})()
}
}
let mermaidCount = 0;
let mermaidCount = 0
export const createMermaidCodeRenderer = (idPrefix: string) => {
return ({text, lang}: Tokens.Code) => {
let highlighted = '';
let highlightLang: string = lang || 'Code';
if (highlightLang && hljs.getLanguage(highlightLang)) {
if (!hljsPromise) {
hljsPromise = getHljs()
}
return ({ text, lang }: Tokens.Code) => {
let highlighted = escapeHtml(text)
let highlightLang: string = lang || 'Code'
const hljs = hljsMod?.default
if (hljs) {
if (highlightLang && hljs.getLanguage(highlightLang)) {
try {
highlighted = hljs.highlight(text, { language: lang }).value;
highlighted = hljs.highlight(text, { language: highlightLang }).value
} catch {
let ret = hljs.highlightAuto(text);
highlighted = ret.value;
highlightLang = ret.language || "Code";
const ret = hljs.highlightAuto(text)
highlighted = ret.value
highlightLang = ret.language || 'Code'
}
} else {
let ret = hljs.highlightAuto(text);
highlighted = ret.value;
highlightLang = ret.language || "Code";
} else {
const ret = hljs.highlightAuto(text)
highlighted = ret.value
highlightLang = ret.language || 'Code'
}
}
if (lang === 'mermaid') {
const id = `${idPrefix}-${++mermaidCount}`;
return `<pre id="${id}" data-mermaid="false"><code class="hljs language-${highlightLang}">${highlighted}</code></pre>`;
const id = `${idPrefix}-${++mermaidCount}`
return `<pre id="${id}" data-mermaid="false"><code class="hljs language-${highlightLang}">${highlighted}</code></pre>`
}
return `<pre><code class="hljs language-${highlightLang}">${highlighted}</code></pre>`;
};
};
return `<pre><code class="hljs language-${highlightLang}">${highlighted}</code></pre>`
}
}
export const renderMermaidInContainer = async (
rootElement: HTMLElement | null | undefined,
) => {
if (!rootElement) return 0;
const mermaidElements = rootElement.querySelectorAll<HTMLElement>('pre[data-mermaid="false"]');
if (!rootElement) return
const mermaid = await getMermaid()
ensureMermaidInitialized()
await initPromise
const mermaidElements = rootElement.querySelectorAll<HTMLElement>('pre[data-mermaid="false"]')
for (const el of mermaidElements) {
try{
const code = el.innerText;
// 验证
await mermaid.parse(code);
// 渲染
let {svg} = await mermaid.render(`${el.id}-svg`, code);
el.classList.add('mermaid')
el.innerHTML = svg;
el.onclick = (event) => {
event.stopPropagation();
openMermaidFullscreen(svg);
};
} catch(e){
console.error("Mermaid rendering error:", e);
try {
const code = el.innerText
await mermaid.parse(code)
const { svg } = await mermaid.render(`${el.id}-svg`, code)
el.classList.add('mermaid')
el.innerHTML = svg
el.onclick = (event) => {
event.stopPropagation()
openMermaidFullscreen(svg)
}
} catch (e) {
console.error('Mermaid rendering error:', e)
}
// 标记为已渲染
el.setAttribute('data-mermaid', 'true');
el.setAttribute('data-mermaid', 'true')
}
};
}
+37 -10
View File
@@ -28,10 +28,16 @@ function getCurrentLanguage(): string {
instance.interceptors.request.use(
(config) => {
// 添加JWT token认证
const token = localStorage.getItem('weknora_token');
if (token) {
config.headers["Authorization"] = `Bearer ${token}`;
const existingAuth = config.headers?.Authorization ?? config.headers?.authorization;
const isEmbedAuth = typeof existingAuth === 'string' && existingAuth.startsWith('Embed ');
const isEmbedPath = typeof config.url === 'string' && config.url.includes('/api/v1/embed/');
// 嵌入渠道使用 Embed token;勿用本地 JWT 覆盖(否则调试页会 401)
if (!isEmbedAuth) {
const token = localStorage.getItem('weknora_token');
if (token) {
config.headers["Authorization"] = `Bearer ${token}`;
}
}
// 添加用户语言偏好
@@ -46,9 +52,11 @@ instance.interceptors.request.use(
// 换之后只有第一批请求带 X-Tenant-ID"调成永久状态。
// 后端 IsTenantAccessible 已经允许 header 指向 home 租户(自家),
// 所以无脑附不会引入新风险。
const selectedTenantId = localStorage.getItem('weknora_selected_tenant_id');
if (selectedTenantId) {
config.headers["X-Tenant-ID"] = selectedTenantId;
if (!isEmbedAuth && !isEmbedPath) {
const selectedTenantId = localStorage.getItem('weknora_selected_tenant_id');
if (selectedTenantId) {
config.headers["X-Tenant-ID"] = selectedTenantId;
}
}
config.headers["X-Request-ID"] = `${generateRandomString(12)}`;
@@ -68,7 +76,7 @@ let failedQueue: Array<{ resolve: Function; reject: Function }> = [];
// must surface to the page (e.g. expired token), not trigger the
// refresh-then-redirect-to-login flow (issue #1617). '/auth/register' already
// covers '/auth/register-by-invite' via substring match.
const PUBLIC_AUTH_PATHS = ['/auth/auto-setup', '/auth/login', '/auth/register', '/auth/oidc/', '/auth/invitations/lookup'];
const PUBLIC_AUTH_PATHS = ['/auth/auto-setup', '/auth/login', '/auth/register', '/auth/oidc/', '/auth/invitations/lookup', '/api/v1/embed/'];
function isPublicAuthRequest(url?: string): boolean {
if (!url) return false;
@@ -88,9 +96,16 @@ const processQueue = (error: any, token: string | null = null) => {
failedQueue = [];
};
function isEmbedPage(): boolean {
if (typeof window === 'undefined') return false;
return window.location.pathname.startsWith('/embed/');
}
function redirectToLogin() {
if (typeof window === 'undefined') return;
if (window.location.pathname === '/login') return;
// Embed 渠道用 Embed token 鉴权,匿名访问不应被踢到登录页
if (isEmbedPage()) return;
window.location.href = '/login';
}
@@ -112,9 +127,21 @@ instance.interceptors.response.use(
}
// 公开接口(auto-setup / login / register / oidc)的 401 不走 refresh 逻辑,直接返回错误
if (error.response.status === 401 && isPublicAuthRequest(originalRequest?.url)) {
if ((error.response.status === 401 || error.response.status === 403) && isPublicAuthRequest(originalRequest?.url)) {
const { status, data } = error.response;
return Promise.reject({ status, message: (typeof data === 'object' ? (data?.error?.message || data?.message) : data) || t('error.invalidCredentials') });
const msg = typeof data === 'object'
? (typeof data?.error === 'string' ? data.error : (data?.error?.message || data?.message))
: data;
return Promise.reject({ status, message: msg || t('error.invalidCredentials') });
}
// Embed 调试页/挂件:无 JWT 时直接拒绝,勿走 refresh → /login
if (error.response.status === 401 && isEmbedPage()) {
const { status, data } = error.response;
const msg = typeof data === 'object'
? (typeof data?.error === 'string' ? data.error : (data?.error?.message || data?.message))
: data;
return Promise.reject({ status, message: msg || t('error.invalidCredentials') });
}
// 如果是401错误且不是刷新token的请求,尝试刷新token
+18 -4
View File
@@ -312,7 +312,10 @@ export function clearProtectedFileFailureCache(): void {
protectedFileFailureCache.clear();
}
export async function hydrateProtectedFileImages(root: ParentNode | null | undefined): Promise<void> {
export async function hydrateProtectedFileImages(
root: ParentNode | null | undefined,
embed?: { channelId: string; token: string },
): Promise<void> {
if (!root || typeof window === 'undefined') {
return;
}
@@ -324,7 +327,11 @@ export async function hydrateProtectedFileImages(root: ParentNode | null | undef
return;
}
const headers = getProtectedFileRequestHeaders();
// Embed visitors carry no Bearer/tenant context; route through the
// embed-scoped file proxy (auth via the Embed header, tenant from the channel).
const headers = embed
? { Authorization: `Embed ${embed.token}` }
: getProtectedFileRequestHeaders();
await Promise.all(Array.from(images).map(async (img) => {
const protectedSrc = (img.getAttribute('data-protected-src') || '').trim();
@@ -339,11 +346,18 @@ export async function hydrateProtectedFileImages(root: ParentNode | null | undef
img.dataset.authHydrated = '1';
const isProviderScheme = /^(local|minio|cos|tos|s3|oss|ks3|obs):\/\//.test(sourceURL);
const fileProxyBase = embed
? `/api/v1/embed/${embed.channelId}/files`
: '/files';
const requestURL = isProviderScheme
? `/files?${new URLSearchParams({ file_path: sourceURL }).toString()}`
? `${fileProxyBase}?${new URLSearchParams({ file_path: sourceURL }).toString()}`
: sourceURL;
if (!requestURL.startsWith('/files?') || !requestURL.includes('file_path=')) {
const isProxyRequest =
requestURL.includes('file_path=') &&
(requestURL.startsWith('/files?') ||
/^\/api\/v1\/embed\/[^/]+\/files\?/.test(requestURL));
if (!isProxyRequest) {
img.dataset.authHydrated = '0';
return;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,507 @@
<template>
<div class="embed-bot-msg" :class="{ 'is-embedded': embeddedMode }">
<DocInfo
v-if="session && !session.isAgentMode"
:session="session"
embedded-mode
/>
<AgentStreamDisplay
v-if="session?.isAgentMode"
:session="session"
:session-id="sessionId"
:user-query="userQuery"
:embedded-mode="embeddedMode"
:embed-channel-id="embedChannelId"
:embed-token="embedToken"
/>
<template v-else-if="!session?.isAgentMode">
<DeepThink v-if="session?.showThink" :deep-session="session" />
<div v-if="!session?.hideContent" ref="parentMd">
<div v-if="hasActualContent" class="content-wrapper">
<div class="ai-markdown-template markdown-content" v-html="renderedHTML" />
</div>
<div v-if="hasActualContent && !session?.is_completed" class="loading-indicator">
<div class="loading-typing">
<span></span>
<span></span>
<span></span>
</div>
</div>
</div>
</template>
<Teleport to="body">
<div
v-if="citationFloat.visible"
class="embed-citation-float"
:style="{ top: `${citationFloat.top}px`, left: `${citationFloat.left}px` }"
@mouseenter="cancelCitationClose"
@mouseleave="scheduleCitationClose"
>
<template v-if="citationFloat.type === 'web'">
<div class="embed-citation-float__title">{{ citationFloat.title || citationFloat.url }}</div>
<a
v-if="citationFloat.url"
class="embed-citation-float__link"
:href="citationFloat.url"
target="_blank"
rel="noopener noreferrer"
>{{ citationFloat.url }}</a>
</template>
<template v-else>
<div class="embed-citation-float__title">{{ citationFloat.title }}</div>
<div v-if="citationFloat.loading" class="embed-citation-float__muted">…</div>
<div v-else-if="citationFloat.error" class="embed-citation-float__error">{{ citationFloat.error }}</div>
<div v-else class="embed-citation-float__body">{{ citationFloat.content }}</div>
</template>
</div>
</Teleport>
</div>
</template>
<script setup lang="ts">
import { computed, defineAsyncComponent, nextTick, onMounted, onUpdated, ref, watch } from 'vue'
import { marked } from 'marked'
import markedKatex from 'marked-katex-extension'
import 'katex/dist/katex.min.css'
import {
sanitizeHTML,
safeMarkdownToHTML,
createSafeImage,
isValidImageURL,
hydrateProtectedFileImages,
} from '@/utils/security'
import { replaceIncompleteImageWithPlaceholder } from '@/utils/chatMessageShared'
import {
createMermaidCodeRenderer,
ensureMermaidInitialized,
renderMermaidInContainer,
} from '@/utils/mermaidShared'
import {
extractCitationHtmlPlaceholders,
preserveCitationTags,
restoreCitationHtmlPlaceholders,
restoreCitationTags,
} from '@/utils/citationMarkdown'
import { useEmbedCitationPopover } from '@/composables/useEmbedCitationPopover'
const AgentStreamDisplay = defineAsyncComponent(
() => import('@/views/chat/components/AgentStreamDisplay.vue'),
)
const DocInfo = defineAsyncComponent(
() => import('@/views/chat/components/docInfo.vue'),
)
const DeepThink = defineAsyncComponent(
() => import('@/views/chat/components/deepThink.vue'),
)
marked.use({ breaks: true })
marked.use(markedKatex({ throwOnError: false, nonStandard: true }))
ensureMermaidInitialized()
const preprocessMathDelimiters = (rawText: string): string => {
if (!rawText || typeof rawText !== 'string') return ''
return rawText
.replace(/\\\[([\s\S]*?)\\\]/g, '$$$$$1$$$$')
.replace(/\\\(([\s\S]*?)\\\)/g, '$$$1$$')
}
const customRenderer = new marked.Renderer()
customRenderer.image = function ({ href, title, text }) {
if (!isValidImageURL(href)) return ''
return createSafeImage(href, text || '', title || '')
}
customRenderer.code = createMermaidCodeRenderer('mermaid-embed-botmsg')
const props = withDefaults(
defineProps<{
content?: string
session?: Record<string, unknown>
sessionId?: string
userQuery?: string
embeddedMode?: boolean
embedChannelId?: string
embedToken?: string
}>(),
{
content: '',
session: () => ({}),
sessionId: '',
userQuery: '',
embeddedMode: true,
embedChannelId: '',
embedToken: '',
},
)
const parentMd = ref<HTMLElement | null>(null)
const embedChannelIdRef = computed(() => props.embedChannelId)
const embedTokenRef = computed(() => props.embedToken)
const { float: citationFloat, rebind: rebindCitations } = useEmbedCitationPopover(
parentMd,
embedChannelIdRef,
embedTokenRef,
)
let citationCloseTimer: number | null = null
const cancelCitationClose = () => {
if (citationCloseTimer) {
window.clearTimeout(citationCloseTimer)
citationCloseTimer = null
}
}
const scheduleCitationClose = () => {
cancelCitationClose()
citationCloseTimer = window.setTimeout(() => {
citationFloat.value.visible = false
}, 120)
}
const renderedHTML = computed(() => {
const text = String(props.content || props.session?.content || '')
if (!text.trim()) return ''
const { text: tagSafe, tags } = preserveCitationTags(text)
const processed = replaceIncompleteImageWithPlaceholder(tagSafe)
const mathSafe = preprocessMathDelimiters(processed)
const restoredTags = restoreCitationTags(mathSafe, tags)
const safeMarkdown = safeMarkdownToHTML(restoredTags)
const { content: mdWithPlaceholders, htmlSnippets } = extractCitationHtmlPlaceholders(safeMarkdown)
const html = marked.parse(mdWithPlaceholders, { renderer: customRenderer, breaks: true }) as string
const withCitations = restoreCitationHtmlPlaceholders(html, htmlSnippets)
return sanitizeHTML(withCitations)
})
const hasActualContent = computed(() => {
const text = String(props.content || props.session?.content || '')
return text.trim().length > 0
})
const hydrateImages = async () => {
const embedCtx =
props.embedChannelId && props.embedToken
? { channelId: props.embedChannelId, token: props.embedToken }
: undefined
await hydrateProtectedFileImages(parentMd.value, embedCtx)
}
const renderMermaidDiagrams = async () => {
await renderMermaidInContainer(parentMd.value)
}
watch(renderedHTML, () => {
nextTick(async () => {
rebindCitations()
await hydrateImages()
if (props.session?.is_completed) {
await renderMermaidDiagrams()
}
})
})
onUpdated(() => {
nextTick(async () => {
await hydrateImages()
if (props.session?.is_completed) {
await renderMermaidDiagrams()
}
})
})
onMounted(() => {
nextTick(async () => {
await hydrateImages()
await renderMermaidDiagrams()
})
})
</script>
<style scoped lang="less">
@import '../../components/css/markdown.less';
.embed-bot-msg {
border-radius: 4px;
color: var(--td-text-color-primary);
font-size: 16px;
margin-right: auto;
max-width: 100%;
box-sizing: border-box;
&.is-embedded {
width: 100%;
:deep(.agent-stream-display) {
width: 100%;
}
}
}
.content-wrapper {
background: var(--td-bg-color-container);
border-radius: 6px;
padding: 8px 0;
}
.ai-markdown-template {
font-size: 15px;
color: var(--td-text-color-primary);
line-height: 1.6;
}
.markdown-content {
:deep(p) {
margin: 6px 0;
line-height: 1.6;
}
:deep(code) {
background: var(--td-bg-color-secondarycontainer);
padding: 2px 5px;
border-radius: 3px;
font-family: var(--app-font-family-mono);
font-size: 11px;
}
:deep(pre) {
background: var(--td-bg-color-secondarycontainer);
padding: 10px;
border-radius: 4px;
overflow-x: auto;
margin: 6px 0;
code {
background: none;
padding: 0;
}
}
:deep(ul),
:deep(ol) {
margin: 6px 0;
padding-left: 20px;
}
:deep(li) {
margin: 3px 0;
}
:deep(blockquote) {
border-left: 2px solid var(--td-brand-color);
padding-left: 10px;
margin: 6px 0;
color: var(--td-text-color-secondary);
}
:deep(h1),
:deep(h2),
:deep(h3),
:deep(h4),
:deep(h5),
:deep(h6) {
margin: 10px 0 6px;
font-weight: 600;
color: var(--td-text-color-primary);
}
:deep(a) {
color: var(--td-brand-color);
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
:deep(table) {
border-collapse: collapse;
margin: 6px 0;
font-size: 11px;
width: 100%;
th,
td {
border: 1px solid var(--td-component-stroke);
padding: 5px 8px;
text-align: left;
}
th {
background: var(--td-bg-color-secondarycontainer);
font-weight: 600;
}
tbody tr:nth-child(even) {
background: var(--td-bg-color-secondarycontainer);
}
}
:deep(img) {
max-width: 80%;
max-height: 300px;
width: auto;
height: auto;
border-radius: 8px;
display: block;
margin: 8px 0;
border: 0.5px solid var(--td-component-stroke);
object-fit: contain;
}
:deep(.mermaid) {
margin: 16px 0;
padding: 16px;
background: var(--td-bg-color-secondarycontainer);
border-radius: 8px;
overflow-x: auto;
text-align: center;
svg {
max-width: 100%;
height: auto;
}
}
}
.loading-indicator {
padding: 8px 0;
}
.loading-typing {
display: flex;
align-items: center;
gap: 4px;
span {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--embed-primary, var(--td-brand-color));
animation: typingBounce 1.4s ease-in-out infinite;
&:nth-child(1) {
animation-delay: 0s;
}
&:nth-child(2) {
animation-delay: 0.2s;
}
&:nth-child(3) {
animation-delay: 0.4s;
}
}
}
@keyframes typingBounce {
0%,
60%,
100% {
transform: translateY(0);
}
30% {
transform: translateY(-8px);
}
}
.markdown-content {
:deep(.citation) {
display: inline-flex;
align-items: center;
gap: 4px;
border-radius: 10px;
padding: 2px 4px;
font-size: 11px;
line-height: 1.4;
margin: 0 4px;
}
:deep(.citation-web),
:deep(.citation-kb) {
background: color-mix(in srgb, var(--td-brand-color) 8%, transparent);
color: var(--td-brand-color);
border: 1px solid color-mix(in srgb, var(--td-brand-color) 20%, transparent);
cursor: pointer;
white-space: nowrap;
}
:deep(.citation-web:hover),
:deep(.citation-kb:hover) {
background: color-mix(in srgb, var(--td-brand-color) 12%, transparent);
border-color: var(--td-brand-color);
}
:deep(.citation .citation-icon) {
display: inline-block;
width: 14px;
height: 14px;
background-color: var(--embed-primary, var(--td-brand-color));
mask-size: contain;
mask-repeat: no-repeat;
mask-position: center;
-webkit-mask-size: contain;
-webkit-mask-repeat: no-repeat;
-webkit-mask-position: center;
flex-shrink: 0;
}
:deep(.citation .citation-icon.web) {
mask-image: url('@/assets/img/websearch-globe.svg');
-webkit-mask-image: url('@/assets/img/websearch-globe.svg');
}
:deep(.citation .citation-icon.kb) {
mask-image: url('@/assets/img/zhishiku.svg');
-webkit-mask-image: url('@/assets/img/zhishiku.svg');
}
:deep(.citation-tip) {
display: none;
}
:deep(a.wiki-content-link) {
color: var(--td-brand-color);
border-bottom: 1px dashed var(--td-brand-color);
text-decoration: none;
font-weight: 500;
}
}
.embed-citation-float {
position: absolute;
z-index: 10000;
max-width: 320px;
padding: 10px 12px;
border-radius: 8px;
background: var(--td-bg-color-container);
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.18);
font-size: 12px;
line-height: 1.5;
color: var(--td-text-color-primary);
&__title {
font-weight: 600;
color: var(--td-brand-color);
margin-bottom: 4px;
}
&__link {
color: var(--td-brand-color);
word-break: break-all;
}
&__body {
max-height: 200px;
overflow-y: auto;
white-space: pre-wrap;
}
&__muted {
color: var(--td-text-color-placeholder);
}
&__error {
color: var(--td-error-color);
}
}
</style>
+490
View File
@@ -0,0 +1,490 @@
<template>
<div class="embed-chat">
<div ref="scrollContainer" class="embed-chat__scroll" @scroll="handleScroll">
<div class="embed-chat__messages">
<div v-if="historyLoading && messagesList.length === 0 && !hasWelcomeText" class="msg-skeleton-list">
<div class="msg-skeleton msg-skeleton-user"><div class="sk-line sk-line--short" /></div>
<div class="msg-skeleton msg-skeleton-bot">
<div class="sk-line" />
<div class="sk-line" />
<div class="sk-line sk-line--medium" />
</div>
</div>
<div
v-if="showWelcome"
class="embed-welcome-bubble"
>
<p class="embed-welcome-bubble__text">{{ welcomeText }}</p>
</div>
<div
v-if="showSuggestedBlock"
class="embed-suggested"
>
<p v-if="suggestedQuestions.length > 0" class="embed-suggested__title">
{{ t('chat.suggestedQuestions') }}
</p>
<div v-if="suggestedLoading && suggestedQuestions.length === 0" class="embed-suggested__grid">
<div v-for="n in 4" :key="`sq-skel-${n}`" class="embed-suggested__card embed-suggested__card--skeleton" />
</div>
<div v-else-if="suggestedQuestions.length > 0" class="embed-suggested__grid">
<button
v-for="item in suggestedQuestions"
:key="item.question"
type="button"
class="embed-suggested__card"
@click="handleSuggestedClick(item.question)"
>
<span class="embed-suggested__text">{{ item.question }}</span>
</button>
</div>
</div>
<div
v-for="(session, index) in messagesList"
:key="(session.id as string) || `${session.role}-${session.created_at}-${index}`"
class="msg-item-wrapper"
>
<div v-if="session.role === 'user'">
<EmbedUserMessage
:content="String(session.content || '')"
:mentioned_items="session.mentioned_items"
:images="session.images"
:attachments="session.attachments"
:embeddedMode="true"
:embed-channel-id="channelId"
:embed-token="token"
/>
</div>
<div v-if="session.role === 'assistant' && shouldRenderAssistantMessage(session)">
<EmbedBotMessage
:content="String(session.content || '')"
:session="session"
:session-id="sessionId"
:user-query="getUserQuery(index)"
:embedded-mode="true"
:embed-channel-id="channelId"
:embed-token="token"
/>
</div>
</div>
<div v-if="loading" class="embed-chat__typing">
<div class="loading-typing">
<span></span>
<span></span>
<span></span>
</div>
</div>
</div>
</div>
<transition name="scroll-btn-fade">
<div v-show="userHasScrolledUp" class="scroll-to-bottom-btn" @click="onClickScrollToBottom" aria-label="scroll to bottom">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" aria-hidden="true">
<path d="M6 9l6 6 6-6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
</svg>
</div>
</transition>
<div class="embed-chat__input">
<EmbedInputField
:isReplying="isReplying"
:show-web-search-toggle="showWebSearchToggle"
v-model:web-search-enabled="webSearchEnabled"
:show-file-upload-toggle="showFileUploadToggle"
@send-msg="onSendMsg"
@stop-generation="handleStopGeneration"
/>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, toRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { getEmbedSuggestedQuestions, onEmbedHostOpenWithQuery, type SuggestedQuestion } from '@/api/embed'
import EmbedInputField from '@/components/EmbedInputField.vue'
import EmbedBotMessage from '@/views/embed/EmbedBotMessage.vue'
import EmbedUserMessage from '@/views/embed/EmbedUserMessage.vue'
import { useEmbedChatSession } from '@/composables/useEmbedChatSession'
const props = defineProps<{
sessionId: string
sessionSig: string
channelId: string
token: string
agentId: string
kbIds: string[]
welcomeMessage?: string
showSuggestedQuestions?: boolean
allowWebSearch?: boolean
agentWebSearchEnabled?: boolean
allowFileUpload?: boolean
agentImageUploadEnabled?: boolean
useSessionHeaderTitle?: boolean
hostContext?: Record<string, unknown>
}>()
const emit = defineEmits<{
(e: 'session-title', title: string): void
(e: 'messages-state', hasMessages: boolean): void
}>()
const { t } = useI18n()
const sessionIdRef = toRef(props, 'sessionId')
const sessionSigRef = toRef(props, 'sessionSig')
const suggestedQuestions = ref<SuggestedQuestion[]>([])
const suggestedLoading = ref(false)
const hostContextRef = ref<Record<string, unknown>>(props.hostContext || {})
const embedWebSearchStorageKey = () => `weknora-embed-web-search:${props.channelId}`
const readStoredWebSearchEnabled = () => {
if (typeof localStorage === 'undefined') return false
return localStorage.getItem(embedWebSearchStorageKey()) === '1'
}
const webSearchEnabled = ref(readStoredWebSearchEnabled())
const showWebSearchToggle = computed(
() => props.allowWebSearch === true && props.agentWebSearchEnabled === true,
)
const showFileUploadToggle = computed(
() => props.allowFileUpload === true && props.agentImageUploadEnabled === true,
)
watch(webSearchEnabled, (enabled) => {
if (!showWebSearchToggle.value) return
if (typeof localStorage === 'undefined') return
localStorage.setItem(embedWebSearchStorageKey(), enabled ? '1' : '0')
})
watch(showWebSearchToggle, (visible) => {
if (!visible) {
webSearchEnabled.value = false
}
})
watch(() => props.hostContext, (ctx) => {
hostContextRef.value = ctx || {}
}, { deep: true })
const {
messagesList,
loading,
isReplying,
historyLoading,
scrollContainer,
userHasScrolledUp,
shouldRenderAssistantMessage,
getUserQuery,
handleScroll,
scrollToBottom,
onClickScrollToBottom,
sendMsg,
handleStopGeneration,
} = useEmbedChatSession({
sessionId: sessionIdRef,
sessionSig: sessionSigRef,
channelId: props.channelId,
token: props.token,
agentId: props.agentId,
kbIds: props.kbIds,
allowWebSearch: props.allowWebSearch,
allowFileUpload: props.allowFileUpload,
hostContext: hostContextRef,
onMessagesChange: (has) => emit('messages-state', has),
onSessionTitle: (title) => {
if (props.useSessionHeaderTitle) {
emit('session-title', title)
}
},
})
const welcomeText = computed(() => props.welcomeMessage?.trim() || '')
const hasWelcomeText = computed(() => welcomeText.value.length > 0)
const hasUserMessage = computed(() =>
messagesList.some((m) => m.role === 'user'))
/** 访客未发言前始终展示欢迎语(含历史加载中),发送后隐藏 */
const showWelcome = computed(() => hasWelcomeText.value && !hasUserMessage.value)
const showSuggestedBlock = computed(() =>
props.showSuggestedQuestions
&& !hasUserMessage.value
&& !loading.value
&& !historyLoading.value
&& (suggestedLoading.value || suggestedQuestions.value.length > 0))
const fetchSuggestedQuestions = async () => {
if (!props.showSuggestedQuestions || !props.channelId || !props.token) {
suggestedQuestions.value = []
return
}
suggestedLoading.value = true
try {
const res = await getEmbedSuggestedQuestions(props.channelId, props.token, 6)
suggestedQuestions.value = res?.data?.questions || []
} catch {
suggestedQuestions.value = []
} finally {
suggestedLoading.value = false
}
}
const onSendMsg = (query: string, imageFiles: File[] = [], attachmentFiles: File[] = []) => {
void sendMsg(query, {
webSearchEnabled: webSearchEnabled.value,
imageFiles,
attachmentFiles,
})
}
const handleSuggestedClick = (question: string) => {
const text = question.trim()
if (!text || isReplying.value) return
void sendMsg(text, { webSearchEnabled: webSearchEnabled.value })
}
let removeOpenQueryListener: (() => void) | null = null
onMounted(() => {
fetchSuggestedQuestions()
removeOpenQueryListener = onEmbedHostOpenWithQuery((query) => {
if (isReplying.value) return
void sendMsg(query, { webSearchEnabled: webSearchEnabled.value })
})
})
onUnmounted(() => {
removeOpenQueryListener?.()
})
watch(
() => [props.showSuggestedQuestions, props.channelId, props.token] as const,
() => { fetchSuggestedQuestions() },
)
</script>
<style scoped lang="less">
.embed-chat {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
width: 100%;
position: relative;
}
.embed-chat__scroll {
flex: 1;
min-height: 0;
width: 100%;
overflow-y: auto;
}
.embed-chat__messages {
display: flex;
flex-direction: column;
gap: 16px;
max-width: 800px;
margin: 0 auto;
width: 100%;
padding: 12px 16px 0;
box-sizing: border-box;
}
.embed-suggested {
width: 100%;
&__title {
margin: 0 0 8px;
font-size: 13px;
font-weight: 500;
color: var(--td-text-color-secondary);
}
&__grid {
display: flex;
flex-direction: column;
gap: 8px;
}
&__card {
display: block;
width: 100%;
padding: 10px 12px;
border: 1px solid var(--td-component-stroke);
border-radius: 10px;
background: var(--td-bg-color-container);
text-align: left;
cursor: pointer;
transition: border-color 0.15s ease, background 0.15s ease;
&:hover {
border-color: var(--td-brand-color-3, var(--td-brand-color));
background: color-mix(in srgb, var(--td-brand-color) 4%, var(--td-bg-color-container));
}
&--skeleton {
height: 40px;
cursor: default;
background: linear-gradient(90deg, #f0f0f0 25%, #e6e6e6 50%, #f0f0f0 75%);
background-size: 200% 100%;
animation: sk-shimmer 1.2s ease-in-out infinite;
border: none;
}
}
&__text {
font-size: 13px;
line-height: 1.45;
color: var(--td-text-color-primary);
}
}
.embed-welcome-bubble {
display: flex;
justify-content: flex-start;
width: 100%;
animation: welcome-in 0.28s ease both;
&__text {
margin: 0;
max-width: min(88%, 520px);
padding: 10px 14px;
font-size: 14px;
line-height: 1.55;
color: var(--td-text-color-primary);
white-space: pre-wrap;
word-break: break-word;
background: color-mix(
in srgb,
var(--embed-primary, var(--td-brand-color)) 7%,
var(--td-bg-color-container, #fff)
);
border: 1px solid color-mix(
in srgb,
var(--embed-primary, var(--td-brand-color)) 14%,
var(--td-component-stroke, #e7e7e7)
);
border-radius: 4px 14px 14px 14px;
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
}
}
@keyframes welcome-in {
from {
opacity: 0;
transform: translateY(6px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.embed-chat__typing {
height: 41px;
display: flex;
align-items: center;
padding-left: 4px;
}
.embed-chat__input {
flex-shrink: 0;
padding: 8px 16px 16px;
box-sizing: border-box;
}
.msg-skeleton-list {
display: flex;
flex-direction: column;
gap: 20px;
padding: 8px 0;
}
.msg-skeleton-user {
display: flex;
justify-content: flex-end;
}
.msg-skeleton-bot {
display: flex;
flex-direction: column;
gap: 8px;
padding-left: 4px;
}
.sk-line {
height: 14px;
border-radius: 6px;
background: linear-gradient(90deg, #f0f0f0 25%, #e6e6e6 50%, #f0f0f0 75%);
background-size: 200% 100%;
animation: sk-shimmer 1.2s ease-in-out infinite;
}
.sk-line--short { width: 45%; height: 36px; }
.sk-line--medium { width: 60%; }
@keyframes sk-shimmer {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
}
.loading-typing {
display: flex;
align-items: center;
gap: 4px;
span {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--embed-primary, #0052d9);
animation: typingBounce 1.4s ease-in-out infinite;
&:nth-child(1) { animation-delay: 0s; }
&:nth-child(2) { animation-delay: 0.2s; }
&:nth-child(3) { animation-delay: 0.4s; }
}
}
@keyframes typingBounce {
0%, 60%, 100% { transform: translateY(0); }
30% { transform: translateY(-8px); }
}
.scroll-to-bottom-btn {
position: absolute;
left: 50%;
transform: translateX(-50%);
bottom: 100px;
z-index: 10;
width: 36px;
height: 36px;
border-radius: 50%;
background: var(--td-bg-color-container);
border: 1px solid var(--td-component-stroke);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
color: var(--td-text-color-secondary);
}
.scroll-btn-fade-enter-active,
.scroll-btn-fade-leave-active {
transition: opacity 0.2s ease, transform 0.2s ease;
}
.scroll-btn-fade-enter-from,
.scroll-btn-fade-leave-to {
opacity: 0;
transform: translateX(-50%) translateY(8px);
}
</style>
@@ -0,0 +1,48 @@
<template>
<EmbedChatCore
:session-id="sessionId"
:session-sig="sessionSig"
:channel-id="channelId"
:token="token"
:agent-id="agentId"
:kb-ids="kbIds"
:welcome-message="welcomeMessage"
:show-suggested-questions="showSuggestedQuestions"
:allow-web-search="allowWebSearch"
:agent-web-search-enabled="agentWebSearchEnabled"
:allow-file-upload="allowFileUpload"
:agent-image-upload-enabled="agentImageUploadEnabled"
:use-session-header-title="useSessionHeaderTitle"
:host-context="hostContext"
@session-title="(title: string) => emit('session-title', title)"
@messages-state="(has: boolean) => emit('messages-state', has)"
/>
</template>
<script setup lang="ts">
import { defineAsyncComponent } from 'vue'
const EmbedChatCore = defineAsyncComponent(() => import('@/views/embed/EmbedChatCore.vue'))
defineProps<{
sessionId: string
sessionSig: string
channelId: string
token: string
agentId: string
kbIds: string[]
welcomeMessage?: string
showSuggestedQuestions?: boolean
allowWebSearch?: boolean
agentWebSearchEnabled?: boolean
allowFileUpload?: boolean
agentImageUploadEnabled?: boolean
useSessionHeaderTitle?: boolean
hostContext?: Record<string, unknown>
}>()
const emit = defineEmits<{
(e: 'session-title', title: string): void
(e: 'messages-state', hasMessages: boolean): void
}>()
</script>
+256
View File
@@ -0,0 +1,256 @@
<template>
<div class="embed-page" :style="pageStyle">
<div v-if="loadError" class="embed-error">{{ loadError }}</div>
<template v-else-if="config">
<header v-if="sessionId" class="embed-header">
<span class="embed-header__badge" :style="badgeStyle">
<span v-if="config.agent_avatar" class="embed-header__avatar">{{ config.agent_avatar }}</span>
<t-icon v-else :name="headerIcon" size="18px" />
</span>
<div class="embed-header__text">
<h1 class="embed-header__title">{{ headerTitle }}</h1>
<p v-if="headerSubtitle" class="embed-header__subtitle">{{ headerSubtitle }}</p>
</div>
<t-button
variant="text"
shape="square"
size="small"
class="embed-header__action"
:disabled="!chatHasMessages"
:title="$t('embedPublish.newChat')"
:aria-label="$t('embedPublish.newChat')"
@click="handleNewChat"
>
<template #icon><t-icon name="add" /></template>
</t-button>
</header>
<EmbedChatView
v-if="sessionId"
:session-id="sessionId"
:session-sig="sessionSig"
:channel-id="channelId"
:token="token"
:agent-id="config.agent_id"
:kb-ids="kbIds"
:welcome-message="config.welcome_message"
:show-suggested-questions="config.show_suggested_questions !== false"
:allow-web-search="config.allow_web_search === true"
:agent-web-search-enabled="config.agent_web_search_enabled === true"
:allow-file-upload="config.allow_file_upload === true"
:agent-image-upload-enabled="config.agent_image_upload_enabled === true"
:use-session-header-title="useSessionHeaderTitle"
:host-context="hostContext"
@session-title="sessionTitle = $event"
@messages-state="chatHasMessages = $event"
/>
<div v-else class="embed-loading">{{ $t('embedPublish.loading') }}</div>
</template>
<div v-else-if="awaitingToken" class="embed-loading">{{ $t('embedPublish.awaitingToken') }}</div>
<div v-else-if="bootstrapping" class="embed-loading">{{ $t('embedPublish.loading') }}</div>
</div>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import EmbedChatView from '@/views/embed/EmbedChatView.vue'
import { useEmbedBridge } from '@/composables/useEmbedBridge'
const { t } = useI18n()
const route = useRoute()
const channelId = ref(String(route.params.channelId || ''))
const sessionTitle = ref('')
const chatHasMessages = ref(false)
const {
token,
config,
sessionId,
sessionSig,
loadError,
awaitingToken,
bootstrapping,
hostContext,
startNewSession,
} = useEmbedBridge(channelId)
const handleNewChat = () => {
// The current session is already empty — reuse it instead of spawning yet
// another blank session (which would otherwise pile up server-side).
if (!chatHasMessages.value) return
sessionTitle.value = ''
startNewSession()
}
const kbIds = computed(() => config.value?.knowledge_base_ids ?? [])
const pageStyle = computed(() => {
const color = config.value?.primary_color
if (!color) return {}
return {
'--embed-primary': color,
'--td-brand-color': color,
'--td-brand-color-hover': color,
'--td-brand-color-active': color,
} as Record<string, string>
})
const badgeStyle = computed(() => {
const color = config.value?.primary_color
if (!color) return {}
return {
background: `color-mix(in srgb, ${color} 12%, transparent)`,
color,
} as Record<string, string>
})
const channelDisplayTitle = computed(() => {
const cfg = config.value
if (!cfg) return ''
return (
cfg.display_title?.trim()
|| cfg.page_title?.trim()
|| cfg.name?.trim()
|| cfg.agent_name?.trim()
|| t('embedPublish.defaultChatTitle')
)
})
const useSessionHeaderTitle = computed(
() => config.value?.header_title_mode === 'session',
)
const headerTitle = computed(() => {
if (useSessionHeaderTitle.value && sessionTitle.value.trim()) {
return sessionTitle.value.trim()
}
return channelDisplayTitle.value
})
const headerSubtitle = computed(() => {
const cfg = config.value
if (!cfg?.agent_name) return ''
if (useSessionHeaderTitle.value && sessionTitle.value.trim()) {
const fallback = channelDisplayTitle.value
if (fallback && fallback !== sessionTitle.value.trim()) {
return fallback
}
return cfg.agent_name
}
const channelName = cfg.name?.trim()
if (!channelName || channelName === channelDisplayTitle.value) return ''
return cfg.agent_name
})
const headerIcon = computed(() => {
const agentId = config.value?.agent_id || ''
return agentId && agentId !== 'builtin-quick-answer' ? 'control-platform' : 'chat'
})
watch(headerTitle, (title) => {
if (title) document.title = title
}, { immediate: true })
</script>
<style scoped lang="less">
.embed-page {
height: 100vh;
display: flex;
flex-direction: column;
background: var(--td-bg-color-container, #fff);
overflow: hidden;
/* 子组件(含 AgentStreamDisplay)内凡用 --td-brand-color 的 loading / 强调色均跟随渠道主题 */
--td-brand-color: var(--embed-primary, var(--td-brand-color));
--td-brand-color-hover: var(--embed-primary, var(--td-brand-color-hover));
--td-brand-color-active: var(--embed-primary, var(--td-brand-color-active));
:deep(.t-button--theme-primary) {
--td-brand-color: var(--embed-primary, var(--td-brand-color));
--td-brand-color-hover: var(--embed-primary, var(--td-brand-color-hover));
--td-brand-color-active: var(--embed-primary, var(--td-brand-color-active));
}
:deep(.embed-input-box:focus-within) {
border-color: var(--embed-primary, var(--td-brand-color));
}
:deep(.embed-send-btn:not(.disabled)) {
background: var(--embed-primary, var(--td-brand-color));
}
:deep(.loading-typing span) {
background: var(--embed-primary, var(--td-brand-color));
}
}
.embed-header {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 16px;
border-bottom: 1px solid var(--td-component-stroke);
background: var(--td-bg-color-container);
flex-shrink: 0;
&__badge {
display: inline-flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border-radius: 10px;
flex-shrink: 0;
background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
color: var(--td-brand-color);
}
&__avatar {
font-size: 20px;
line-height: 1;
}
&__text {
min-width: 0;
flex: 1;
}
&__action {
flex-shrink: 0;
color: var(--td-text-color-secondary);
&:hover {
color: var(--td-brand-color);
}
}
&__title {
margin: 0;
font-size: 15px;
font-weight: 600;
line-height: 1.35;
color: var(--td-text-color-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
&__subtitle {
margin: 2px 0 0;
font-size: 12px;
line-height: 1.4;
color: var(--td-text-color-secondary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.embed-error,
.embed-loading {
padding: 24px;
text-align: center;
color: var(--td-text-color-placeholder);
}
</style>
@@ -0,0 +1,179 @@
<template>
<div ref="containerRef" class="embed-user-msg" :class="{ 'is-embedded': embeddedMode }">
<div v-if="hasImages" class="user_images">
<img
v-for="(img, idx) in displayImages"
:key="idx"
:src="img.url"
class="user_image_thumb"
alt=""
@click="previewImage($event)"
/>
</div>
<div v-if="hasAttachments" class="user_attachments">
<div v-for="(att, idx) in attachments" :key="idx" class="user_attachment_card">
<div class="attachment_card_info">
<div class="attachment_card_name">{{ att.file_name }}</div>
<div v-if="att.file_size" class="attachment_card_meta">{{ formatFileSize(att.file_size) }}</div>
</div>
</div>
</div>
<div class="user_msg">{{ content }}</div>
<picturePreview :reviewImg="reviewImg" :reviewUrl="reviewUrl" @closePreImg="closePreImg" />
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { hydrateProtectedFileImages } from '@/utils/security'
import picturePreview from '@/components/picture-preview.vue'
type EmbedImage = { url?: string; data?: string }
type EmbedAttachment = { file_name: string; file_size?: number }
const props = withDefaults(
defineProps<{
content?: string
mentioned_items?: unknown[]
images?: EmbedImage[]
attachments?: EmbedAttachment[]
embeddedMode?: boolean
embedChannelId?: string
embedToken?: string
}>(),
{
content: '',
mentioned_items: () => [],
images: () => [],
attachments: () => [],
embeddedMode: true,
embedChannelId: '',
embedToken: '',
},
)
const containerRef = ref<HTMLElement | null>(null)
const reviewImg = ref(false)
const reviewUrl = ref('')
const displayImages = computed(() =>
(props.images || [])
.map((img) => ({ url: String(img.url || img.data || '').trim() }))
.filter((img) => img.url.length > 0),
)
const hasImages = computed(() => displayImages.value.length > 0)
const hasAttachments = computed(() => (props.attachments?.length ?? 0) > 0)
const hydrateImages = async () => {
await nextTick()
if (!props.embedChannelId || !props.embedToken) return
await hydrateProtectedFileImages(containerRef.value, {
channelId: props.embedChannelId,
token: props.embedToken,
})
}
watch(() => props.images, hydrateImages, { deep: true })
onMounted(hydrateImages)
const previewImage = (event: MouseEvent) => {
const src = (event.target as HTMLImageElement | null)?.src
if (!src) return
reviewUrl.value = src
reviewImg.value = true
}
const closePreImg = () => {
reviewImg.value = false
reviewUrl.value = ''
}
const formatFileSize = (bytes: number): string => {
if (!bytes) return ''
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}
</script>
<style scoped lang="less">
.embed-user-msg {
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 6px;
width: 100%;
&.is-embedded .user_msg {
max-width: 100%;
}
}
.user_msg {
width: max-content;
max-width: 776px;
padding: 10px 12px;
border-radius: 4px;
background: #8ce97f;
margin-left: auto;
color: #000000e6;
font-size: 15px;
text-align: justify;
word-break: break-all;
box-sizing: border-box;
white-space: pre-wrap;
}
.user_images {
display: flex;
flex-wrap: wrap;
gap: 6px;
justify-content: flex-end;
max-width: 100%;
}
.user_image_thumb {
width: 120px;
height: 120px;
object-fit: cover;
border-radius: 6px;
border: 1px solid var(--td-border-level-2-color, #e7e7e7);
cursor: pointer;
}
.user_attachments {
display: flex;
flex-wrap: wrap;
gap: 8px;
justify-content: flex-end;
max-width: 100%;
}
.user_attachment_card {
padding: 8px 12px;
border-radius: 8px;
border: 1px solid var(--td-border-level-1-color, #e7e7e7);
background: var(--td-bg-color-container, #fff);
max-width: 260px;
min-width: 120px;
}
.attachment_card_name {
font-size: 13px;
font-weight: 500;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.attachment_card_meta {
font-size: 11px;
color: var(--td-text-color-secondary, #999);
}
html[theme-mode='dark'] .user_msg {
background: var(--td-brand-color-3);
color: rgba(255, 255, 255, 0.9);
}
</style>
+76 -1
View File
@@ -3,7 +3,7 @@ import { resolve, dirname } from 'node:path'
import { existsSync } from 'node:fs'
import { execSync } from 'node:child_process'
import { createRequire } from 'node:module'
import { defineConfig } from 'vite'
import { defineConfig, type Plugin } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
@@ -28,6 +28,25 @@ function resolveFrontendCommit(): string {
}
const FRONTEND_COMMIT = resolveFrontendCommit()
/** Dev parity with nginx: serve embed.html for /embed/:channelId (not the main SPA). */
function embedHtmlDevFallback(): Plugin {
return {
name: 'embed-html-dev-fallback',
configureServer(server) {
server.middlewares.use((req, _res, next) => {
const raw = req.url ?? ''
const qIdx = raw.indexOf('?')
const path = qIdx >= 0 ? raw.slice(0, qIdx) : raw
const qs = qIdx >= 0 ? raw.slice(qIdx) : ''
if (path.startsWith('/embed/') && path !== '/embed.html' && !path.includes('.')) {
req.url = `/embed.html${qs}`
}
next()
})
},
}
}
const DEV_PROXY_TARGET =
process.env.VITE_DEV_PROXY_TARGET ||
process.env.FRONTEND_BACKEND_URL ||
@@ -53,9 +72,65 @@ export default defineConfig({
__FRONTEND_VERSION__: JSON.stringify(FRONTEND_VERSION),
__FRONTEND_COMMIT__: JSON.stringify(FRONTEND_COMMIT),
},
build: {
modulePreload: {
resolveDependencies(_filename, deps, { hostId }) {
// Embed iframe bootstraps with token exchange only; defer heavy chat chunks.
if (hostId?.includes('embed')) {
return deps.filter((dep) => !(
dep.includes('vendor-mermaid')
|| dep.includes('vendor-highlight')
|| dep.includes('vendor-markdown')
|| dep.includes('vendor-tdesign')
|| dep.includes('botmsg')
|| dep.includes('usermsg')
|| dep.includes('EmbedBotMessage')
|| dep.includes('EmbedUserMessage')
|| dep.includes('AgentStreamDisplay')
|| dep.includes('EmbedChatCore')
|| dep.includes('vendor-markdown')
|| dep.includes('fonts-')
))
}
return deps
},
},
rollupOptions: {
input: {
main: resolve(__dirname, 'index.html'),
embed: resolve(__dirname, 'embed.html'),
},
output: {
manualChunks(id) {
if (!id.includes('node_modules')) return
if (id.includes('mermaid') || id.includes('/dagre') || id.includes('cytoscape')) {
return 'vendor-mermaid'
}
if (id.includes('marked') || id.includes('katex')) {
return 'vendor-markdown'
}
if (id.includes('highlight.js')) {
return 'vendor-highlight'
}
if (id.includes('tdesign-vue-next')) {
return 'vendor-tdesign'
}
if (
id.includes('/vue/') ||
id.includes('/vue-router/') ||
id.includes('/pinia/') ||
id.includes('/vue-i18n/')
) {
return 'vendor-vue'
}
},
},
},
},
plugins: [
vue(),
vueJsx(),
embedHtmlDevFallback(),
],
resolve: {
alias: {