Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(frontend): add API integration playground
wizardchenee1014f87c3b
diff --git a/client/tenant.go b/client/tenant.goindex 878ce96c1..90e503534 100644--- a/client/tenant.go+++ b/client/tenant.go@@ -245,6 +245,7 @@ type APIPrincipalConfig struct {SignedTokenHeaderName string `json:"signed_token_header_name"`RequireDirectHeader bool `json:"require_direct_header"`HasHMACSecret bool `json:"has_hmac_secret"`+ HMACSecret string `json:"hmac_secret,omitempty"`}type apiPrincipalConfigResponse struct {@@ -261,6 +262,26 @@ type UpdateAPIPrincipalConfigRequest struct {HMACSecret string `json:"hmac_secret,omitempty"`}+// CreateAPIPrincipalTestTokenRequest signs a short-lived JWT for API integration testing.+type CreateAPIPrincipalTestTokenRequest struct {+ ExternalUserID string `json:"external_user_id"`+ ExpiresInSeconds int `json:"expires_in_seconds,omitempty"`+}++// APIPrincipalTestToken is a short-lived JWT signed with the tenant API principal HMAC secret.+type APIPrincipalTestToken struct {+ Token string `json:"token"`+ HeaderName string `json:"header_name"`+ ExpiresInSeconds int `json:"expires_in_seconds"`+ ExpiresAtUnix int64 `json:"expires_at_unix"`+ ExternalUserID string `json:"external_user_id"`+}++type apiPrincipalTestTokenResponse struct {+ Success bool `json:"success"`+ Data APIPrincipalTestToken `json:"data"`+}+// GetAPIPrincipalConfig returns how X-API-Key requests map to principals for a tenant.func (c *Client) GetAPIPrincipalConfig(ctx context.Context, tenantID uint64) (*APIPrincipalConfig, error) {path := fmt.Sprintf("/api/v1/tenants/%d/api-principal-config", tenantID)@@ -292,3 +313,20 @@ func (c *Client) UpdateAPIPrincipalConfig(}return &response.Data, nil}++// CreateAPIPrincipalTestToken signs a short-lived JWT with the tenant API principal HMAC secret.+func (c *Client) CreateAPIPrincipalTestToken(+ ctx context.Context, tenantID uint64, req *CreateAPIPrincipalTestTokenRequest,+) (*APIPrincipalTestToken, error) {+ path := fmt.Sprintf("/api/v1/tenants/%d/api-principal-test-token", tenantID)+ resp, err := c.doRequest(ctx, http.MethodPost, path, req, nil)+ if err != nil {+ return nil, err+ }++ var response apiPrincipalTestTokenResponse+ if err := parseResponse(resp, &response); err != nil {+ return nil, err+ }+ return &response.Data, nil+}diff --git a/frontend/src/api/tenant/index.ts b/frontend/src/api/tenant/index.tsindex 2758832b5..a785a83b2 100644--- a/frontend/src/api/tenant/index.ts+++ b/frontend/src/api/tenant/index.ts@@ -25,6 +25,7 @@ export interface APIPrincipalConfig {signed_token_header_name: stringrequire_direct_header: booleanhas_hmac_secret: boolean+ hmac_secret?: string}export interface UpdateAPIPrincipalConfigPayload {@@ -35,6 +36,19 @@ export interface UpdateAPIPrincipalConfigPayload {hmac_secret?: string}+export interface CreateAPIPrincipalTestTokenPayload {+ external_user_id: string+ expires_in_seconds?: number+}++export interface APIPrincipalTestToken {+ token: string+ header_name: string+ expires_in_seconds: number+ expires_at_unix: number+ external_user_id: string+}+// 搜索租户参数export interface SearchTenantsParams {keyword?: string@@ -117,6 +131,21 @@ export async function updateAPIPrincipalConfig(}}+export async function createAPIPrincipalTestToken(+ tenantId: number,+ payload: CreateAPIPrincipalTestTokenPayload,+): Promise<{ success: boolean; data?: APIPrincipalTestToken; message?: string }> {+ try {+ const response = await post(`/api/v1/tenants/${tenantId}/api-principal-test-token`, payload)+ return response as unknown as { success: boolean; data?: APIPrincipalTestToken; message?: string }+ } catch (error: any) {+ return {+ success: false,+ message: error.message || t('error.tenant.createApiPrincipalTestTokenFailed'),+ }+ }+}+/*** 更新租户信息(目前暴露名称、描述两个字段的编辑入口)。* 后端 `PUT /tenants/:id` 用指针字段区分"未传"和"显式空串",未传的列不会diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 9f9b4911b..a66e86ea5 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -3637,6 +3637,7 @@ export default {resetApiKeyFailed: 'Failed to reset API Key',getApiPrincipalConfigFailed: 'Failed to get API principal config',updateApiPrincipalConfigFailed: 'Failed to update API principal config',+ createApiPrincipalTestTokenFailed: 'Failed to create API test token',updateFailed: 'Failed to update tenant information',deleteFailed: 'Failed to delete tenant',},@@ -5774,11 +5775,15 @@ export default {requireDirectHeaderDesc:'When enabled, API Key requests without the user ID header are rejected; when disabled, all requests are treated as the whole tenant with no per-user distinction.',tokenHeader: 'Token header',- tokenHeaderDesc: 'Clients send the backend-signed JWT; header name is configurable.',+ tokenHeaderDesc: 'Clients send the backend-signed JWT in this fixed header.',hmacSecret: 'HMAC secret',hmacSecretDesc: 'Same secret stored in WeKnora; used only on your backend to sign JWTs—never send it as a request header.',secretConfigured: 'Secret configured; enter a new value to rotate',generateSecret: 'Generate secret',+ hmacSecretResetConfirmTitle: 'Reset HMAC secret?',+ hmacSecretResetConfirmBody: 'After reset, the old HMAC secret is revoked immediately. Every backend service signing JWTs with the old secret must switch to the new secret to keep signed-token calls working. This action cannot be undone.',+ hmacSecretResetConfirmOk: 'Reset',+ hmacSecretResetConfirmCancel: 'Cancel',tokenSignExample: 'Backend JWT signing example (Go)',signedRequestStep0:'# 0. Sign JWT on your backend (HS256, aud=weknora, sub=user id, tenant_id={tenantId}, exp<=24h)',@@ -5787,9 +5792,47 @@ export default {requestExampleAgentChat: '# 2. Agent chat (SSE; replace <session_id> with the id from step 1)',requestExampleJwtPlaceholder: '<JWT signed by your backend>',requestExample: 'Request example',+ playgroundTitle: 'API Playground',+ playgroundDesc: 'Send real requests with the current API key and identity mode to verify session creation, agent chat, and SSE output.',+ playgroundOpen: 'Open Playground',+ playgroundDrawerDesc: 'Debug sessions, Agent Chat, and SSE output using the real API integration flow',+ playgroundBadge: 'Real request',+ playgroundSectionRequest: 'Request setup',+ playgroundSectionPreview: 'Request preview',+ playgroundSectionResult: 'Run result',+ playgroundAgent: 'Test agent',+ playgroundAgentPlaceholder: 'Select an agent to test',+ playgroundBuiltin: 'Built-in',+ playgroundAgentsLoadFailed: 'Failed to load agents',+ playgroundExternalUser: 'External user ID',+ playgroundExternalUserPlaceholder: 'user_123',+ playgroundTenantModeHint: 'Tenant-only mode does not send an external user identity; all API sessions use the same tenant-level principal.',+ playgroundDirectModeHint: 'This user ID is sent with the {headerName} header.',+ playgroundSignedModeHint: 'Signed-token mode uses the JWT sub as the external user. The playground signs a short-lived test JWT for this user ID.',+ playgroundQuestion: 'Test question',+ playgroundQuestionPlaceholder: 'Enter a question to send to the agent',+ playgroundRequestPreview: 'Request preview (secrets masked)',+ playgroundRun: 'Run test',+ playgroundStop: 'Stop',+ playgroundNeedApiKey: 'This tenant has no API key.',+ playgroundNeedAgent: 'Select a test agent.',+ playgroundNeedQuestion: 'Enter a test question.',+ playgroundNeedExternalUser: 'Enter an external user ID.',+ playgroundMintTokenFailed: 'Failed to create a short-lived test JWT.',+ playgroundMissingSessionId: 'Session creation succeeded, but the response did not include a session id.',+ playgroundNoStream: 'The chat API did not return a readable SSE stream.',+ playgroundGeneratedToken: 'Generated test token',+ playgroundStepSession: 'Step 1: Create Session',+ playgroundStepChat: 'Step 2: Agent Chat SSE',+ playgroundFinalAnswer: 'Extracted answer',+ playgroundEmptyResult: 'Run a test to show the session response, raw SSE output, and extracted answer here.',+ playgroundSuccess: 'Test completed ({ms}ms)',+ playgroundStopped: 'Test stopped',+ playgroundFailed: 'API Playground test failed',loadFailed: 'Failed to load API integration settings',saveFailed: 'Failed to save API integration settings',saveSuccess: 'API integration settings saved',+ autoSaveNeedSecret: 'Signed-token mode needs an HMAC secret before auto-save can run.',},manageSectionTitle: 'Channel configuration',manageSectionDesc: 'Select an agent to create or edit integration channels for that agent',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 3cc55ee19..04197f4ef 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -2645,6 +2645,7 @@ export default {resetApiKeyFailed: 'API 키 재설정 실패',getApiPrincipalConfigFailed: 'API principal config 조회 실패',updateApiPrincipalConfigFailed: 'API principal config 업데이트 실패',+ createApiPrincipalTestTokenFailed: 'API 테스트 토큰 생성 실패',updateFailed: '테넌트 정보 업데이트 실패',},initialization: {@@ -5785,11 +5786,15 @@ export default {requireDirectHeaderDesc:"켜면 사용자 ID 헤더가 없는 API Key 요청을 거부하고, 끄면 테넌트 전체로 통일 처리하며 개별 사용자를 구분하지 않습니다.",tokenHeader: "토큰 헤더",- tokenHeaderDesc: "클라이언트는 백엔드가 서명한 JWT를 전달합니다. 헤더 이름은 변경할 수 있습니다.",+ tokenHeaderDesc: "클라이언트는 이 고정 헤더에 백엔드가 서명한 JWT를 전달합니다.",hmacSecret: "HMAC secret",hmacSecretDesc: "WeKnora에 저장된 것과 동일한 secret. 백엔드에서 JWT 서명에만 사용하며 요청 헤더로 보내지 않습니다.",secretConfigured: "Secret configured; enter a new value to rotate",generateSecret: "Secret 생성",+ hmacSecretResetConfirmTitle: "HMAC secret을 재설정할까요?",+ hmacSecretResetConfirmBody: "재설정하면 기존 HMAC secret은 즉시 무효화됩니다. 기존 secret으로 JWT를 서명하는 모든 백엔드 서비스는 새 secret으로 교체해야 서명 토큰 호출을 계속 사용할 수 있습니다. 이 작업은 되돌릴 수 없습니다.",+ hmacSecretResetConfirmOk: "재설정",+ hmacSecretResetConfirmCancel: "취소",tokenSignExample: "백엔드 JWT 서명 예시 (Go)",signedRequestStep0:"# 0. 백엔드에서 JWT 서명 (HS256, aud=weknora, sub=사용자 ID, tenant_id={tenantId}, exp 최대 24시간)",@@ -5798,9 +5803,47 @@ export default {requestExampleAgentChat: "# 2. Agent 대화 (SSE; <session_id>를 1단계 id로 교체)",requestExampleJwtPlaceholder: "<백엔드가 서명한 JWT>",requestExample: "요청 예시",+ playgroundTitle: "API Playground",+ playgroundDesc: "현재 API Key와 사용자 ID 모드로 실제 요청을 보내 세션 생성, Agent 대화, SSE 출력을 확인합니다.",+ playgroundOpen: "Playground 열기",+ playgroundDrawerDesc: "실제 API 연동 흐름으로 Session, Agent Chat, SSE 출력을 디버그합니다",+ playgroundBadge: "실제 요청",+ playgroundSectionRequest: "요청 설정",+ playgroundSectionPreview: "요청 미리보기",+ playgroundSectionResult: "실행 결과",+ playgroundAgent: "테스트 Agent",+ playgroundAgentPlaceholder: "테스트할 Agent 선택",+ playgroundBuiltin: "기본 제공",+ playgroundAgentsLoadFailed: "Agent 목록을 불러오지 못했습니다",+ playgroundExternalUser: "외부 사용자 ID",+ playgroundExternalUserPlaceholder: "user_123",+ playgroundTenantModeHint: "테넌트 전용 모드는 외부 사용자 ID를 보내지 않으며 모든 API 세션이 동일한 테넌트 주체에 속합니다.",+ playgroundDirectModeHint: "{headerName} 헤더로 이 사용자 ID를 보냅니다.",+ playgroundSignedModeHint: "서명 토큰 모드는 JWT sub를 외부 사용자로 사용합니다. Playground가 이 사용자 ID로 단기 테스트 JWT를 자동 서명합니다.",+ playgroundQuestion: "테스트 질문",+ playgroundQuestionPlaceholder: "Agent에게 보낼 질문을 입력하세요",+ playgroundRequestPreview: "요청 미리보기(secret 마스킹됨)",+ playgroundRun: "테스트 실행",+ playgroundStop: "중지",+ playgroundNeedApiKey: "현재 테넌트에 API Key가 없습니다.",+ playgroundNeedAgent: "테스트 Agent를 선택하세요.",+ playgroundNeedQuestion: "테스트 질문을 입력하세요.",+ playgroundNeedExternalUser: "외부 사용자 ID를 입력하세요.",+ playgroundMintTokenFailed: "단기 테스트 JWT 생성 실패.",+ playgroundMissingSessionId: "세션 생성은 성공했지만 응답에 session id가 없습니다.",+ playgroundNoStream: "대화 API가 읽을 수 있는 SSE 스트림을 반환하지 않았습니다.",+ playgroundGeneratedToken: "이번에 생성된 테스트 토큰",+ playgroundStepSession: "1단계: Session 생성",+ playgroundStepChat: "2단계: Agent Chat SSE",+ playgroundFinalAnswer: "추출된 답변",+ playgroundEmptyResult: "테스트를 실행하면 Session 응답, 원시 SSE 출력, 추출된 답변이 여기에 표시됩니다.",+ playgroundSuccess: "테스트 완료({ms}ms)",+ playgroundStopped: "테스트가 중지되었습니다",+ playgroundFailed: "API Playground 테스트 실패",loadFailed: "API 통합 설정을 불러오지 못했습니다",saveFailed: "API 통합 설정 저장 실패",saveSuccess: "API 통합 설정이 저장되었습니다",+ autoSaveNeedSecret: "서명 토큰 모드는 자동 저장 전에 HMAC secret이 필요합니다.",},manageSectionTitle: "채널 구성",manageSectionDesc: "에이전트를 선택한 후 해당 에이전트의 통합 채널을 생성하거나 편집할 수 있습니다",diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex cd63b374f..dd9b26233 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -2360,6 +2360,7 @@ export default {resetApiKeyFailed: 'Не удалось сбросить API Key',getApiPrincipalConfigFailed: 'Не удалось получить конфигурацию API principal',updateApiPrincipalConfigFailed: 'Не удалось обновить конфигурацию API principal',+ createApiPrincipalTestTokenFailed: 'Не удалось создать тестовый API Token',updateFailed: 'Не удалось обновить информацию об арендаторе'},initialization: {@@ -5607,11 +5608,15 @@ export default {requireDirectHeaderDesc:'Если включено, запросы без заголовка ID пользователя отклоняются; иначе все запросы обрабатываются как единый арендатор без различия конечных пользователей.',tokenHeader: 'Заголовок token',- tokenHeaderDesc: 'Клиент передаёт JWT, подписанный backend; имя заголовка настраивается.',+ tokenHeaderDesc: 'Клиент передаёт JWT, подписанный backend, в этом фиксированном заголовке.',hmacSecret: 'HMAC secret',hmacSecretDesc: 'Тот же secret, что в WeKnora; только для подписи JWT на backend — не отправляйте его в заголовке запроса.',secretConfigured: 'Secret настроен; введите новое значение для ротации',generateSecret: 'Сгенерировать secret',+ hmacSecretResetConfirmTitle: 'Сбросить HMAC secret?',+ hmacSecretResetConfirmBody: 'После сброса старый HMAC secret немедленно перестанет действовать. Все backend-сервисы, подписывающие JWT старым secret, должны перейти на новый secret, чтобы вызовы signed token продолжили работать. Это действие нельзя отменить.',+ hmacSecretResetConfirmOk: 'Сбросить',+ hmacSecretResetConfirmCancel: 'Отмена',tokenSignExample: 'Пример подписи JWT на backend (Go)',signedRequestStep0:'# 0. Подпишите JWT на backend (HS256, aud=weknora, sub=ID пользователя, tenant_id={tenantId}, exp не более 24 ч)',@@ -5620,9 +5625,47 @@ export default {requestExampleAgentChat: '# 2. Agent-чат (SSE; замените <session_id> на id из шага 1)',requestExampleJwtPlaceholder: '<JWT, подписанный backend>',requestExample: 'Пример запроса',+ playgroundTitle: 'API Playground',+ playgroundDesc: 'Отправьте реальные запросы с текущим API key и режимом идентификации, чтобы проверить создание session, agent chat и SSE-ответ.',+ playgroundOpen: 'Открыть Playground',+ playgroundDrawerDesc: 'Отладка Session, Agent Chat и SSE-ответа через реальный API integration flow',+ playgroundBadge: 'Реальный запрос',+ playgroundSectionRequest: 'Настройка запроса',+ playgroundSectionPreview: 'Preview запроса',+ playgroundSectionResult: 'Результат запуска',+ playgroundAgent: 'Тестовый агент',+ playgroundAgentPlaceholder: 'Выберите агента для теста',+ playgroundBuiltin: 'Встроенный',+ playgroundAgentsLoadFailed: 'Не удалось загрузить агентов',+ playgroundExternalUser: 'ID внешнего пользователя',+ playgroundExternalUserPlaceholder: 'user_123',+ playgroundTenantModeHint: 'Режим только арендатора не отправляет внешнего пользователя; все API sessions используют один tenant principal.',+ playgroundDirectModeHint: 'Этот ID пользователя будет отправлен в заголовке {headerName}.',+ playgroundSignedModeHint: 'В режиме signed token внешний пользователь берётся из JWT sub. Playground автоматически подпишет краткоживущий тестовый JWT для этого user ID.',+ playgroundQuestion: 'Тестовый вопрос',+ playgroundQuestionPlaceholder: 'Введите вопрос для отправки агенту',+ playgroundRequestPreview: 'Preview запроса (секреты скрыты)',+ playgroundRun: 'Запустить тест',+ playgroundStop: 'Остановить',+ playgroundNeedApiKey: 'У этого арендатора нет API key.',+ playgroundNeedAgent: 'Выберите тестового агента.',+ playgroundNeedQuestion: 'Введите тестовый вопрос.',+ playgroundNeedExternalUser: 'Введите external user ID.',+ playgroundMintTokenFailed: 'Не удалось создать краткоживущий тестовый JWT.',+ playgroundMissingSessionId: 'Session создана, но в ответе нет session id.',+ playgroundNoStream: 'Chat API не вернул читаемый SSE stream.',+ playgroundGeneratedToken: 'Сгенерированный тестовый token',+ playgroundStepSession: 'Шаг 1: создать Session',+ playgroundStepChat: 'Шаг 2: Agent Chat SSE',+ playgroundFinalAnswer: 'Извлечённый ответ',+ playgroundEmptyResult: 'Запустите тест, чтобы увидеть здесь ответ Session, сырой SSE output и извлечённый ответ.',+ playgroundSuccess: 'Тест завершён ({ms}ms)',+ playgroundStopped: 'Тест остановлен',+ playgroundFailed: 'Тест API Playground не удался',loadFailed: 'Не удалось загрузить настройки API-интеграции',saveFailed: 'Не удалось сохранить настройки API-интеграции',saveSuccess: 'Настройки API-интеграции сохранены',+ autoSaveNeedSecret: 'Для signed-token режима нужен HMAC secret перед автосохранением.',},manageSectionTitle: 'Настройка каналов',manageSectionDesc: 'Выберите агента, чтобы создать или изменить каналы интеграции для него',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex d7b35f3e1..3be6ea6e4 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -2655,6 +2655,7 @@ export default {resetApiKeyFailed: "重置 API Key 失败",getApiPrincipalConfigFailed: "获取 API 用户身份配置失败",updateApiPrincipalConfigFailed: "更新 API 用户身份配置失败",+ createApiPrincipalTestTokenFailed: "生成 API 测试 Token 失败",updateFailed: "更新空间信息失败",deleteFailed: "删除空间失败",},@@ -5787,11 +5788,15 @@ export default {requireDirectHeaderDesc:"开启后,缺少用户 ID 请求头的 API Key 请求将被拒绝;关闭则按整个租户统一处理,不区分具体终端用户。",tokenHeader: "Token 请求头",- tokenHeaderDesc: "客户端携带后端签发的 JWT,请求头名可自定义。",+ tokenHeaderDesc: "客户端在该固定请求头中携带后端签发的 JWT。",hmacSecret: "HMAC 密钥",hmacSecretDesc: "与 WeKnora 保存的同一份密钥;仅用于后端签发 JWT,不要作为请求头发送。",secretConfigured: "已配置密钥;输入新值可轮换",generateSecret: "生成密钥",+ hmacSecretResetConfirmTitle: "确认重置 HMAC 密钥?",+ hmacSecretResetConfirmBody: "重置后,旧的 HMAC 密钥会立即失效,所有使用旧密钥签发 JWT 的后端服务必须更换为新密钥才可继续通过签名 Token 调用。此操作不可撤销。",+ hmacSecretResetConfirmOk: "确认重置",+ hmacSecretResetConfirmCancel: "取消",tokenSignExample: "后端签发 JWT 示例(Go)",signedRequestStep0:"# 0. 在你的后端签发 JWT(HS256,aud=weknora,sub=用户 ID,tenant_id={tenantId},exp 不超过 24 小时)",@@ -5800,9 +5805,47 @@ export default {requestExampleAgentChat: "# 2. Agent 对话(SSE;将 <session_id> 替换为第 1 步返回的 id)",requestExampleJwtPlaceholder: "<后端签发的 JWT>",requestExample: "请求示例",+ playgroundTitle: "API Playground",+ playgroundDesc: "用当前 API Key 和身份模式发起真实请求,验证会话创建、智能体对话和 SSE 返回。",+ playgroundOpen: "打开 Playground",+ playgroundDrawerDesc: "按真实 API 集成方式调试 Session、Agent Chat 和 SSE 返回",+ playgroundBadge: "真实请求",+ playgroundSectionRequest: "请求配置",+ playgroundSectionPreview: "请求预览",+ playgroundSectionResult: "运行结果",+ playgroundAgent: "测试智能体",+ playgroundAgentPlaceholder: "选择要测试的智能体",+ playgroundBuiltin: "内置",+ playgroundAgentsLoadFailed: "智能体列表加载失败",+ playgroundExternalUser: "外部用户 ID",+ playgroundExternalUserPlaceholder: "user_123",+ playgroundTenantModeHint: "仅租户模式不会发送外部用户身份,所有 API 会话归属同一个租户级主体。",+ playgroundDirectModeHint: "将通过 {headerName} 请求头发送此用户 ID。",+ playgroundSignedModeHint: "签名模式由 JWT 的 sub 代表外部用户;Playground 会用这里的用户 ID 自动签出短期测试 JWT。",+ playgroundQuestion: "测试问题",+ playgroundQuestionPlaceholder: "输入要发送给智能体的问题",+ playgroundRequestPreview: "请求预览(已遮蔽密钥)",+ playgroundRun: "运行测试",+ playgroundStop: "停止",+ playgroundNeedApiKey: "当前租户没有 API Key。",+ playgroundNeedAgent: "请选择测试智能体。",+ playgroundNeedQuestion: "请输入测试问题。",+ playgroundNeedExternalUser: "请输入外部用户 ID。",+ playgroundMintTokenFailed: "生成短期测试 JWT 失败。",+ playgroundMissingSessionId: "创建会话成功,但响应中没有 session id。",+ playgroundNoStream: "对话接口没有返回可读取的 SSE 流。",+ playgroundGeneratedToken: "本次生成的测试 Token",+ playgroundStepSession: "步骤 1:创建 Session",+ playgroundStepChat: "步骤 2:Agent Chat SSE",+ playgroundFinalAnswer: "提取出的回答",+ playgroundEmptyResult: "运行后将在这里显示 Session 响应、SSE 原始输出和提取出的回答。",+ playgroundSuccess: "测试完成({ms}ms)",+ playgroundStopped: "测试已停止",+ playgroundFailed: "API Playground 测试失败",loadFailed: "加载 API 集成设置失败",saveFailed: "保存 API 集成设置失败",saveSuccess: "API 集成设置已保存",+ autoSaveNeedSecret: "签名 Token 模式需要填写 HMAC 密钥后才能自动保存。",},manageSectionTitle: "渠道配置",manageSectionDesc: "选择智能体后,可创建或编辑该智能体下的集成渠道",diff --git a/frontend/src/views/integrations/ApiIntegrationSettings.vue b/frontend/src/views/integrations/ApiIntegrationSettings.vueindex b312b508d..91ac93b28 100644--- a/frontend/src/views/integrations/ApiIntegrationSettings.vue+++ b/frontend/src/views/integrations/ApiIntegrationSettings.vue@@ -50,58 +50,94 @@<p class="principal-section__scope">{{ $t('integrations.api.principalScope') }}</p></div>- <t-radio-group v-model="form.mode" class="mode-radio">+ <t-radio-group v-model="form.mode" class="mode-radio" @change="handlePrincipalModeChange"><t-radio-button value="tenant">{{ $t('integrations.api.modeTenant') }}</t-radio-button><t-radio-button value="direct_header">{{ $t('integrations.api.modeDirect') }}</t-radio-button><t-radio-button value="signed_token">{{ $t('integrations.api.modeSigned') }}</t-radio-button></t-radio-group><div v-if="form.mode !== 'tenant'" class="mode-detail">- <t-alert+ <divv-if="form.mode === 'direct_header'"- theme="warning"- :title="$t('integrations.api.directWarning')"- :message="$t('integrations.api.directWarningDetail')"- />- <p v-else-if="form.mode === 'signed_token'" class="mode-hint">- <span class="mode-hint__title">{{ $t('integrations.api.signedRecommended') }}</span>- {{ $t('integrations.api.signedFlowDetail') }}- </p>-- <div v-if="form.mode === 'direct_header'" class="form-grid">- <div class="form-item">- <label class="form-item__label">{{ $t('integrations.api.directHeader') }}</label>- <t-input v-model="form.direct_header_name" class="mono-input" />+ class="mode-callout mode-callout--warning"+ >+ <div class="mode-callout__body">+ <strong>{{ $t('integrations.api.directWarning') }}</strong>+ <p>{{ $t('integrations.api.directWarningDetail') }}</p>+ </div>+ </div>+ <div+ v-else-if="form.mode === 'signed_token'"+ class="mode-callout"+ >+ <div class="mode-callout__body">+ <strong>{{ $t('integrations.api.signedRecommended') }}</strong>+ <p>{{ $t('integrations.api.signedFlowDetail') }}</p>+ </div>+ </div>++ <div v-if="form.mode === 'direct_header'" class="principal-config">+ <div class="config-row">+ <div class="config-row__text">+ <label>{{ $t('integrations.api.directHeader') }}</label>+ </div>+ <code class="fixed-header-name">{{ directHeaderName }}</code></div>- <div class="form-item form-item--switch">- <label class="form-item__label">{{ $t('integrations.api.requireDirectHeader') }}</label>- <div class="form-item__control">- <t-switch v-model="form.require_direct_header" size="small" />- <span class="form-item__hint">{{ $t('integrations.api.requireDirectHeaderDesc') }}</span>+ <div class="config-row config-row--switch">+ <div class="config-row__text">+ <label>{{ $t('integrations.api.requireDirectHeader') }}</label>+ <p>{{ $t('integrations.api.requireDirectHeaderDesc') }}</p>+ </div>+ <div class="config-row__action">+ <t-switch v-model="form.require_direct_header" size="small" @change="handleRequireDirectHeaderChange" /></div></div></div>- <div v-else-if="form.mode === 'signed_token'" class="form-grid">- <div class="form-item">- <label class="form-item__label">{{ $t('integrations.api.tokenHeader') }}</label>- <t-input v-model="form.signed_token_header_name" class="mono-input" />- <p class="form-item__hint">{{ $t('integrations.api.tokenHeaderDesc') }}</p>+ <div v-else-if="form.mode === 'signed_token'" class="principal-config">+ <div class="config-row">+ <div class="config-row__text">+ <label>{{ $t('integrations.api.tokenHeader') }}</label>+ <p>{{ $t('integrations.api.tokenHeaderDesc') }}</p>+ </div>+ <code class="fixed-header-name">{{ tokenHeaderName }}</code></div>- <div class="form-item">- <label class="form-item__label">{{ $t('integrations.api.hmacSecret') }}</label>- <div class="copy-field">+ <div class="config-row config-row--secret">+ <div class="config-row__text">+ <label>{{ $t('integrations.api.hmacSecret') }}</label>+ <p>{{ $t('integrations.api.hmacSecretDesc') }}</p>+ </div>+ <div class="secret-control"><t-inputv-model="secretInput"- type="password"+ :type="showHMACSecret ? 'text' : 'password'"class="mono-input":placeholder="config?.has_hmac_secret ? $t('integrations.api.secretConfigured') : ''"+ @blur="triggerAutoSave"/>- <t-button variant="text" :title="$t('integrations.api.generateSecret')" @click="generateSecret">+ <t-button size="small" variant="text" @click="showHMACSecret = !showHMACSecret">+ <t-icon :name="showHMACSecret ? 'browse-off' : 'browse'" />+ </t-button>+ <t-button+ size="small"+ variant="text"+ :title="$t('integrations.api.copy')"+ :disabled="!secretInput.trim()"+ @click="copy(secretInput)"+ >+ <t-icon name="file-copy" />+ </t-button>+ <t-button+ size="small"+ variant="text"+ theme="danger"+ :title="$t('integrations.api.generateSecret')"+ :loading="saving"+ @click="confirmGenerateSecret"+ ><t-icon name="refresh" /></t-button></div>- <p class="form-item__hint">{{ $t('integrations.api.hmacSecretDesc') }}</p></div></div></div>@@ -127,22 +163,153 @@</div></div>- <div class="actions">- <t-button theme="primary" :loading="saving" :disabled="!canSave" @click="save">- {{ $t('integrations.api.save') }}+ <div class="playground-entry">+ <div class="playground-entry__info">+ <label>{{ $t('integrations.api.playgroundTitle') }}</label>+ <p>{{ $t('integrations.api.playgroundDesc') }}</p>+ </div>+ <t-button variant="outline" @click="openPlaygroundDrawer">+ <template #icon><t-icon name="code" /></template>+ {{ $t('integrations.api.playgroundOpen') }}</t-button></div></section></div>++ <SettingDrawer+ v-model:visible="playgroundDrawerVisible"+ class="api-playground-drawer"+ :title="$t('integrations.api.playgroundTitle')"+ :description="$t('integrations.api.playgroundDrawerDesc')"+ icon="code"+ width="640px"+ :min-width="560"+ :max-width="960"+ storage-key="setting-drawer:width:api-playground"+ :confirm-text="$t('integrations.api.playgroundRun')"+ :confirm-loading="playground.running"+ :confirm-disabled="!canRunPlayground"+ @confirm="runPlayground"+ @cancel="handlePlaygroundDrawerCancel"+ >+ <template #footer-left>+ <t-button v-if="playground.running" variant="outline" @click="stopPlayground">+ <template #icon><t-icon name="close-circle" /></template>+ {{ $t('integrations.api.playgroundStop') }}+ </t-button>+ <span v-if="playgroundDisabledReason" class="footer-test-message">+ {{ playgroundDisabledReason }}+ </span>+ </template>++ <section class="setting-drawer__section">+ <h4 class="setting-drawer__section-title">{{ $t('integrations.api.playgroundSectionRequest') }}</h4>++ <div class="drawer-form-item">+ <label class="drawer-form-label">{{ $t('integrations.api.playgroundAgent') }}</label>+ <t-select+ v-model="playground.agent_id"+ :options="agentOptions"+ :loading="agentsLoading"+ filterable+ :placeholder="$t('integrations.api.playgroundAgentPlaceholder')"+ />+ <p v-if="agentsError" class="drawer-form-desc drawer-form-desc--error">{{ agentsError }}</p>+ </div>++ <div class="drawer-form-item">+ <label class="drawer-form-label">{{ $t('integrations.api.playgroundExternalUser') }}</label>+ <t-input+ v-model="playground.external_user_id"+ :disabled="form.mode === 'tenant'"+ class="mono-input"+ :placeholder="$t('integrations.api.playgroundExternalUserPlaceholder')"+ />+ <p class="drawer-form-desc">{{ externalUserHint }}</p>+ </div>++ <div class="drawer-form-item">+ <label class="drawer-form-label">{{ $t('integrations.api.playgroundQuestion') }}</label>+ <t-textarea+ v-model="playground.query"+ :autosize="{ minRows: 2, maxRows: 4 }"+ :placeholder="$t('integrations.api.playgroundQuestionPlaceholder')"+ />+ </div>+ </section>++ <section class="setting-drawer__section">+ <h4 class="setting-drawer__section-title">{{ $t('integrations.api.playgroundSectionPreview') }}</h4>+ <div class="code-panel playground-preview">+ <div class="code-panel__toolbar">+ <span class="code-panel__label">{{ $t('integrations.api.playgroundRequestPreview') }}</span>+ <t-button size="small" variant="text" class="code-panel__copy" @click="copy(playgroundRequestPreview)">+ <template #icon><t-icon name="file-copy" /></template>+ {{ $t('integrations.api.copy') }}+ </t-button>+ </div>+ <pre class="code-panel__pre">{{ playgroundRequestPreview }}</pre>+ </div>+ </section>++ <section class="setting-drawer__section">+ <h4 class="setting-drawer__section-title">{{ $t('integrations.api.playgroundSectionResult') }}</h4>+ <t-alert v-if="playground.error" theme="error" :message="playground.error" />++ <div v-if="hasPlaygroundResult" class="playground-results">+ <div v-if="form.mode === 'signed_token' && playground.signed_token" class="playground-step">+ <div class="playground-step__header">+ <span>{{ $t('integrations.api.playgroundGeneratedToken') }}</span>+ <t-button size="small" variant="text" @click="copy(playground.signed_token)">+ <template #icon><t-icon name="file-copy" /></template>+ {{ $t('integrations.api.copy') }}+ </t-button>+ </div>+ <pre>{{ playground.signed_token }}</pre>+ </div>++ <div class="playground-step">+ <div class="playground-step__header">+ <span>{{ $t('integrations.api.playgroundStepSession') }}</span>+ <t-tag size="small" :theme="playground.session_status === 'success' ? 'success' : 'default'" variant="light">+ {{ playground.session_status || '-' }}+ </t-tag>+ </div>+ <pre>{{ playground.session_response || '-' }}</pre>+ </div>++ <div class="playground-step">+ <div class="playground-step__header">+ <span>{{ $t('integrations.api.playgroundStepChat') }}</span>+ <t-tag size="small" :theme="playground.chat_status === 'success' ? 'success' : 'default'" variant="light">+ {{ playground.chat_status || '-' }}+ </t-tag>+ </div>+ <pre>{{ playground.stream_output || '-' }}</pre>+ </div>++ <div v-if="playground.final_answer" class="playground-step">+ <div class="playground-step__header">+ <span>{{ $t('integrations.api.playgroundFinalAnswer') }}</span>+ </div>+ <pre>{{ playground.final_answer }}</pre>+ </div>+ </div>+ <p v-else class="playground-empty">{{ $t('integrations.api.playgroundEmptyResult') }}</p>+ </section>+ </SettingDrawer></div></template><script setup lang="ts">-import { computed, onMounted, reactive, ref, watch } from 'vue'-import { MessagePlugin } from 'tdesign-vue-next'+import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'+import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'import { useI18n } from 'vue-i18n'import { getCurrentUser } from '@/api/auth'+import { listAgents, BUILTIN_SMART_REASONING_ID, type CustomAgent } from '@/api/agent'+import SettingDrawer from '@/components/settings/SettingDrawer.vue'import {+ createAPIPrincipalTestToken,getAPIPrincipalConfig,updateAPIPrincipalConfig,type APIPrincipalConfig,@@ -152,6 +319,9 @@ import { getApiBaseUrl } from '@/utils/api-base'const { t } = useI18n()+const DEFAULT_DIRECT_HEADER_NAME = 'X-External-User-ID'+const DEFAULT_TOKEN_HEADER_NAME = 'X-External-User-Token'+const loading = ref(true)const saving = ref(false)const error = ref('')@@ -160,21 +330,50 @@ const apiKey = ref('')const showApiKey = ref(false)const config = ref<APIPrincipalConfig | null>(null)const secretInput = ref('')+const savedHMACSecret = ref('')const exampleTab = ref<'jwt' | 'curl'>('curl')+const agents = ref<CustomAgent[]>([])+const agentsLoading = ref(false)+const agentsError = ref('')+const playgroundDrawerVisible = ref(false)+const playgroundController = ref<AbortController | null>(null)+const showHMACSecret = ref(false)const form = reactive({mode: 'tenant' as APIPrincipalMode,- direct_header_name: 'X-External-User-ID',- signed_token_header_name: 'X-External-User-Token',+ direct_header_name: DEFAULT_DIRECT_HEADER_NAME,+ signed_token_header_name: DEFAULT_TOKEN_HEADER_NAME,require_direct_header: false,})+type PlaygroundStatus = '' | 'running' | 'success' | 'failed' | 'stopped'++const playground = reactive({+ agent_id: '',+ query: 'hello',+ external_user_id: 'user_123',+ signed_token: '',+ running: false,+ session_status: '' as PlaygroundStatus,+ chat_status: '' as PlaygroundStatus,+ session_response: '',+ stream_output: '',+ final_answer: '',+ error: '',+})+watch(() => form.mode, (mode) => {if (mode === 'signed_token') {exampleTab.value = 'curl'}})+watch(playgroundDrawerVisible, (visible) => {+ if (!visible) {+ stopPlayground()+ }+})+const apiBaseUrl = computed(() => {const configured = getApiBaseUrl().trim().replace(/\/$/, '')const origin = typeof window !== 'undefined' && window.location.origin !== 'null' ? window.location.origin : ''@@ -187,17 +386,78 @@ const displayApiKey = computed(() => {return '•'.repeat(apiKey.value.length)})-const canSave = computed(() => {+const tokenHeaderName = computed(() => DEFAULT_TOKEN_HEADER_NAME)++const directHeaderName = computed(() => DEFAULT_DIRECT_HEADER_NAME)++const canAutoSave = computed(() => {if (!tenantId.value) return falseif (form.mode === 'signed_token') {- return config.value?.has_hmac_secret === true || secretInput.value.trim() !== ''+ return secretInput.value.trim() !== ''}return true})+const agentOptions = computed(() => agents.value.map((agent) => ({+ label: `${agent.name}${agent.is_builtin ? ` · ${t('integrations.api.playgroundBuiltin')}` : ''}`,+ value: agent.id,+})))++const hasUnsavedPrincipalChanges = computed(() => {+ const cfg = config.value+ if (!cfg) return false+ return (+ form.mode !== cfg.mode+ || form.require_direct_header !== cfg.require_direct_header+ || secretInput.value.trim() !== savedHMACSecret.value.trim()+ )+})++const externalUserHint = computed(() => {+ if (form.mode === 'tenant') return t('integrations.api.playgroundTenantModeHint')+ if (form.mode === 'direct_header') {+ return t('integrations.api.playgroundDirectModeHint', { headerName: directHeaderName.value })+ }+ return t('integrations.api.playgroundSignedModeHint', { headerName: tokenHeaderName.value })+})++const playgroundRequestPreview = computed(() => {+ const body = {+ query: playground.query || '<query>',+ agent_enabled: true,+ agent_id: playground.agent_id || '<agent_id>',+ channel: 'api',+ }+ const headers = buildPlaygroundHeaders(true)+ return [+ 'POST /api/v1/sessions',+ JSON.stringify({ headers: headers.sessionHeaders, body: {} }, null, 2),+ '',+ 'POST /api/v1/agent-chat/<session_id>',+ JSON.stringify({ headers: headers.chatHeaders, body }, null, 2),+ ].join('\n')+})++const playgroundDisabledReason = computed(() => {+ if (playground.running) return ''+ if (!apiKey.value) return t('integrations.api.playgroundNeedApiKey')+ if (!playground.agent_id) return t('integrations.api.playgroundNeedAgent')+ if (!playground.query.trim()) return t('integrations.api.playgroundNeedQuestion')+ if (form.mode === 'signed_token' && !playground.external_user_id.trim()) {+ return t('integrations.api.playgroundNeedExternalUser')+ }+ return ''+})++const canRunPlayground = computed(() => !playground.running && !playgroundDisabledReason.value)++const hasPlaygroundResult = computed(() => Boolean(+ playground.signed_token || playground.session_response || playground.stream_output || playground.final_answer,+))+const tokenSignExample = computed(() => {const tid = tenantId.value || 10000- const headerName = form.signed_token_header_name.trim() || 'X-External-User-Token'+ const headerName = tokenHeaderName.valuereturn `import ("time"@@ -224,20 +484,20 @@ const requestExample = computed(() => {const apiKeyHeader = ` -H "X-API-Key: ${apiKey.value ? '<API_KEY>' : '<YOUR_API_KEY>'}"`const contentType = ' -H "Content-Type: application/json"'const principalHeaders: string[] = []- const tokenHeaderName = form.signed_token_header_name.trim() || 'X-External-User-Token'if (form.mode === 'direct_header') {- principalHeaders.push(` -H "${form.direct_header_name || 'X-External-User-ID'}: user_123"`)+ principalHeaders.push(` -H "${directHeaderName.value}: user_123"`)}if (form.mode === 'signed_token') {- principalHeaders.push(` -H "${tokenHeaderName}: ${t('integrations.api.requestExampleJwtPlaceholder')}"`)+ principalHeaders.push(` -H "${tokenHeaderName.value}: ${t('integrations.api.requestExampleJwtPlaceholder')}"`)}const commonHeaders = [apiKeyHeader, contentType, ...principalHeaders].join(' \\\n')+ const agentID = playground.agent_id || BUILTIN_SMART_REASONING_IDconst lines: string[] = []if (form.mode === 'signed_token') {lines.push(t('integrations.api.signedRequestStep0', { tenantId: tenantId.value || '<tenant_id>' }),- t('integrations.api.signedRequestStep0Hint', { headerName: tokenHeaderName }),+ t('integrations.api.signedRequestStep0Hint', { headerName: tokenHeaderName.value }),'',)}@@ -250,7 +510,7 @@ const requestExample = computed(() => {t('integrations.api.requestExampleAgentChat'),`curl -N -X POST ${apiBaseUrl.value}/agent-chat/<session_id> \\`,commonHeaders,- ` -d '{"query":"hello"}'`,+ ` -d '{"query":"hello","agent_enabled":true,"agent_id":"${agentID}","channel":"api"}'`,)return lines.join('\n')})@@ -271,7 +531,10 @@ async function load() {loading.value = trueerror.value = ''try {- const userResp = await getCurrentUser()+ const [userResp] = await Promise.all([+ getCurrentUser(),+ loadAgents(),+ ])const tenant = (userResp as any)?.data?.tenantif (!tenant?.id) {throw new Error(t('integrations.api.loadFailed'))@@ -285,10 +548,12 @@ async function load() {}config.value = cfgResp.dataform.mode = cfgResp.data.mode || 'tenant'- form.direct_header_name = cfgResp.data.direct_header_name || 'X-External-User-ID'- form.signed_token_header_name = cfgResp.data.signed_token_header_name || 'X-External-User-Token'+ form.direct_header_name = DEFAULT_DIRECT_HEADER_NAME+ form.signed_token_header_name = DEFAULT_TOKEN_HEADER_NAMEform.require_direct_header = cfgResp.data.require_direct_header === true- secretInput.value = ''+ savedHMACSecret.value = cfgResp.data.hmac_secret || ''+ secretInput.value = savedHMACSecret.value+ ensurePlaygroundAgent()} catch (err: any) {error.value = err?.message || t('integrations.api.loadFailed')} finally {@@ -296,23 +561,87 @@ async function load() {}}-function generateSecret() {+async function loadAgents() {+ agentsLoading.value = true+ agentsError.value = ''+ try {+ const resp = await listAgents({ creator: 'all' }) as any+ agents.value = Array.isArray(resp?.data) ? resp.data : []+ ensurePlaygroundAgent()+ } catch (err: any) {+ agentsError.value = err?.message || t('integrations.api.playgroundAgentsLoadFailed')+ } finally {+ agentsLoading.value = false+ }+}++function ensurePlaygroundAgent() {+ if (playground.agent_id && agents.value.some((agent) => agent.id === playground.agent_id)) return+ const smartReasoning = agents.value.find((agent) => agent.id === BUILTIN_SMART_REASONING_ID)+ playground.agent_id = smartReasoning?.id || agents.value[0]?.id || ''+}++function openPlaygroundDrawer() {+ ensurePlaygroundAgent()+ playgroundDrawerVisible.value = true+}++function handlePlaygroundDrawerCancel() {+ stopPlayground()+ playgroundDrawerVisible.value = false+}++function handlePrincipalModeChange(mode: APIPrincipalMode) {+ form.mode = mode+ void saveIfNeeded()+}++function handleRequireDirectHeaderChange(checked: boolean) {+ form.require_direct_header = checked+ void saveIfNeeded()+}++function triggerAutoSave() {+ void saveIfNeeded()+}++function confirmGenerateSecret() {+ const dialog = DialogPlugin.confirm({+ header: t('integrations.api.hmacSecretResetConfirmTitle'),+ body: t('integrations.api.hmacSecretResetConfirmBody'),+ confirmBtn: { content: t('integrations.api.hmacSecretResetConfirmOk'), theme: 'danger' },+ cancelBtn: t('integrations.api.hmacSecretResetConfirmCancel'),+ onConfirm: async () => {+ await generateSecret()+ dialog.destroy()+ },+ onClose: () => dialog.destroy(),+ })+}++async function generateSecret() {const bytes = new Uint8Array(32)window.crypto.getRandomValues(bytes)secretInput.value = btoa(String.fromCharCode(...bytes))+ showHMACSecret.value = true+ await saveIfNeeded({ showSuccess: true })}-async function save() {- if (!tenantId.value) return+async function saveIfNeeded(options: { showSuccess?: boolean } = {}) {+ if (!hasUnsavedPrincipalChanges.value) return true+ if (!canAutoSave.value) {+ MessagePlugin.error(t('integrations.api.autoSaveNeedSecret'))+ return false+ }saving.value = truetry {const payload: Parameters<typeof updateAPIPrincipalConfig>[1] = {mode: form.mode,- direct_header_name: form.direct_header_name.trim(),- signed_token_header_name: form.signed_token_header_name.trim(),+ direct_header_name: DEFAULT_DIRECT_HEADER_NAME,+ signed_token_header_name: DEFAULT_TOKEN_HEADER_NAME,require_direct_header: form.require_direct_header,}- if (secretInput.value.trim()) {+ if (secretInput.value.trim() !== savedHMACSecret.value.trim()) {payload.hmac_secret = secretInput.value.trim()}const resp = await updateAPIPrincipalConfig(tenantId.value, payload)@@ -320,10 +649,15 @@ async function save() {throw new Error(resp.message || t('integrations.api.saveFailed'))}config.value = resp.data- secretInput.value = ''- MessagePlugin.success(t('integrations.api.saveSuccess'))+ savedHMACSecret.value = resp.data.hmac_secret || payload.hmac_secret || ''+ secretInput.value = savedHMACSecret.value+ if (options.showSuccess) {+ MessagePlugin.success(t('integrations.api.saveSuccess'))+ }+ return true} catch (err: any) {MessagePlugin.error(err?.message || t('integrations.api.saveFailed'))+ return false} finally {saving.value = false}@@ -335,7 +669,185 @@ async function copy(text: string) {MessagePlugin.success(t('integrations.api.copySuccess'))}+function buildPlaygroundHeaders(maskSecrets: boolean) {+ const commonHeaders: Record<string, string> = {+ Accept: 'application/json',+ 'Content-Type': 'application/json',+ 'X-API-Key': maskSecrets ? '<API_KEY>' : apiKey.value,+ }+ if (form.mode === 'direct_header' && playground.external_user_id.trim()) {+ commonHeaders[directHeaderName.value] = playground.external_user_id.trim()+ }+ if (form.mode === 'signed_token') {+ commonHeaders[tokenHeaderName.value] = maskSecrets ? '<JWT>' : playground.signed_token.trim()+ }+ return {+ sessionHeaders: commonHeaders,+ chatHeaders: { ...commonHeaders, Accept: 'text/event-stream' },+ }+}++function compactText(text: string, max = 12000) {+ if (text.length <= max) return text+ return `${text.slice(0, max)}\n...`+}++function formatJSON(value: unknown) {+ try {+ return compactText(JSON.stringify(value, null, 2))+ } catch {+ return String(value)+ }+}++function extractAnswerFromSSE(raw: string) {+ const chunks: string[] = []+ raw.split('\n').forEach((line) => {+ if (!line.startsWith('data:')) return+ const payload = line.slice(5).trim()+ if (!payload || payload === '[DONE]') return+ try {+ const parsed = JSON.parse(payload)+ const type = parsed?.response_type || parsed?.type+ const content = parsed?.content+ if (type === 'answer' && typeof content === 'string') {+ chunks.push(content)+ }+ } catch {+ // Keep raw stream visible even when an event is not JSON.+ }+ })+ return chunks.join('')+}++async function readResponseBody(resp: Response) {+ const text = await resp.text()+ if (!text) return ''+ try {+ return formatJSON(JSON.parse(text))+ } catch {+ return compactText(text)+ }+}++async function ensurePlaygroundSignedToken() {+ if (form.mode !== 'signed_token') return+ if (!tenantId.value) throw new Error(t('integrations.api.loadFailed'))+ const resp = await createAPIPrincipalTestToken(tenantId.value, {+ external_user_id: playground.external_user_id.trim(),+ expires_in_seconds: 900,+ })+ if (!resp.success || !resp.data?.token) {+ throw new Error(resp.message || t('integrations.api.playgroundMintTokenFailed'))+ }+ playground.signed_token = resp.data.token+}++async function runPlayground() {+ if (!canRunPlayground.value) return+ const controller = new AbortController()+ playgroundController.value = controller+ playground.running = true+ playground.error = ''+ playground.session_status = 'running'+ playground.chat_status = ''+ playground.session_response = ''+ playground.stream_output = ''+ playground.final_answer = ''+ playground.signed_token = ''++ const startedAt = performance.now()+ try {+ await ensurePlaygroundSignedToken()+ const headers = buildPlaygroundHeaders(false).sessionHeaders+ const sessionResp = await fetch(`${apiBaseUrl.value}/sessions`, {+ method: 'POST',+ headers,+ body: '{}',+ signal: controller.signal,+ credentials: 'omit',+ })+ const sessionRaw = await sessionResp.text()+ let sessionPayload: any = null+ try {+ sessionPayload = sessionRaw ? JSON.parse(sessionRaw) : null+ } catch {+ sessionPayload = null+ }+ playground.session_response = sessionPayload ? formatJSON(sessionPayload) : compactText(sessionRaw)+ if (!sessionResp.ok || sessionPayload?.success === false) {+ playground.session_status = 'failed'+ throw new Error(sessionPayload?.message || sessionPayload?.error?.message || `HTTP ${sessionResp.status}`)+ }+ playground.session_status = 'success'+ const sessionID = sessionPayload?.data?.id || sessionPayload?.data?.ID+ if (!sessionID) {+ throw new Error(t('integrations.api.playgroundMissingSessionId'))+ }++ playground.chat_status = 'running'+ const chatResp = await fetch(`${apiBaseUrl.value}/agent-chat/${encodeURIComponent(sessionID)}`, {+ method: 'POST',+ headers: buildPlaygroundHeaders(false).chatHeaders,+ body: JSON.stringify({+ query: playground.query.trim(),+ agent_enabled: true,+ agent_id: playground.agent_id,+ channel: 'api',+ }),+ signal: controller.signal,+ credentials: 'omit',+ })+ if (!chatResp.ok) {+ playground.chat_status = 'failed'+ const body = await readResponseBody(chatResp)+ playground.stream_output = body+ throw new Error(body || `HTTP ${chatResp.status}`)+ }+ if (!chatResp.body) {+ throw new Error(t('integrations.api.playgroundNoStream'))+ }++ const reader = chatResp.body.getReader()+ const decoder = new TextDecoder()+ let raw = ''+ while (true) {+ const { done, value } = await reader.read()+ if (done) break+ raw += decoder.decode(value, { stream: true })+ playground.stream_output = compactText(raw)+ playground.final_answer = extractAnswerFromSSE(raw)+ }+ raw += decoder.decode()+ playground.stream_output = compactText(raw)+ playground.final_answer = extractAnswerFromSSE(raw)+ playground.chat_status = 'success'+ MessagePlugin.success(t('integrations.api.playgroundSuccess', {+ ms: Math.round(performance.now() - startedAt),+ }))+ } catch (err: any) {+ const aborted = err?.name === 'AbortError'+ if (aborted) {+ if (playground.session_status === 'running') playground.session_status = 'stopped'+ if (playground.chat_status === 'running') playground.chat_status = 'stopped'+ playground.error = t('integrations.api.playgroundStopped')+ } else {+ if (playground.session_status === 'running') playground.session_status = 'failed'+ if (playground.chat_status === 'running') playground.chat_status = 'failed'+ playground.error = err?.message || t('integrations.api.playgroundFailed')+ }+ } finally {+ playground.running = false+ playgroundController.value = null+ }+}++function stopPlayground() {+ playgroundController.value?.abort()+}+onMounted(load)+onBeforeUnmount(stopPlayground)</script><style scoped lang="less">@@ -408,64 +920,131 @@ onMounted(load).mode-detail {display: flex;flex-direction: column;- gap: 16px;+ gap: 12px;width: 100%;- max-width: 640px;+ max-width: 760px;}-.mode-hint {- margin: 0;- padding: 10px 12px;+.mode-callout {+ position: relative;+ padding: 12px 14px;border-radius: 8px;border: 1px solid var(--td-component-stroke);background: var(--td-bg-color-secondarycontainer);- color: var(--td-text-color-secondary);- font-size: 13px;- line-height: 1.55;+ overflow: hidden;++ &--warning {+ border-color: var(--td-warning-color-3);+ background: var(--td-warning-color-1);+ }- &__title {+ &__body {display: block;- margin-bottom: 4px;- color: var(--td-text-color-primary);- font-weight: 500;++ strong {+ display: block;+ margin-bottom: 5px;+ color: var(--td-text-color-primary);+ font-size: 13px;+ font-weight: 600;+ line-height: 1.4;+ }++ margin: 0;+ p {+ margin: 0;+ color: var(--td-text-color-secondary);+ font-size: 12px;+ line-height: 1.6;+ }}}-.form-grid {+.principal-config {display: flex;flex-direction: column;+ border: 1px solid var(--td-component-stroke);+ border-radius: 8px;+ background: var(--td-bg-color-container);+ overflow: hidden;+}++.config-row {+ display: grid;+ grid-template-columns: minmax(180px, 1fr) auto;+ align-items: center;gap: 16px;+ padding: 14px 16px;++ & + & {+ border-top: 1px solid var(--td-component-stroke);+ }++ &__text {+ min-width: 0;++ label {+ display: block;+ color: var(--td-text-color-primary);+ font-size: 13px;+ font-weight: 600;+ line-height: 1.4;+ }++ p {+ margin: 5px 0 0;+ color: var(--td-text-color-placeholder);+ font-size: 12px;+ line-height: 1.5;+ }+ }++ &__action {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ min-width: 52px;+ }++ &--switch {+ align-items: flex-start;+ }++ &--secret {+ grid-template-columns: minmax(220px, 0.55fr) minmax(360px, 1fr);+ align-items: center;+ }}-.form-item {+.secret-control {display: flex;- flex-direction: column;- gap: 6px;+ align-items: center;+ gap: 8px;min-width: 0;- &__label {- color: var(--td-text-color-primary);- font-size: 13px;- font-weight: 500;+ .mono-input {+ flex: 1 1 auto;+ min-width: 0;}- &__control {- display: flex;- align-items: flex-start;- gap: 10px;+ :deep(.t-button) {+ flex: 0 0 auto;}+}- &__hint {- margin: 0;- color: var(--td-text-color-placeholder);- font-size: 12px;- line-height: 1.5;+@media (max-width: 640px) {+ .config-row {+ grid-template-columns: 1fr;+ align-items: stretch;+ gap: 10px;++ &__action {+ justify-content: flex-start;+ }}- &--switch .form-item__control {- flex-direction: column;- align-items: flex-start;- gap: 6px;+ .fixed-header-name {+ width: 100%;}}@@ -545,17 +1124,141 @@ onMounted(load)}}-.actions {- display: flex;- justify-content: flex-end;- margin-top: 4px;- padding-top: 16px;- border-top: 1px solid var(--td-component-stroke);+.mono-input :deep(input) {+ font-family: var(--app-font-family-mono);+ font-size: 12px;}-.mono-input :deep(input) {+.fixed-header-name {+ width: fit-content;+ max-width: 100%;+ padding: 7px 10px;+ border: 1px solid var(--td-component-stroke);+ border-radius: 6px;+ background: var(--td-bg-color-secondarycontainer);+ color: var(--td-text-color-primary);font-family: var(--app-font-family-mono);font-size: 12px;+ line-height: 18px;+ overflow-wrap: anywhere;+}++.mono-textarea :deep(.t-textarea__inner) {+ font-family: var(--app-font-family-mono);+ font-size: 12px;+}++.playground-entry {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ padding: 12px 14px;+ border: 1px solid var(--td-component-stroke);+ border-radius: 8px;+ background: var(--td-bg-color-secondarycontainer);++ &__info {+ min-width: 0;++ label {+ display: block;+ margin-bottom: 4px;+ color: var(--td-text-color-primary);+ font-size: 13px;+ font-weight: 500;+ }++ p {+ margin: 0;+ color: var(--td-text-color-secondary);+ font-size: 12px;+ line-height: 1.5;+ }+ }+}++.playground-preview {+ width: 100%;+}++.drawer-form-item {+ display: flex;+ flex-direction: column;+ gap: 6px;+ min-width: 0;+}++.drawer-form-label {+ display: block;+ color: var(--td-text-color-primary);+ font-size: 13px;+ font-weight: 500;+ line-height: 1.4;+}++.drawer-form-desc {+ margin: 0;+ color: var(--td-text-color-placeholder);+ font-size: 12px;+ line-height: 1.5;++ &--error {+ color: var(--td-error-color);+ }+}++.footer-test-message {+ min-width: 0;+ color: var(--td-text-color-placeholder);+ font-size: 12px;+ line-height: 1.4;+}++.playground-empty {+ margin: 0;+ color: var(--td-text-color-placeholder);+ font-size: 12px;+ line-height: 1.6;+}++.playground-results {+ display: grid;+ grid-template-columns: 1fr;+ gap: 12px;+}++.playground-step {+ border: 1px solid var(--td-component-stroke);+ border-radius: 8px;+ background: var(--td-bg-color-secondarycontainer);+ overflow: hidden;++ &__header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ padding: 8px 10px;+ border-bottom: 1px solid var(--td-component-stroke);+ background: var(--td-bg-color-container);+ color: var(--td-text-color-secondary);+ font-size: 12px;+ font-weight: 500;+ }++ pre {+ max-height: 240px;+ margin: 0;+ padding: 10px 12px;+ overflow: auto;+ color: var(--td-text-color-primary);+ font-family: var(--app-font-family-mono);+ font-size: 12px;+ line-height: 1.5;+ white-space: pre-wrap;+ word-break: break-word;+ }}@media (max-width: 780px) {@@ -580,6 +1283,11 @@ onMounted(load).mode-detail {max-width: none;}++ .playground-entry {+ flex-direction: column;+ align-items: stretch;+ }}.row-info {diff --git a/internal/handler/tenant.go b/internal/handler/tenant.goindex 879f42d63..c00592957 100644--- a/internal/handler/tenant.go+++ b/internal/handler/tenant.go@@ -5,8 +5,10 @@ import ("net/http""strconv""strings"+ "time""github.com/gin-gonic/gin"+ "github.com/golang-jwt/jwt/v5""github.com/Tencent/WeKnora/internal/config""github.com/Tencent/WeKnora/internal/errors"@@ -110,11 +112,28 @@ type apiPrincipalConfigResponse struct {SignedTokenHeaderName string `json:"signed_token_header_name"`RequireDirectHeader bool `json:"require_direct_header"`HasHMACSecret bool `json:"has_hmac_secret"`+ HMACSecret string `json:"hmac_secret,omitempty"`+}++type apiPrincipalTestTokenRequest struct {+ ExternalUserID string `json:"external_user_id"`+ ExpiresInSeconds int `json:"expires_in_seconds"`+}++type apiPrincipalTestTokenResponse struct {+ Token string `json:"token"`+ HeaderName string `json:"header_name"`+ ExpiresInSeconds int `json:"expires_in_seconds"`+ ExpiresAtUnix int64 `json:"expires_at_unix"`+ ExternalUserID string `json:"external_user_id"`}const (- defaultAPIPrincipalDirectHeader = "X-External-User-ID"- defaultAPIPrincipalTokenHeader = "X-External-User-Token"+ defaultAPIPrincipalDirectHeader = "X-External-User-ID"+ defaultAPIPrincipalTokenHeader = "X-External-User-Token"+ defaultAPIPrincipalTestTokenTTL = 15 * time.Minute+ maxAPIPrincipalTestTokenTTL = time.Hour+ maxAPIPrincipalExternalUserIDLen = 128)// defaultMaxOwnedTenantsPerUser is the cap applied when@@ -539,20 +558,13 @@ func apiPrincipalConfigForResponse(cfg *types.APIPrincipalConfig) apiPrincipalCoif mode == "" {mode = types.APIPrincipalModeTenant}- directHeader := strings.TrimSpace(cfg.DirectHeaderName)- if directHeader == "" {- directHeader = defaultAPIPrincipalDirectHeader- }- tokenHeader := strings.TrimSpace(cfg.SignedTokenHeaderName)- if tokenHeader == "" {- tokenHeader = defaultAPIPrincipalTokenHeader- }return apiPrincipalConfigResponse{Mode: mode,- DirectHeaderName: directHeader,- SignedTokenHeaderName: tokenHeader,+ DirectHeaderName: defaultAPIPrincipalDirectHeader,+ SignedTokenHeaderName: defaultAPIPrincipalTokenHeader,RequireDirectHeader: cfg.RequireDirectHeader,HasHMACSecret: strings.TrimSpace(cfg.HMACSecret) != "",+ HMACSecret: strings.TrimSpace(cfg.HMACSecret),}}@@ -645,17 +657,11 @@ func (h *TenantHandler) UpdateAPIPrincipalConfig(c *gin.Context) {}cfg := &types.APIPrincipalConfig{Mode: req.Mode,- DirectHeaderName: strings.TrimSpace(req.DirectHeaderName),- SignedTokenHeaderName: strings.TrimSpace(req.SignedTokenHeaderName),+ DirectHeaderName: defaultAPIPrincipalDirectHeader,+ SignedTokenHeaderName: defaultAPIPrincipalTokenHeader,RequireDirectHeader: req.RequireDirectHeader,HMACSecret: hmacSecret,}- if cfg.DirectHeaderName == "" {- cfg.DirectHeaderName = defaultAPIPrincipalDirectHeader- }- if cfg.SignedTokenHeaderName == "" {- cfg.SignedTokenHeaderName = defaultAPIPrincipalTokenHeader- }if cfg.Mode == types.APIPrincipalModeSignedToken && strings.TrimSpace(cfg.HMACSecret) == "" {c.Error(errors.NewValidationError("hmac_secret is required for signed_token mode"))return@@ -677,6 +683,110 @@ func (h *TenantHandler) UpdateAPIPrincipalConfig(c *gin.Context) {})}+// CreateAPIPrincipalTestToken godoc+// @Summary 生成 API Playground 测试 JWT+// @Description 使用租户已保存的 HMAC 密钥签发短期外部用户 JWT(Owner)+// @Tags 租户管理+// @Accept json+// @Produce json+// @Param id path int true "租户ID"+// @Param request body handler.apiPrincipalTestTokenRequest true "测试 Token 参数"+// @Success 200 {object} map[string]interface{} "短期 JWT"+// @Failure 400 {object} errors.AppError "请求参数错误"+// @Failure 403 {object} errors.AppError "权限不足"+// @Security Bearer+// @Router /tenants/{id}/api-principal-test-token [post]+func (h *TenantHandler) CreateAPIPrincipalTestToken(c *gin.Context) {+ ctx := c.Request.Context()+ id, err := strconv.ParseUint(c.Param("id"), 10, 64)+ if err != nil {+ c.Error(errors.NewBadRequestError("Invalid tenant ID"))+ return+ }++ var req apiPrincipalTestTokenRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ c.Error(errors.NewValidationError("Invalid request data").WithDetails(err.Error()))+ return+ }++ externalUserID := strings.TrimSpace(req.ExternalUserID)+ if err := validateAPIPrincipalExternalUserID(externalUserID); err != nil {+ c.Error(errors.NewValidationError("external_user_id is invalid").WithDetails(err.Error()))+ return+ }++ tenant, err := h.service.GetTenantByID(ctx, id)+ if err != nil {+ if appErr, ok := errors.IsAppError(err); ok {+ c.Error(appErr)+ } else {+ c.Error(errors.NewInternalServerError("Failed to load tenant").WithDetails(err.Error()))+ }+ return+ }++ cfg := tenant.APIPrincipalConfig+ if cfg == nil || cfg.Mode != types.APIPrincipalModeSignedToken {+ c.Error(errors.NewValidationError("signed_token mode is required"))+ return+ }+ secret := strings.TrimSpace(cfg.HMACSecret)+ if secret == "" {+ c.Error(errors.NewValidationError("hmac_secret is required for signed_token mode"))+ return+ }++ ttl := defaultAPIPrincipalTestTokenTTL+ if req.ExpiresInSeconds > 0 {+ ttl = time.Duration(req.ExpiresInSeconds) * time.Second+ }+ if ttl <= 0 || ttl > maxAPIPrincipalTestTokenTTL {+ c.Error(errors.NewValidationError("expires_in_seconds must be between 1 and 3600"))+ return+ }++ now := time.Now()+ expiresAt := now.Add(ttl)+ token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{+ "sub": externalUserID,+ "tenant_id": strconv.FormatUint(id, 10),+ "aud": "weknora",+ "iat": now.Unix(),+ "exp": expiresAt.Unix(),+ }).SignedString([]byte(secret))+ if err != nil {+ c.Error(errors.NewInternalServerError("Failed to create API principal test token").WithDetails(err.Error()))+ return+ }++ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "data": apiPrincipalTestTokenResponse{+ Token: token,+ HeaderName: defaultAPIPrincipalTokenHeader,+ ExpiresInSeconds: int(ttl.Seconds()),+ ExpiresAtUnix: expiresAt.Unix(),+ ExternalUserID: externalUserID,+ },+ })+}++func validateAPIPrincipalExternalUserID(id string) error {+ if id == "" {+ return errors.NewValidationError("external_user_id is required")+ }+ if len(id) > maxAPIPrincipalExternalUserIDLen {+ return errors.NewValidationError("external_user_id is too long")+ }+ for _, r := range id {+ if r < 0x20 || r == 0x7f {+ return errors.NewValidationError("external_user_id contains invalid characters")+ }+ }+ return nil+}+// DeleteTenant godoc// @Summary 删除租户// @Description 删除指定的租户diff --git a/internal/middleware/auth.go b/internal/middleware/auth.goindex cd37059be..e18b99c9d 100644--- a/internal/middleware/auth.go+++ b/internal/middleware/auth.go@@ -324,11 +324,7 @@ func resolveAPIPrincipal(ctx context.Context, tenant *types.Tenant, header http.}switch cfg.Mode {case types.APIPrincipalModeDirect:- name := strings.TrimSpace(cfg.DirectHeaderName)- if name == "" {- name = defaultExternalUserIDHeader- }- externalUserID := strings.TrimSpace(header.Get(name))+ externalUserID := strings.TrimSpace(header.Get(defaultExternalUserIDHeader))if externalUserID == "" {if cfg.RequireDirectHeader {return types.Principal{}, errMissingDirectHeader@@ -343,11 +339,7 @@ func resolveAPIPrincipal(ctx context.Context, tenant *types.Tenant, header http.ID: strconv.FormatUint(tenantID, 10) + ":" + externalUserID,}, nilcase types.APIPrincipalModeSignedToken:- name := strings.TrimSpace(cfg.SignedTokenHeaderName)- if name == "" {- name = defaultExternalUserTokenHeader- }- externalUserID, err := verifyExternalUserJWT(header.Get(name), tenantID, cfg.HMACSecret)+ externalUserID, err := verifyExternalUserJWT(header.Get(defaultExternalUserTokenHeader), tenantID, cfg.HMACSecret)if err != nil || externalUserID == "" {logger.Warnf(ctx, "invalid external user token for tenant=%d: %v", tenantID, err)return types.Principal{}, fmt.Errorf("%w: %w", errInvalidExternalUserToken, err)diff --git a/internal/router/router.go b/internal/router/router.goindex e1a6b6055..4e9176da6 100644--- a/internal/router/router.go+++ b/internal/router/router.go@@ -107,7 +107,7 @@ func NewRouter(params RouterParams) *gin.Engine {r.Use(cors.New(cors.Config{AllowOrigins: []string{"*"},AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},- AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization", "X-API-Key", "X-Request-ID", "X-Tenant-ID", "X-Embed-Session"},+ AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization", "X-API-Key", "X-Request-ID", "X-Tenant-ID", "X-Embed-Session", "X-External-User-ID", "X-External-User-Token"},ExposeHeaders: []string{"Content-Length", "Access-Control-Allow-Origin"},AllowCredentials: true,MaxAge: 12 * time.Hour,@@ -573,6 +573,7 @@ func RegisterTenantRoutes(tenantByID.POST("/api-key", g.Owner(), handler.ResetAPIKey)tenantByID.GET("/api-principal-config", g.Owner(), handler.GetAPIPrincipalConfig)tenantByID.PUT("/api-principal-config", g.Owner(), handler.UpdateAPIPrincipalConfig)+ tenantByID.POST("/api-principal-test-token", g.Owner(), handler.CreateAPIPrincipalTestToken)// Tenant member management (PR 3 of #1303). Listing is// Viewer+ so any active member can see the roster; mutation