feat(im): add per-channel reply locale (#3455)
parent
ad20ea9c9b
commit
b86821f551
|
|
@ -316,6 +316,7 @@ export interface IMChannel {
|
|||
enabled: boolean;
|
||||
mode: 'webhook' | 'websocket' | 'longpoll';
|
||||
output_mode: 'stream' | 'full';
|
||||
locale?: '' | 'zh-CN' | 'en-US' | 'ko-KR' | 'ja-JP' | 'ru-RU';
|
||||
session_mode?: 'user' | 'thread';
|
||||
knowledge_base_id?: string;
|
||||
credentials: Record<string, any>;
|
||||
|
|
@ -339,6 +340,7 @@ export interface IMChannelOverview {
|
|||
enabled: boolean;
|
||||
mode: IMChannel['mode'];
|
||||
output_mode: IMChannel['output_mode'];
|
||||
locale?: IMChannel['locale'];
|
||||
session_mode?: IMChannel['session_mode'];
|
||||
bot_identity: string;
|
||||
created_at: string;
|
||||
|
|
|
|||
|
|
@ -205,6 +205,12 @@
|
|||
</div>
|
||||
<p class="form-desc">{{ $t('agentEditor.im.sessionModeHint') }}</p>
|
||||
</div>
|
||||
|
||||
<div class="form-item">
|
||||
<label class="form-label">{{ $t('agentEditor.im.replyLanguage') }}</label>
|
||||
<t-select v-model="formData.locale" :options="localeOptions" />
|
||||
<p class="form-desc">{{ $t('agentEditor.im.replyLanguageHint') }}</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-if="editingChannel && formData.mode === 'webhook'"
|
||||
|
|
@ -608,6 +614,7 @@ import qqbotLogo from '@/assets/img/im/qqbot.png';
|
|||
import yunzhijiaLogo from '@/assets/img/im/yunzhijia.svg';
|
||||
|
||||
type IMPlatform = IMChannel['platform'];
|
||||
type IMLocale = NonNullable<IMChannel['locale']>;
|
||||
|
||||
const PLATFORM_LOGO: Record<string, string> = {
|
||||
wecom: wecomLogo,
|
||||
|
|
@ -674,6 +681,15 @@ const platformOptions = computed(() => ([
|
|||
{ value: 'yunzhijia' as IMPlatform, label: t('agentEditor.im.yunzhijia'), logo: yunzhijiaLogo },
|
||||
]));
|
||||
|
||||
const localeOptions = computed(() => ([
|
||||
{ value: '' as IMLocale, label: t('agentEditor.im.replyLanguageDefault') },
|
||||
{ value: 'zh-CN' as IMLocale, label: '简体中文' },
|
||||
{ value: 'en-US' as IMLocale, label: 'English' },
|
||||
{ value: 'ja-JP' as IMLocale, label: '日本語' },
|
||||
{ value: 'ko-KR' as IMLocale, label: '한국어' },
|
||||
{ value: 'ru-RU' as IMLocale, label: 'Русский' },
|
||||
]));
|
||||
|
||||
// Feishu and Lark are the same product on separate clouds, so each has its own
|
||||
// open platform console. Bots must be created on the one matching the channel.
|
||||
const openPlatformConsole = computed(() =>
|
||||
|
|
@ -730,6 +746,7 @@ const formData = ref({
|
|||
name: '',
|
||||
mode: 'websocket' as 'webhook' | 'websocket' | 'longpoll',
|
||||
output_mode: 'stream' as 'stream' | 'full',
|
||||
locale: '' as IMLocale,
|
||||
session_mode: 'user' as 'user' | 'thread',
|
||||
knowledge_base_id: '',
|
||||
credentials: defaultCredentials(),
|
||||
|
|
@ -985,6 +1002,7 @@ async function editChannel(channel: IMChannel | IMChannelOverview) {
|
|||
name: fullChannel.name,
|
||||
mode: fullChannel.mode,
|
||||
output_mode: fullChannel.output_mode,
|
||||
locale: fullChannel.locale || '',
|
||||
session_mode: fullChannel.session_mode || 'user',
|
||||
knowledge_base_id: fullChannel.knowledge_base_id || '',
|
||||
credentials: { ...fullChannel.credentials },
|
||||
|
|
@ -1009,6 +1027,7 @@ function resetForm() {
|
|||
name: defaultChannelName('wecom'),
|
||||
mode: 'websocket',
|
||||
output_mode: 'stream',
|
||||
locale: '',
|
||||
session_mode: 'user',
|
||||
knowledge_base_id: '',
|
||||
credentials: defaultCredentials(),
|
||||
|
|
@ -1038,6 +1057,7 @@ async function handleSave() {
|
|||
name: resolvedChannelName(),
|
||||
mode: formData.value.mode,
|
||||
output_mode: formData.value.output_mode,
|
||||
locale: formData.value.locale,
|
||||
session_mode: formData.value.session_mode,
|
||||
knowledge_base_id: normalizeOptionalString(formData.value.knowledge_base_id),
|
||||
credentials: formData.value.credentials,
|
||||
|
|
@ -1056,6 +1076,7 @@ async function handleSave() {
|
|||
name: resolvedChannelName(),
|
||||
mode: formData.value.mode,
|
||||
output_mode: formData.value.output_mode,
|
||||
locale: formData.value.locale,
|
||||
session_mode: formData.value.session_mode,
|
||||
knowledge_base_id: normalizeOptionalString(formData.value.knowledge_base_id),
|
||||
credentials: formData.value.credentials,
|
||||
|
|
|
|||
|
|
@ -6360,6 +6360,9 @@ export default {
|
|||
sessionModeUser: 'Per User (default)',
|
||||
sessionModeThread: 'Per Thread',
|
||||
sessionModeHint: 'User mode: each person has their own conversation. Use /clear to start fresh. Thread mode: each message thread is a separate conversation. Multiple people can collaborate in the same thread.',
|
||||
replyLanguage: 'Reply Language',
|
||||
replyLanguageDefault: 'Use system default',
|
||||
replyLanguageHint: 'Fix the agent reply language for this channel. Leave unset to use the deployment default.',
|
||||
wechatScanBind: 'Scan to bind WeChat',
|
||||
wechatScanning: 'Scan the QR code with WeChat',
|
||||
wechatBindSuccess: 'WeChat bound successfully',
|
||||
|
|
|
|||
|
|
@ -6360,6 +6360,9 @@ export default {
|
|||
sessionModeUser: 'ユーザ単位(デフォルト)',
|
||||
sessionModeThread: 'スレッド単位',
|
||||
sessionModeHint: 'ユーザモード: 各ユーザが個別の会話を持ちます。/clearで新しく開始できます。スレッドモード: メッセージスレッドごとに個別の会話になります。同じスレッドで複数人が共同作業できます。',
|
||||
replyLanguage: '返信言語',
|
||||
replyLanguageDefault: 'システムのデフォルトを使用',
|
||||
replyLanguageHint: 'このチャネルでエージェントが返信する言語を固定します。未設定の場合はデプロイのデフォルト言語を使用します。',
|
||||
wechatScanBind: 'スキャンしてWeChatを連携',
|
||||
wechatScanning: 'WeChatでQRコードをスキャンしてください',
|
||||
wechatBindSuccess: 'WeChatを連携しました',
|
||||
|
|
|
|||
|
|
@ -1294,6 +1294,9 @@ export default {
|
|||
sessionModeUser: '사용자별 (기본)',
|
||||
sessionModeThread: '스레드별',
|
||||
sessionModeHint: '사용자 모드: 각 사용자별 독립 대화. /clear로 새 대화 시작. 스레드 모드: 메시지 스레드별 독립 대화. 같은 스레드에서 여러 명이 함께 대화 가능.',
|
||||
replyLanguage: '응답 언어',
|
||||
replyLanguageDefault: '시스템 기본값 사용',
|
||||
replyLanguageHint: '이 채널의 에이전트 응답 언어를 고정합니다. 설정하지 않으면 배포 기본 언어를 사용합니다.',
|
||||
wechatScanBind: 'QR 코드를 스캔하여 WeChat 연결',
|
||||
wechatScanning: 'WeChat으로 QR 코드를 스캔하세요',
|
||||
wechatBindSuccess: 'WeChat이 연결되었습니다',
|
||||
|
|
|
|||
|
|
@ -1294,6 +1294,9 @@ export default {
|
|||
sessionModeUser: 'По пользователю (по умолчанию)',
|
||||
sessionModeThread: 'По потоку',
|
||||
sessionModeHint: 'Режим пользователя: отдельный диалог для каждого пользователя. /clear для нового диалога. Режим потока: отдельный диалог для каждого потока. Несколько человек могут общаться в одном потоке.',
|
||||
replyLanguage: 'Язык ответов',
|
||||
replyLanguageDefault: 'Использовать системный язык',
|
||||
replyLanguageHint: 'Фиксирует язык ответов агента для этого канала. Если не задан, используется язык развёртывания по умолчанию.',
|
||||
wechatScanBind: 'Сканировать QR-код для привязки WeChat',
|
||||
wechatScanning: 'Отсканируйте QR-код в WeChat',
|
||||
wechatBindSuccess: 'WeChat успешно привязан',
|
||||
|
|
|
|||
|
|
@ -1296,6 +1296,9 @@ export default {
|
|||
sessionModeUser: '按用户(默认)',
|
||||
sessionModeThread: '按话题',
|
||||
sessionModeHint: '用户模式:每个用户独立对话,使用 /clear 开始新对话。话题模式:每个消息话题独立对话,同一话题中多人可协作。',
|
||||
replyLanguage: '回复语言',
|
||||
replyLanguageDefault: '跟随系统默认语言',
|
||||
replyLanguageHint: '固定该渠道的智能体回复语言;留空时使用部署的默认语言。',
|
||||
wechatScanBind: '扫码绑定微信',
|
||||
wechatScanning: '请使用微信扫描二维码',
|
||||
wechatBindSuccess: '微信绑定成功',
|
||||
|
|
|
|||
|
|
@ -52,6 +52,7 @@ var versionedSQLiteColumns = map[string][]string{
|
|||
},
|
||||
"tenant_invitations": {"token", "accepted_count"}, // 000054
|
||||
"embed_channels": {"allow_memory"}, // 000060
|
||||
"im_channels": {"locale"}, // 000030
|
||||
"mcp_oauth_tokens": {"principal_type", "principal_id"}, // 000064
|
||||
"mcp_tool_approvals": {"enabled"}, // 000091
|
||||
"message_artifacts": {"deleted_at"}, // 000107
|
||||
|
|
@ -64,7 +65,7 @@ var versionedSQLiteColumns = map[string][]string{
|
|||
}, // 000028
|
||||
}
|
||||
|
||||
const expectedSQLiteMigrationVersion = 29
|
||||
const expectedSQLiteMigrationVersion = 30
|
||||
|
||||
func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {
|
||||
repoRoot := sqliteRepoRoot(t)
|
||||
|
|
|
|||
|
|
@ -65,6 +65,7 @@ func (h *IMHandler) CreateIMChannel(c *gin.Context) {
|
|||
Name string `json:"name"`
|
||||
Mode string `json:"mode"`
|
||||
OutputMode string `json:"output_mode"`
|
||||
Locale string `json:"locale"`
|
||||
SessionMode string `json:"session_mode"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
Credentials types.JSON `json:"credentials"`
|
||||
|
|
@ -79,6 +80,11 @@ func (h *IMHandler) CreateIMChannel(c *gin.Context) {
|
|||
c.JSON(http.StatusBadRequest, gin.H{"error": invalidIMPlatformError})
|
||||
return
|
||||
}
|
||||
locale, err := normalizeIMLocale(req.Locale)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
channel := &im.IMChannel{
|
||||
TenantID: tenantID,
|
||||
|
|
@ -87,6 +93,7 @@ func (h *IMHandler) CreateIMChannel(c *gin.Context) {
|
|||
Name: req.Name,
|
||||
Mode: req.Mode,
|
||||
OutputMode: req.OutputMode,
|
||||
Locale: locale,
|
||||
SessionMode: req.SessionMode,
|
||||
Credentials: req.Credentials,
|
||||
Enabled: true,
|
||||
|
|
@ -183,12 +190,12 @@ func (h *IMHandler) ListAllIMChannels(c *gin.Context) {
|
|||
//
|
||||
// UpdateIMChannel godoc
|
||||
// @Summary 更新 IM 渠道
|
||||
// @Description 更新指定 IM 渠道的名称、模式、知识库、凭证或启用状态
|
||||
// @Description 更新指定 IM 渠道的名称、模式、回复语言、知识库、凭证或启用状态
|
||||
// @Tags IM 渠道
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "渠道 ID"
|
||||
// @Param request body map[string]interface{} true "更新字段(name/mode/output_mode/knowledge_base_id/credentials/enabled)"
|
||||
// @Param request body map[string]interface{} true "更新字段(含 locale)"
|
||||
// @Success 200 {object} map[string]interface{} "更新后的渠道"
|
||||
// @Failure 400 {object} map[string]interface{} "请求参数错误"
|
||||
// @Failure 404 {object} map[string]interface{} "渠道不存在"
|
||||
|
|
@ -218,6 +225,7 @@ func (h *IMHandler) UpdateIMChannel(c *gin.Context) {
|
|||
Name *string `json:"name"`
|
||||
Mode *string `json:"mode"`
|
||||
OutputMode *string `json:"output_mode"`
|
||||
Locale *string `json:"locale"`
|
||||
SessionMode *string `json:"session_mode"`
|
||||
KnowledgeBaseID *string `json:"knowledge_base_id"`
|
||||
Credentials types.JSON `json:"credentials"`
|
||||
|
|
@ -238,6 +246,14 @@ func (h *IMHandler) UpdateIMChannel(c *gin.Context) {
|
|||
if req.OutputMode != nil {
|
||||
channel.OutputMode = *req.OutputMode
|
||||
}
|
||||
if req.Locale != nil {
|
||||
locale, err := normalizeIMLocale(*req.Locale)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
channel.Locale = locale
|
||||
}
|
||||
if req.SessionMode != nil {
|
||||
channel.SessionMode = *req.SessionMode
|
||||
}
|
||||
|
|
@ -278,6 +294,17 @@ func (h *IMHandler) UpdateIMChannel(c *gin.Context) {
|
|||
c.JSON(http.StatusOK, gin.H{"data": channel})
|
||||
}
|
||||
|
||||
func normalizeIMLocale(locale string) (string, error) {
|
||||
locale = strings.TrimSpace(locale)
|
||||
if locale == "" {
|
||||
return "", nil
|
||||
}
|
||||
if normalized := types.NormalizeSupportedLocale(locale); normalized != "" {
|
||||
return normalized, nil
|
||||
}
|
||||
return "", errors.New("locale must be one of: 'en-US', 'ja-JP', 'ko-KR', 'ru-RU', 'zh-CN'")
|
||||
}
|
||||
|
||||
// DeleteIMChannel deletes an IM channel.
|
||||
//
|
||||
// DeleteIMChannel godoc
|
||||
|
|
|
|||
|
|
@ -0,0 +1,61 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestNormalizeIMLocale(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
locale string
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "empty", locale: "", want: ""},
|
||||
{name: "supported", locale: "en-US", want: "en-US"},
|
||||
{name: "trimmed", locale: " zh-CN ", want: "zh-CN"},
|
||||
{name: "unsupported", locale: "fr-FR", wantErr: true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := normalizeIMLocale(tt.locale)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("normalizeIMLocale(%q) error = %v, wantErr %v", tt.locale, err, tt.wantErr)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Fatalf("normalizeIMLocale(%q) = %q, want %q", tt.locale, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateIMChannelRejectsUnsupportedLocale(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
handler := NewIMHandler(nil)
|
||||
router.POST("/agents/:id/im-channels", handler.CreateIMChannel)
|
||||
|
||||
req := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/agents/agent-1/im-channels",
|
||||
strings.NewReader(`{"platform":"feishu","locale":"fr-FR"}`),
|
||||
)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req = req.WithContext(context.WithValue(req.Context(), types.TenantIDContextKey, uint64(42)))
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
router.ServeHTTP(recorder, req)
|
||||
|
||||
if recorder.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d; body=%s", recorder.Code, http.StatusBadRequest, recorder.Body.String())
|
||||
}
|
||||
if !strings.Contains(recorder.Body.String(), "locale must be one of") {
|
||||
t.Fatalf("body = %s, want locale validation error", recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
|
@ -10,7 +10,8 @@ import (
|
|||
func TestWithIMIdentity(t *testing.T) {
|
||||
const tenantID uint64 = 42
|
||||
msg := &IncomingMessage{Platform: PlatformFeishu, UserID: "open-id-1"}
|
||||
ctx := withIMIdentity(context.Background(), tenantID, "channel-1", msg)
|
||||
channel := &IMChannel{ID: "channel-1", TenantID: tenantID, Locale: "ja-JP"}
|
||||
ctx := withIMIdentity(context.Background(), channel, msg)
|
||||
|
||||
gotTenant, ok := types.TenantIDFromContext(ctx)
|
||||
if !ok || gotTenant != tenantID {
|
||||
|
|
@ -48,4 +49,31 @@ func TestWithIMIdentity(t *testing.T) {
|
|||
if !types.IsMCPOAuthNonInteractive(ctx) {
|
||||
t.Fatal("IM context should mark MCP OAuth as non-interactive")
|
||||
}
|
||||
if got, ok := types.LanguageFromContext(ctx); !ok || got != "ja-JP" {
|
||||
t.Fatalf("Language = %q, want %q", got, "ja-JP")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithIMIdentityUsesDeploymentDefaultWithoutChannelLocale(t *testing.T) {
|
||||
t.Setenv("WEKNORA_LANGUAGE", "ko-KR")
|
||||
ctx := context.WithValue(context.Background(), types.LanguageContextKey, "en-US")
|
||||
ctx = withIMIdentity(ctx, &IMChannel{ID: "channel-1", TenantID: 42}, nil)
|
||||
|
||||
if got, ok := types.LanguageFromContext(ctx); !ok || got != "ko-KR" {
|
||||
t.Fatalf("Language = %q, want deployment default %q", got, "ko-KR")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithIMIdentityAppliesChannelLocaleAcrossTransports(t *testing.T) {
|
||||
for _, mode := range []string{"webhook", "websocket", "longpoll"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
ctx := context.WithValue(context.Background(), types.LanguageContextKey, "en-US")
|
||||
channel := &IMChannel{ID: "channel-1", TenantID: 42, Mode: mode, Locale: "ru-RU"}
|
||||
ctx = withIMIdentity(ctx, channel, nil)
|
||||
|
||||
if got, ok := types.LanguageFromContext(ctx); !ok || got != "ru-RU" {
|
||||
t.Fatalf("Language = %q, want channel locale %q", got, "ru-RU")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -417,12 +417,20 @@ func formatQuotedContext(quote *QuotedMessage) string {
|
|||
// user (recognised by types.IsSyntheticUserID) lets Organization-shared
|
||||
// knowledge bases be merged and resolved correctly, since the shared-KB code
|
||||
// gates on a non-empty UserID. Viewer is the least privilege sufficient to
|
||||
// retrieve shared KBs.
|
||||
func withIMIdentity(ctx context.Context, tenantID uint64, channelID string, msg *IncomingMessage) context.Context {
|
||||
// retrieve shared KBs. The channel locale replaces any HTTP middleware value
|
||||
// because webhook Accept-Language belongs to the IM platform, not the writer;
|
||||
// channels without an explicit locale use the deployment default.
|
||||
func withIMIdentity(ctx context.Context, channel *IMChannel, msg *IncomingMessage) context.Context {
|
||||
tenantID := channel.TenantID
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, tenantID)
|
||||
ctx = context.WithValue(ctx, types.UserIDContextKey, fmt.Sprintf("system-%d", tenantID))
|
||||
locale := channel.Locale
|
||||
if locale == "" {
|
||||
locale = types.DefaultLanguage()
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.LanguageContextKey, locale)
|
||||
if msg != nil {
|
||||
principalID := fmt.Sprintf("%d:%s:%s:%s", tenantID, channelID, msg.Platform, msg.UserID)
|
||||
principalID := fmt.Sprintf("%d:%s:%s:%s", tenantID, channel.ID, msg.Platform, msg.UserID)
|
||||
ctx = types.WithPrincipal(ctx, types.Principal{Type: types.PrincipalIMUser, ID: principalID})
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleViewer)
|
||||
|
|
@ -1606,6 +1614,7 @@ func sameChannelRuntimeConfig(cached, fresh *IMChannel) bool {
|
|||
cached.Enabled == fresh.Enabled &&
|
||||
cached.Mode == fresh.Mode &&
|
||||
cached.OutputMode == fresh.OutputMode &&
|
||||
cached.Locale == fresh.Locale &&
|
||||
cached.KnowledgeBaseID == fresh.KnowledgeBaseID &&
|
||||
cached.SessionMode == fresh.SessionMode &&
|
||||
equalChannelCredentials(cached.Credentials, fresh.Credentials)
|
||||
|
|
@ -1763,7 +1772,7 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann
|
|||
return fmt.Errorf("get tenant: %w", err)
|
||||
}
|
||||
sessionCtx := context.WithValue(ctx, types.TenantInfoContextKey, tenant)
|
||||
sessionCtx = withIMIdentity(sessionCtx, tenantID, channelID, msg)
|
||||
sessionCtx = withIMIdentity(sessionCtx, channel, msg)
|
||||
|
||||
// 2. Resolve or create a WeKnora session
|
||||
channelSession, err := s.resolveSession(sessionCtx, msg, tenantID, agentID, channelID, channel.SessionMode)
|
||||
|
|
@ -3167,6 +3176,7 @@ type ChannelWithAgent struct {
|
|||
Enabled bool `json:"enabled"`
|
||||
Mode string `json:"mode"`
|
||||
OutputMode string `json:"output_mode"`
|
||||
Locale string `json:"locale"`
|
||||
SessionMode string `json:"session_mode"`
|
||||
BotIdentity string `json:"bot_identity"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
|
|
@ -3184,7 +3194,7 @@ func (s *Service) ListChannelsByTenant(ctx context.Context, tenantID uint64) ([]
|
|||
q := s.db.Table("im_channels AS c").
|
||||
Select(`c.id, c.tenant_id, c.agent_id,
|
||||
COALESCE(a.name, '') AS agent_name,
|
||||
c.platform, c.name, c.enabled, c.mode, c.output_mode,
|
||||
c.platform, c.name, c.enabled, c.mode, c.output_mode, c.locale,
|
||||
c.session_mode, c.bot_identity, c.created_at, c.updated_at`).
|
||||
Joins(`LEFT JOIN custom_agents AS a
|
||||
ON a.id = c.agent_id AND a.tenant_id = c.tenant_id AND a.deleted_at IS NULL`).
|
||||
|
|
|
|||
|
|
@ -81,6 +81,7 @@ func newLifecycleTestDB(t *testing.T) *gorm.DB {
|
|||
enabled NUMERIC NOT NULL DEFAULT 1,
|
||||
mode TEXT NOT NULL DEFAULT 'websocket',
|
||||
output_mode TEXT NOT NULL DEFAULT 'stream',
|
||||
locale TEXT NOT NULL DEFAULT '',
|
||||
knowledge_base_id TEXT DEFAULT '',
|
||||
bot_identity TEXT NOT NULL DEFAULT '',
|
||||
session_mode TEXT NOT NULL DEFAULT 'user',
|
||||
|
|
@ -173,6 +174,7 @@ func createLifecycleChannel(t *testing.T, db *gorm.DB, id, agentID string) *IMCh
|
|||
Enabled: true,
|
||||
Mode: "webhook",
|
||||
OutputMode: "full",
|
||||
Locale: "en-US",
|
||||
SessionMode: string(SessionModeUser),
|
||||
Credentials: types.JSON(`{"token":"v1"}`),
|
||||
}
|
||||
|
|
@ -411,6 +413,7 @@ func TestSameChannelRuntimeConfigUsesSemanticCredentials(t *testing.T) {
|
|||
Enabled: true,
|
||||
Mode: "webhook",
|
||||
OutputMode: "full",
|
||||
Locale: "en-US",
|
||||
SessionMode: string(SessionModeUser),
|
||||
Credentials: types.JSON(`{"token":"secret","timeout":10}`),
|
||||
UpdatedAt: now,
|
||||
|
|
@ -426,6 +429,11 @@ func TestSameChannelRuntimeConfigUsesSemanticCredentials(t *testing.T) {
|
|||
if sameChannelRuntimeConfig(cached, &fresh) {
|
||||
t.Fatal("changed credentials did not trigger a rebuild")
|
||||
}
|
||||
fresh = *cached
|
||||
fresh.Locale = "ja-JP"
|
||||
if sameChannelRuntimeConfig(cached, &fresh) {
|
||||
t.Fatal("changed locale did not trigger a rebuild")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLeaderElectionFailsClosedWhenRedisUnavailable(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ type IMChannel struct {
|
|||
Enabled bool `json:"enabled" gorm:"not null;default:true"`
|
||||
Mode string `json:"mode" gorm:"type:varchar(20);not null;default:'websocket'"`
|
||||
OutputMode string `json:"output_mode" gorm:"type:varchar(20);not null;default:'stream'"`
|
||||
Locale string `json:"locale" gorm:"type:varchar(16);not null;default:''"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"type:varchar(36);default:''"`
|
||||
BotIdentity string `json:"bot_identity" gorm:"type:varchar(255);not null;default:'';uniqueIndex:idx_im_channels_bot_identity,where:deleted_at IS NULL AND bot_identity != ''"`
|
||||
SessionMode string `json:"session_mode" gorm:"type:varchar(20);not null;default:'user'"`
|
||||
|
|
@ -49,6 +50,7 @@ type IMChannelSummary struct {
|
|||
Enabled bool `json:"enabled"`
|
||||
Mode string `json:"mode"`
|
||||
OutputMode string `json:"output_mode"`
|
||||
Locale string `json:"locale"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
BotIdentity string `json:"bot_identity"`
|
||||
SessionMode string `json:"session_mode"`
|
||||
|
|
@ -68,6 +70,7 @@ func SummarizeIMChannel(ch IMChannel) IMChannelSummary {
|
|||
Enabled: ch.Enabled,
|
||||
Mode: ch.Mode,
|
||||
OutputMode: ch.OutputMode,
|
||||
Locale: ch.Locale,
|
||||
KnowledgeBaseID: ch.KnowledgeBaseID,
|
||||
BotIdentity: ch.BotIdentity,
|
||||
SessionMode: ch.SessionMode,
|
||||
|
|
@ -111,6 +114,9 @@ func (ch *IMChannel) BeforeCreate(tx *gorm.DB) error {
|
|||
if err := ch.validateSessionMode(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ch.normalizeAndValidateLocale(); err != nil {
|
||||
return err
|
||||
}
|
||||
ch.BotIdentity = ch.computeBotIdentity()
|
||||
return nil
|
||||
}
|
||||
|
|
@ -124,10 +130,26 @@ func (ch *IMChannel) BeforeSave(tx *gorm.DB) error {
|
|||
if err := ch.validateSessionMode(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ch.normalizeAndValidateLocale(); err != nil {
|
||||
return err
|
||||
}
|
||||
ch.BotIdentity = ch.computeBotIdentity()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ch *IMChannel) normalizeAndValidateLocale() error {
|
||||
locale := strings.TrimSpace(ch.Locale)
|
||||
if locale == "" {
|
||||
ch.Locale = ""
|
||||
return nil
|
||||
}
|
||||
if normalized := types.NormalizeSupportedLocale(locale); normalized != "" {
|
||||
ch.Locale = normalized
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("invalid locale: %s", locale)
|
||||
}
|
||||
|
||||
// validateSessionMode checks that SessionMode holds a supported value.
|
||||
func (ch *IMChannel) validateSessionMode() error {
|
||||
switch SessionMode(ch.SessionMode) {
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ func TestSummarizeIMChannel_OmitsCredentials(t *testing.T) {
|
|||
AgentID: "agent-1",
|
||||
Platform: "feishu",
|
||||
Name: "support",
|
||||
Locale: "ko-KR",
|
||||
Credentials: types.JSON(`{"app_secret":"top-secret"}`),
|
||||
}
|
||||
|
||||
|
|
@ -24,6 +25,7 @@ func TestSummarizeIMChannel_OmitsCredentials(t *testing.T) {
|
|||
require.NoError(t, err)
|
||||
|
||||
assert.True(t, summary.CredentialsConfigured)
|
||||
assert.Equal(t, "ko-KR", summary.Locale)
|
||||
assert.NotContains(t, string(body), "top-secret")
|
||||
assert.NotContains(t, string(body), `"credentials":`)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,6 +42,31 @@ func TestValidateSessionMode(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestIMChannelNormalizesAndValidatesLocale(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
locale string
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "empty uses deployment default", locale: "", want: ""},
|
||||
{name: "supported locale", locale: "ja-JP", want: "ja-JP"},
|
||||
{name: "trims supported locale", locale: " ko-KR ", want: "ko-KR"},
|
||||
{name: "rejects unsupported locale", locale: "fr-FR", wantErr: true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ch := &IMChannel{Locale: tt.locale}
|
||||
err := ch.normalizeAndValidateLocale()
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("normalizeAndValidateLocale() error = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
if ch.Locale != tt.want && !tt.wantErr {
|
||||
t.Fatalf("Locale = %q, want %q", ch.Locale, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIMChannelBeforeCreate_SessionModeDefault(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
|
|
|||
|
|
@ -126,23 +126,10 @@ type EmbedChannelPublicConfig struct {
|
|||
DefaultLocale string `json:"default_locale,omitempty"`
|
||||
}
|
||||
|
||||
// Supported embed UI locales.
|
||||
var supportedEmbedLocales = map[string]struct{}{
|
||||
"zh-CN": {},
|
||||
"en-US": {},
|
||||
"ko-KR": {},
|
||||
"ja-JP": {},
|
||||
"ru-RU": {},
|
||||
}
|
||||
|
||||
// NormalizeEmbedDefaultLocale returns a supported locale tag or empty string
|
||||
// (meaning follow browser / host widget locale).
|
||||
func NormalizeEmbedDefaultLocale(locale string) string {
|
||||
locale = strings.TrimSpace(locale)
|
||||
if _, ok := supportedEmbedLocales[locale]; ok {
|
||||
return locale
|
||||
}
|
||||
return ""
|
||||
return NormalizeSupportedLocale(locale)
|
||||
}
|
||||
|
||||
// EmbedSessionMarkerPrefix tags sessions created through an embed channel.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,21 @@
|
|||
package types
|
||||
|
||||
import "strings"
|
||||
|
||||
var supportedLocales = map[string]struct{}{
|
||||
"zh-CN": {},
|
||||
"en-US": {},
|
||||
"ko-KR": {},
|
||||
"ja-JP": {},
|
||||
"ru-RU": {},
|
||||
}
|
||||
|
||||
// NormalizeSupportedLocale returns a trimmed, supported locale tag or an empty
|
||||
// string when the value is blank or unsupported.
|
||||
func NormalizeSupportedLocale(locale string) string {
|
||||
locale = strings.TrimSpace(locale)
|
||||
if _, ok := supportedLocales[locale]; ok {
|
||||
return locale
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
package types
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNormalizeSupportedLocale(t *testing.T) {
|
||||
for _, locale := range []string{"zh-CN", "en-US", "ko-KR", "ja-JP", "ru-RU"} {
|
||||
if got := NormalizeSupportedLocale(locale); got != locale {
|
||||
t.Errorf("NormalizeSupportedLocale(%q) = %q", locale, got)
|
||||
}
|
||||
}
|
||||
if got := NormalizeSupportedLocale("fr-FR"); got != "" {
|
||||
t.Errorf("NormalizeSupportedLocale(unsupported) = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
ALTER TABLE im_channels DROP COLUMN locale;
|
||||
|
|
@ -0,0 +1 @@
|
|||
ALTER TABLE im_channels ADD COLUMN locale VARCHAR(16) NOT NULL DEFAULT '';
|
||||
|
|
@ -0,0 +1 @@
|
|||
ALTER TABLE im_channels DROP COLUMN IF EXISTS locale;
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
ALTER TABLE im_channels
|
||||
ADD COLUMN IF NOT EXISTS locale VARCHAR(16) NOT NULL DEFAULT '';
|
||||
|
||||
COMMENT ON COLUMN im_channels.locale IS
|
||||
'Fixed locale for responses on this IM channel; empty uses the deployment default';
|
||||
Loading…
Reference in New Issue