fix(i18n): 修复内置智能体名称与描述不随界面语言切换的问题 (#2828)
* fix(i18n): 修复内置智能体名称与描述不随界面语言切换的问题
问题现象:切换界面语言后,内置智能体的名称/描述仍显示旧语言,
需要强制刷新(Ctrl+F5)才能恢复正确语言。
35820ebb 已在 GetAgentByID / ListAgents 读取路径按请求语言重新本地化,
本提交补全剩余场景:
后端:
- 共享智能体读取(sharedAgentInfo / GetSharedAgentForTenant)与组织
共享列表(ListOrgAgentShares)补 ApplyBuiltinAgentLocalization;
- IM 渠道列表(ListChannelsByTenant)改传请求 ctx,内置渠道的
AgentName 按调用方语言从 YAML i18n 重新解析(DB 列可能为空或为
落库时语言的残留值);
- 写入侧收敛:内置智能体配置落库时持久化 YAML default 语言的展示
字段(GetBuiltinAgent 而非 GetBuiltinAgentWithContext,与 locale
无关),更新/创建接口返回值再按调用方语言本地化,避免未覆盖的
读取路径显示随机语言。
前端:
- utils/request.ts 导出 getCurrentLanguage;
- chatResources 的 agents 缓存与 orgStore 的 sharedAgents 缓存在
新鲜度判断中加入"加载时语言 == 当前语言",切换语言后缓存立即
失效,下次访问按新 Accept-Language 重新拉取并响应式更新。
* fix(i18n): 按请求发起时的语言给智能体缓存打戳,避免切换语言时命中旧数据
落地预取尚未返回就改界面语言时,原先会把 zh-CN 响应标成 en-US 新鲜缓存,最多冻 60s。in-flight 只复用同语言请求,写入前校验代际,并补共享/IM 本地化回归测试。
---------
Co-authored-by: asmh1989 <minhua.sun@velavigo.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
main
parent
2a20733682
commit
8486912b48
|
|
@ -329,7 +329,7 @@ export interface IMChannelOverview {
|
|||
id: string;
|
||||
tenant_id: number;
|
||||
agent_id: string;
|
||||
agent_name: string; // empty string for built-in agents
|
||||
agent_name: string; // localized built-in name when the agent is built-in
|
||||
platform: IMChannel['platform'];
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
|
|
|
|||
|
|
@ -1,11 +1,17 @@
|
|||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import { ref, computed, watch } from 'vue'
|
||||
import { listKnowledgeBases, getKnowledgeBaseById } from '@/api/knowledge-base'
|
||||
import { listAgents, type CustomAgent } from '@/api/agent'
|
||||
import { listModels, type ModelConfig } from '@/api/model'
|
||||
import { listWebSearchProviders, type WebSearchProviderEntity } from '@/api/web-search-provider'
|
||||
import { isNamedSandboxBackend, listSandboxConfigs, type SandboxConfigRecord } from '@/api/system'
|
||||
import { useOrganizationStore } from '@/stores/organization'
|
||||
import { getCurrentLanguage } from '@/utils/request'
|
||||
import {
|
||||
isLocalizedCacheFresh,
|
||||
shouldCommitLocalizedGeneration,
|
||||
shouldReuseLocalizedInflight,
|
||||
} from './localizedResourceCache'
|
||||
|
||||
/** 空间级资源缓存 TTL */
|
||||
const CACHE_TTL_MS = 60_000
|
||||
|
|
@ -49,11 +55,37 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
|
|||
const validKnowledgeBases = computed(() => rawKnowledgeBases.value.filter(isKbModelReady))
|
||||
const chatModels = computed(() => allModels.value.filter((m) => m.type === 'KnowledgeQA'))
|
||||
|
||||
// 内置智能体名称/描述由后端按 Accept-Language 本地化返回;切换 UI 语言后
|
||||
// 旧缓存必须立即失效,否则要等 TTL 过期或强刷才能看到正确语言。
|
||||
// agentsLoadedLocale 必须是「请求发起时」的语言,不能在 await 之后再读当前语言。
|
||||
let agentsLoadedLocale = ''
|
||||
let agentsAllInflightLocale = ''
|
||||
|
||||
function isFresh(key: ResourceKey): boolean {
|
||||
const at = loadedAt.value[key]
|
||||
return !!at && Date.now() - at < CACHE_TTL_MS
|
||||
const at = loadedAt.value[key] ?? 0
|
||||
if (key === 'agents') {
|
||||
return isLocalizedCacheFresh(at, agentsLoadedLocale, getCurrentLanguage(), CACHE_TTL_MS)
|
||||
}
|
||||
return at > 0 && Date.now() - at < CACHE_TTL_MS
|
||||
}
|
||||
|
||||
function bumpAgentsGeneration() {
|
||||
agentsAllGen++
|
||||
agentsAllInflight = null
|
||||
agentsAllInflightLocale = ''
|
||||
}
|
||||
|
||||
watch(
|
||||
() => getCurrentLanguage(),
|
||||
(locale) => {
|
||||
if (agentsLoadedLocale && agentsLoadedLocale !== locale) {
|
||||
delete loadedAt.value.agents
|
||||
agentsLoadedLocale = ''
|
||||
bumpAgentsGeneration()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
async function runOnce(key: ResourceKey, force: boolean, loader: () => Promise<void>): Promise<void> {
|
||||
if (!force && isFresh(key)) return
|
||||
const existing = inflight.get(key)
|
||||
|
|
@ -125,12 +157,20 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
|
|||
return { data: res.data || [], disabled_own_agent_ids: res.disabled_own_agent_ids || [] }
|
||||
}
|
||||
|
||||
const locale = getCurrentLanguage()
|
||||
if (!force && isFresh('agents')) {
|
||||
return { data: agents.value, disabled_own_agent_ids: disabledOwnAgentIds.value }
|
||||
}
|
||||
if (!force && agentsAllInflight) return agentsAllInflight
|
||||
if (
|
||||
!force &&
|
||||
shouldReuseLocalizedInflight(!!agentsAllInflight, agentsAllInflightLocale, locale)
|
||||
) {
|
||||
return agentsAllInflight as Promise<{ data: CustomAgent[]; disabled_own_agent_ids: string[] }>
|
||||
}
|
||||
|
||||
const gen = ++agentsAllGen
|
||||
const requestLocale = locale
|
||||
agentsAllInflightLocale = requestLocale
|
||||
agentsAllInflight = (async () => {
|
||||
try {
|
||||
const [agentsRes] = await Promise.all([
|
||||
|
|
@ -139,12 +179,19 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
|
|||
])
|
||||
const res = agentsRes as { data?: CustomAgent[]; disabled_own_agent_ids?: string[] }
|
||||
const data = res.data || []
|
||||
agents.value = data
|
||||
disabledOwnAgentIds.value = res.disabled_own_agent_ids || []
|
||||
loadedAt.value.agents = Date.now()
|
||||
return { data, disabled_own_agent_ids: res.disabled_own_agent_ids || [] }
|
||||
const disabled = res.disabled_own_agent_ids || []
|
||||
if (shouldCommitLocalizedGeneration(gen, agentsAllGen)) {
|
||||
agents.value = data
|
||||
disabledOwnAgentIds.value = disabled
|
||||
loadedAt.value.agents = Date.now()
|
||||
agentsLoadedLocale = requestLocale
|
||||
}
|
||||
return { data, disabled_own_agent_ids: disabled }
|
||||
} finally {
|
||||
if (agentsAllGen === gen) agentsAllInflight = null
|
||||
if (shouldCommitLocalizedGeneration(gen, agentsAllGen)) {
|
||||
agentsAllInflight = null
|
||||
agentsAllInflightLocale = ''
|
||||
}
|
||||
}
|
||||
})()
|
||||
return agentsAllInflight
|
||||
|
|
@ -290,7 +337,8 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
|
|||
inflight.clear()
|
||||
agentKbInflight.clear()
|
||||
kbAllInflight = null
|
||||
agentsAllInflight = null
|
||||
agentsLoadedLocale = ''
|
||||
bumpAgentsGeneration()
|
||||
invalidateKnowledgeBaseDetail()
|
||||
return
|
||||
}
|
||||
|
|
@ -305,7 +353,8 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
|
|||
invalidateKnowledgeBaseDetail()
|
||||
}
|
||||
if (keys.includes('agents')) {
|
||||
agentsAllInflight = null
|
||||
agentsLoadedLocale = ''
|
||||
bumpAgentsGeneration()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,43 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import {
|
||||
isLocalizedCacheFresh,
|
||||
shouldCommitLocalizedGeneration,
|
||||
shouldForceLocalizedRefetch,
|
||||
shouldReuseLocalizedInflight,
|
||||
} from './localizedResourceCache.ts'
|
||||
|
||||
const TTL_MS = 60_000
|
||||
|
||||
test('localized cache is fresh only when TTL and request locale both match', () => {
|
||||
const loadedAt = 1_000
|
||||
assert.equal(isLocalizedCacheFresh(loadedAt, 'zh-CN', 'zh-CN', TTL_MS, 2_000), true)
|
||||
assert.equal(isLocalizedCacheFresh(loadedAt, 'zh-CN', 'en-US', TTL_MS, 2_000), false)
|
||||
assert.equal(isLocalizedCacheFresh(loadedAt, 'zh-CN', 'zh-CN', TTL_MS, loadedAt + TTL_MS), false)
|
||||
assert.equal(isLocalizedCacheFresh(0, 'zh-CN', 'zh-CN', TTL_MS, 2_000), false)
|
||||
})
|
||||
|
||||
test('landing prefetch must not be reused after the UI language changes', () => {
|
||||
// Request started as zh-CN; user switched to en-US before it settled.
|
||||
assert.equal(shouldReuseLocalizedInflight(true, 'zh-CN', 'en-US'), false)
|
||||
assert.equal(shouldForceLocalizedRefetch(true, 'zh-CN', 'en-US'), true)
|
||||
|
||||
assert.equal(shouldReuseLocalizedInflight(true, 'en-US', 'en-US'), true)
|
||||
assert.equal(shouldForceLocalizedRefetch(true, 'en-US', 'en-US'), false)
|
||||
assert.equal(shouldReuseLocalizedInflight(false, 'zh-CN', 'zh-CN'), false)
|
||||
assert.equal(shouldReuseLocalizedInflight(true, '', 'en-US'), false)
|
||||
})
|
||||
|
||||
test('stamping the request locale keeps a late zh-CN payload from looking fresh for en-US', () => {
|
||||
const requestLocale = 'zh-CN'
|
||||
const loadedAt = Date.now()
|
||||
// Wrong (old bug): stamp getCurrentLanguage() after await → 'en-US'.
|
||||
assert.equal(isLocalizedCacheFresh(loadedAt, 'en-US', 'en-US', TTL_MS), true)
|
||||
// Correct: stamp the locale the HTTP call was started with.
|
||||
assert.equal(isLocalizedCacheFresh(loadedAt, requestLocale, 'en-US', TTL_MS), false)
|
||||
})
|
||||
|
||||
test('a superseded generation must not write the cache', () => {
|
||||
assert.equal(shouldCommitLocalizedGeneration(1, 1), true)
|
||||
assert.equal(shouldCommitLocalizedGeneration(1, 2), false)
|
||||
})
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
/**
|
||||
* Helpers for short-TTL caches of API payloads that vary by Accept-Language
|
||||
* (built-in agent names/descriptions, shared-agent lists, …).
|
||||
*
|
||||
* The request must stamp the locale it was *started* with. Stamping
|
||||
* getCurrentLanguage() after await lets a zh-CN response be marked fresh for
|
||||
* en-US when the user switches language while the call is in flight.
|
||||
*/
|
||||
|
||||
export function isLocalizedCacheFresh(
|
||||
loadedAt: number,
|
||||
loadedLocale: string,
|
||||
currentLocale: string,
|
||||
ttlMs: number,
|
||||
now = Date.now(),
|
||||
): boolean {
|
||||
return loadedAt > 0 && now - loadedAt < ttlMs && loadedLocale === currentLocale
|
||||
}
|
||||
|
||||
/** Reuse an in-flight list request only when it was started for this UI language. */
|
||||
export function shouldReuseLocalizedInflight(
|
||||
hasInflight: boolean,
|
||||
inflightLocale: string,
|
||||
currentLocale: string,
|
||||
): boolean {
|
||||
return hasInflight && inflightLocale !== '' && inflightLocale === currentLocale
|
||||
}
|
||||
|
||||
/**
|
||||
* Force a follow-up fetch when the in-flight request was started for a
|
||||
* different UI language. versionedRequestCoordinator reuses in-flight on
|
||||
* non-force fetch, so locale mismatch must opt into force.
|
||||
*/
|
||||
export function shouldForceLocalizedRefetch(
|
||||
hasInflight: boolean,
|
||||
inflightLocale: string,
|
||||
currentLocale: string,
|
||||
): boolean {
|
||||
return hasInflight && inflightLocale !== '' && inflightLocale !== currentLocale
|
||||
}
|
||||
|
||||
/** Drop a completed payload when a newer generation (or language switch) superseded it. */
|
||||
export function shouldCommitLocalizedGeneration(
|
||||
requestGen: number,
|
||||
currentGen: number,
|
||||
): boolean {
|
||||
return requestGen === currentGen
|
||||
}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import { ref, computed, watch } from 'vue'
|
||||
import type {
|
||||
Organization,
|
||||
OrganizationMember,
|
||||
|
|
@ -43,7 +43,12 @@ import {
|
|||
reviewJoinRequest as reviewJoinRequestApi,
|
||||
requestRoleUpgrade as requestRoleUpgradeApi
|
||||
} from '@/api/organization'
|
||||
import { getCurrentLanguage } from '@/utils/request'
|
||||
import { createVersionedRequestCoordinator } from './versionedRequest'
|
||||
import {
|
||||
isLocalizedCacheFresh,
|
||||
shouldForceLocalizedRefetch,
|
||||
} from './localizedResourceCache'
|
||||
import {
|
||||
applyOrganizationResourceDelta,
|
||||
upsertById,
|
||||
|
|
@ -71,6 +76,9 @@ export const useOrganizationStore = defineStore('organization', () => {
|
|||
const SEARCHABLE_ORGANIZATION_TTL_MS = 5 * 60_000
|
||||
let sharedKbLoadedAt = 0
|
||||
let sharedAgentsLoadedAt = 0
|
||||
/** 共享智能体含按请求语言本地化的内置名称;切换 UI 语言后缓存随之失效 */
|
||||
let sharedAgentsLoadedLocale = ''
|
||||
let sharedAgentsInflightLocale = ''
|
||||
let searchableOrganizationsQuery = ''
|
||||
const searchableOrganizationCache = new Map<
|
||||
string,
|
||||
|
|
@ -491,25 +499,55 @@ export const useOrganizationStore = defineStore('organization', () => {
|
|||
* 去重 + 短期缓存。
|
||||
*/
|
||||
const sharedAgentsRequest = createVersionedRequestCoordinator(
|
||||
listSharedAgents,
|
||||
(response) => {
|
||||
async () => {
|
||||
const locale = getCurrentLanguage()
|
||||
sharedAgentsInflightLocale = locale
|
||||
const response = await listSharedAgents()
|
||||
return { response, locale }
|
||||
},
|
||||
({ response, locale }) => {
|
||||
if (response.success && response.data) {
|
||||
sharedAgents.value = response.data.filter(s => s.agent != null)
|
||||
sharedAgentsLoadedAt = Date.now()
|
||||
sharedAgentsLoadedLocale = locale
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
watch(
|
||||
() => getCurrentLanguage(),
|
||||
(locale) => {
|
||||
if (sharedAgentsLoadedLocale && sharedAgentsLoadedLocale !== locale) {
|
||||
sharedAgentsRequest.invalidate()
|
||||
sharedAgentsLoadedAt = 0
|
||||
sharedAgentsLoadedLocale = ''
|
||||
sharedAgentsInflightLocale = ''
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
async function fetchSharedAgents(options?: { force?: boolean }) {
|
||||
const locale = getCurrentLanguage()
|
||||
const force = options?.force ?? false
|
||||
if (
|
||||
!force &&
|
||||
sharedAgentsLoadedAt > 0 &&
|
||||
Date.now() - sharedAgentsLoadedAt < SHARED_RESOURCE_TTL_MS
|
||||
isLocalizedCacheFresh(
|
||||
sharedAgentsLoadedAt,
|
||||
sharedAgentsLoadedLocale,
|
||||
locale,
|
||||
SHARED_RESOURCE_TTL_MS,
|
||||
)
|
||||
) {
|
||||
return sharedAgents.value
|
||||
}
|
||||
await sharedAgentsRequest.fetch(force)
|
||||
const mustForce =
|
||||
force ||
|
||||
shouldForceLocalizedRefetch(
|
||||
sharedAgentsRequest.hasInFlightRequest(),
|
||||
sharedAgentsInflightLocale,
|
||||
locale,
|
||||
)
|
||||
await sharedAgentsRequest.fetch(mustForce)
|
||||
return sharedAgents.value
|
||||
}
|
||||
|
||||
|
|
@ -542,6 +580,8 @@ export const useOrganizationStore = defineStore('organization', () => {
|
|||
if (options.sharedAgents) {
|
||||
sharedAgentsRequest.invalidate()
|
||||
sharedAgentsLoadedAt = 0
|
||||
sharedAgentsLoadedLocale = ''
|
||||
sharedAgentsInflightLocale = ''
|
||||
}
|
||||
if (options.searchableOrganizations) {
|
||||
invalidateSearchableOrganizations(options.excludeSearchableOrganizationId)
|
||||
|
|
@ -796,6 +836,8 @@ export const useOrganizationStore = defineStore('organization', () => {
|
|||
error.value = null
|
||||
sharedKbLoadedAt = 0
|
||||
sharedAgentsLoadedAt = 0
|
||||
sharedAgentsLoadedLocale = ''
|
||||
sharedAgentsInflightLocale = ''
|
||||
organizationsLoadedAt = 0
|
||||
searchableOrganizationsQuery = ''
|
||||
searchableOrganizationCache.clear()
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ const instance = axios.create({
|
|||
});
|
||||
|
||||
// 获取当前用户语言(用于 Accept-Language header)
|
||||
function getCurrentLanguage(): string {
|
||||
export function getCurrentLanguage(): string {
|
||||
return i18n.global.locale?.value || localStorage.getItem('locale') || 'zh-CN'
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -104,6 +104,9 @@ func (s *agentShareService) sharedAgentInfo(
|
|||
SharedAt: share.CreatedAt,
|
||||
SharedByUserID: share.SharedByUserID,
|
||||
}
|
||||
if share.Agent != nil {
|
||||
types.ApplyBuiltinAgentLocalization(ctx, share.Agent)
|
||||
}
|
||||
if share.Organization != nil {
|
||||
info.OrgName = share.Organization.Name
|
||||
}
|
||||
|
|
@ -474,6 +477,7 @@ func (s *agentShareService) GetSharedAgentForTenant(
|
|||
if err != nil || agent == nil {
|
||||
return nil, ErrAgentNotFoundForShare
|
||||
}
|
||||
types.ApplyBuiltinAgentLocalization(ctx, agent)
|
||||
_ = callerTenantRole
|
||||
return agent, nil
|
||||
}
|
||||
|
|
@ -491,6 +495,7 @@ func (s *agentShareService) GetSharedAgentForTenant(
|
|||
}
|
||||
return nil, err
|
||||
}
|
||||
types.ApplyBuiltinAgentLocalization(ctx, agent)
|
||||
_ = callerTenantRole
|
||||
return agent, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -111,3 +111,44 @@ func TestFilterSharedAgentWriteToolsCoversAllWikiMutations(t *testing.T) {
|
|||
require.Empty(t, filtered, "wiki mutation tool %q must be filtered for shared agents", definition.Name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharedAgentInfoLocalizesBuiltinName(t *testing.T) {
|
||||
restore := types.OverrideBuiltinAgentEntriesForTest(map[string]*types.BuiltinAgentEntry{
|
||||
types.BuiltinQuickAnswerID: {
|
||||
ID: types.BuiltinQuickAnswerID,
|
||||
I18n: map[string]types.BuiltinAgentI18n{
|
||||
"default": {Name: "快速问答", Description: "中文 RAG"},
|
||||
"en-US": {Name: "Quick Answer", Description: "English RAG"},
|
||||
},
|
||||
},
|
||||
})
|
||||
t.Cleanup(restore)
|
||||
|
||||
agent := &types.CustomAgent{
|
||||
ID: types.BuiltinQuickAnswerID,
|
||||
Name: "frozen-zh",
|
||||
Description: "frozen-zh-desc",
|
||||
IsBuiltin: true,
|
||||
TenantID: 1,
|
||||
}
|
||||
svc := &agentShareService{}
|
||||
ctx := context.WithValue(context.Background(), types.LanguageContextKey, "en-US")
|
||||
info := svc.sharedAgentInfo(ctx, &types.AgentShare{
|
||||
Agent: agent,
|
||||
SourceTenantID: 1,
|
||||
}, types.OrgRoleViewer, map[string]bool{})
|
||||
|
||||
require.Equal(t, "Quick Answer", info.Agent.Name)
|
||||
require.Equal(t, "English RAG", info.Agent.Description)
|
||||
}
|
||||
|
||||
func TestSharedAgentInfoLeavesCustomAgentName(t *testing.T) {
|
||||
agent := &types.CustomAgent{ID: "custom-1", Name: "Mine", Description: "keep me"}
|
||||
svc := &agentShareService{}
|
||||
info := svc.sharedAgentInfo(context.Background(), &types.AgentShare{
|
||||
Agent: agent,
|
||||
SourceTenantID: 1,
|
||||
}, types.OrgRoleViewer, map[string]bool{})
|
||||
require.Equal(t, "Mine", info.Agent.Name)
|
||||
require.Equal(t, "keep me", info.Agent.Description)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -311,8 +311,9 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custo
|
|||
|
||||
// updateBuiltinAgent updates a built-in agent's configuration (but not basic info)
|
||||
func (s *customAgentService) updateBuiltinAgent(ctx context.Context, agent *types.CustomAgent, tenantID uint64) (*types.CustomAgent, error) {
|
||||
// Get the default built-in agent from registry (i18n-aware)
|
||||
defaultAgent := types.GetBuiltinAgentWithContext(ctx, agent.ID, tenantID)
|
||||
// Persist locale-independent display fields (the YAML "default" locale) so
|
||||
// read paths that skip builtin localization see a stable language.
|
||||
defaultAgent := types.GetBuiltinAgent(agent.ID, tenantID)
|
||||
if defaultAgent == nil {
|
||||
return nil, ErrAgentNotFound
|
||||
}
|
||||
|
|
@ -342,6 +343,7 @@ func (s *customAgentService) updateBuiltinAgent(ctx context.Context, agent *type
|
|||
}
|
||||
|
||||
logger.Infof(ctx, "Built-in agent config updated successfully, ID: %s", agent.ID)
|
||||
types.ApplyBuiltinAgentLocalization(ctx, existingAgent)
|
||||
return existingAgent, nil
|
||||
}
|
||||
|
||||
|
|
@ -373,6 +375,7 @@ func (s *customAgentService) updateBuiltinAgent(ctx context.Context, agent *type
|
|||
}
|
||||
|
||||
logger.Infof(ctx, "Built-in agent config record created successfully, ID: %s", agent.ID)
|
||||
types.ApplyBuiltinAgentLocalization(ctx, newAgent)
|
||||
return newAgent, nil
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -161,7 +161,7 @@ func (h *IMHandler) ListAllIMChannels(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
channels, err := h.imService.ListChannelsByTenant(tenantID)
|
||||
channels, err := h.imService.ListChannelsByTenant(c.Request.Context(), tenantID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list channels"})
|
||||
return
|
||||
|
|
|
|||
|
|
@ -1463,6 +1463,9 @@ func (h *OrganizationHandler) ListOrgAgentShares(c *gin.Context) {
|
|||
Permission: string(s.Permission), MyRoleInOrg: string(myRoleInOrg), MyPermission: string(effectivePerm), CreatedAt: s.CreatedAt,
|
||||
}
|
||||
if s.Agent != nil {
|
||||
// Built-in rows carry display fields frozen in the writer's
|
||||
// language; re-localize for the caller.
|
||||
types.ApplyBuiltinAgentLocalization(ctx, s.Agent)
|
||||
resp.AgentName = s.Agent.Name
|
||||
resp.AgentAvatar = s.Agent.Avatar
|
||||
cfg := &s.Agent.Config
|
||||
|
|
|
|||
|
|
@ -0,0 +1,36 @@
|
|||
package im
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestRelocalizeBuiltinChannelAgentNames(t *testing.T) {
|
||||
restore := types.OverrideBuiltinAgentEntriesForTest(map[string]*types.BuiltinAgentEntry{
|
||||
types.BuiltinQuickAnswerID: {
|
||||
ID: types.BuiltinQuickAnswerID,
|
||||
Avatar: "quick.png",
|
||||
I18n: map[string]types.BuiltinAgentI18n{
|
||||
"default": {Name: "快速问答"},
|
||||
"en-US": {Name: "Quick Answer"},
|
||||
"zh-CN": {Name: "快速问答"},
|
||||
},
|
||||
},
|
||||
})
|
||||
t.Cleanup(restore)
|
||||
|
||||
rows := []ChannelWithAgent{
|
||||
{AgentID: "custom-1", TenantID: 1, AgentName: "Mine"},
|
||||
{AgentID: types.BuiltinQuickAnswerID, TenantID: 1, AgentName: ""},
|
||||
{AgentID: types.BuiltinQuickAnswerID, TenantID: 1, AgentName: "frozen-zh"},
|
||||
}
|
||||
ctx := context.WithValue(context.Background(), types.LanguageContextKey, "en-US")
|
||||
relocalizeBuiltinChannelAgentNames(ctx, rows)
|
||||
|
||||
require.Equal(t, "Mine", rows[0].AgentName)
|
||||
require.Equal(t, "Quick Answer", rows[1].AgentName)
|
||||
require.Equal(t, "Quick Answer", rows[2].AgentName)
|
||||
}
|
||||
|
|
@ -3009,11 +3009,11 @@ type ChannelWithAgent struct {
|
|||
}
|
||||
|
||||
// ListChannelsByTenant returns all non-deleted IM channels in the given tenant,
|
||||
// joined with custom_agents.name. Built-in agent IDs (whose rows may not exist
|
||||
// in custom_agents) produce an empty AgentName — the frontend can substitute a
|
||||
// localized "builtin agent" label in that case. Channels whose custom agent was
|
||||
// soft-deleted are excluded so overview lists stay consistent after agent removal.
|
||||
func (s *Service) ListChannelsByTenant(tenantID uint64) ([]ChannelWithAgent, error) {
|
||||
// joined with custom_agents.name. Built-in agent names are re-localized from
|
||||
// YAML i18n using ctx (the DB column may be empty or frozen in the writer's
|
||||
// language). Channels whose custom agent was soft-deleted are excluded so
|
||||
// overview lists stay consistent after agent removal.
|
||||
func (s *Service) ListChannelsByTenant(ctx context.Context, tenantID uint64) ([]ChannelWithAgent, error) {
|
||||
builtinIDs := types.GetBuiltinAgentIDs()
|
||||
var rows []ChannelWithAgent
|
||||
q := s.db.Table("im_channels AS c").
|
||||
|
|
@ -3033,9 +3033,20 @@ func (s *Service) ListChannelsByTenant(tenantID uint64) ([]ChannelWithAgent, err
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
relocalizeBuiltinChannelAgentNames(ctx, rows)
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// relocalizeBuiltinChannelAgentNames overlays YAML i18n names onto overview
|
||||
// rows for built-in agents. Custom agents are left unchanged.
|
||||
func relocalizeBuiltinChannelAgentNames(ctx context.Context, rows []ChannelWithAgent) {
|
||||
for i := range rows {
|
||||
if a := types.GetBuiltinAgentWithContext(ctx, rows[i].AgentID, rows[i].TenantID); a != nil && a.Name != "" {
|
||||
rows[i].AgentName = a.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CreateChannel creates a new IM channel and optionally starts it.
|
||||
// Returns a duplicate_bot error if the bot identity is already used by another channel.
|
||||
func (s *Service) CreateChannel(channel *IMChannel) error {
|
||||
|
|
|
|||
|
|
@ -151,6 +151,26 @@ func ApplyBuiltinAgentLocalization(ctx context.Context, agent *CustomAgent) {
|
|||
agent.Avatar = localized.Avatar
|
||||
}
|
||||
|
||||
var builtinAgentEntriesTestMu sync.Mutex
|
||||
|
||||
// OverrideBuiltinAgentEntriesForTest replaces the in-memory YAML registry.
|
||||
// Tests in other packages use this to assert locale overlays; call the
|
||||
// returned func to restore the previous map. Concurrent tests are serialized
|
||||
// so they do not clobber each other's entries.
|
||||
func OverrideBuiltinAgentEntriesForTest(entries map[string]*BuiltinAgentEntry) func() {
|
||||
builtinAgentEntriesTestMu.Lock()
|
||||
builtinAgentEntriesMu.Lock()
|
||||
prev := builtinAgentEntries
|
||||
builtinAgentEntries = entries
|
||||
builtinAgentEntriesMu.Unlock()
|
||||
return func() {
|
||||
builtinAgentEntriesMu.Lock()
|
||||
builtinAgentEntries = prev
|
||||
builtinAgentEntriesMu.Unlock()
|
||||
builtinAgentEntriesTestMu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Internal helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
|
|
|||
|
|
@ -6,9 +6,7 @@ import (
|
|||
)
|
||||
|
||||
func TestApplyBuiltinAgentLocalizationOverlaysYAMLLocale(t *testing.T) {
|
||||
builtinAgentEntriesMu.Lock()
|
||||
prevEntries := builtinAgentEntries
|
||||
builtinAgentEntries = map[string]*BuiltinAgentEntry{
|
||||
restore := OverrideBuiltinAgentEntriesForTest(map[string]*BuiltinAgentEntry{
|
||||
BuiltinQuickAnswerID: {
|
||||
ID: BuiltinQuickAnswerID,
|
||||
Avatar: "quick.png",
|
||||
|
|
@ -18,13 +16,8 @@ func TestApplyBuiltinAgentLocalizationOverlaysYAMLLocale(t *testing.T) {
|
|||
"zh-CN": {Name: "快速问答", Description: "中文 RAG"},
|
||||
},
|
||||
},
|
||||
}
|
||||
builtinAgentEntriesMu.Unlock()
|
||||
t.Cleanup(func() {
|
||||
builtinAgentEntriesMu.Lock()
|
||||
builtinAgentEntries = prevEntries
|
||||
builtinAgentEntriesMu.Unlock()
|
||||
})
|
||||
t.Cleanup(restore)
|
||||
|
||||
agent := &CustomAgent{
|
||||
ID: BuiltinQuickAnswerID,
|
||||
|
|
|
|||
Loading…
Reference in New Issue