fix(wiki): ensure prompt language is always resolved
Wiki generation sometimes rendered "Write in ." because async workers read empty locale payloads without falling back to context or defaults. Unify language resolution helpers and apply them at enqueue and consume time so every wiki and related async prompt gets a non-empty language.main
parent
d2888e9565
commit
39f4220c13
|
|
@ -762,7 +762,7 @@ func (s *customAgentService) getSuggestedQuestions(
|
|||
})
|
||||
continue
|
||||
}
|
||||
locale, _ := types.LanguageFromContext(ctx)
|
||||
locale := types.LanguageFromContextOrDefault(ctx)
|
||||
for _, page := range wikiPages {
|
||||
q := wikiSuggestionFromPage(page, locale)
|
||||
if q == "" || seen[q] {
|
||||
|
|
|
|||
|
|
@ -1367,7 +1367,7 @@ func (s *knowledgeService) moveKnowledgeReparse(
|
|||
}
|
||||
}
|
||||
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
lang := types.LanguageFromContextOrDefault(ctx)
|
||||
taskPayload := types.DocumentProcessPayload{
|
||||
TenantID: tenantID,
|
||||
KnowledgeID: knowledge.ID,
|
||||
|
|
|
|||
|
|
@ -213,7 +213,7 @@ func (s *knowledgeService) CreateKnowledgeFromFile(ctx context.Context,
|
|||
questionCount = 3
|
||||
}
|
||||
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
lang := types.LanguageFromContextOrDefault(ctx)
|
||||
taskPayload := types.DocumentProcessPayload{
|
||||
TenantID: tenantID,
|
||||
KnowledgeID: knowledge.ID,
|
||||
|
|
@ -411,7 +411,7 @@ func (s *knowledgeService) CreateKnowledgeFromURL(ctx context.Context,
|
|||
questionCount = 3
|
||||
}
|
||||
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
lang := types.LanguageFromContextOrDefault(ctx)
|
||||
taskPayload := types.DocumentProcessPayload{
|
||||
TenantID: tenantID,
|
||||
KnowledgeID: knowledge.ID,
|
||||
|
|
@ -653,7 +653,7 @@ func (s *knowledgeService) createKnowledgeFromFileURL(
|
|||
questionCount = 3
|
||||
}
|
||||
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
lang := types.LanguageFromContextOrDefault(ctx)
|
||||
taskPayload := types.DocumentProcessPayload{
|
||||
TenantID: tenantID,
|
||||
KnowledgeID: knowledge.ID,
|
||||
|
|
@ -927,7 +927,7 @@ func (s *knowledgeService) createKnowledgeFromPassageInternal(ctx context.Contex
|
|||
}
|
||||
}
|
||||
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
lang := types.LanguageFromContextOrDefault(ctx)
|
||||
taskPayload := types.DocumentProcessPayload{
|
||||
TenantID: tenantID,
|
||||
KnowledgeID: knowledge.ID,
|
||||
|
|
|
|||
|
|
@ -315,7 +315,7 @@ func (s *knowledgeService) cleanupWikiOnKnowledgeDelete(ctx context.Context, kno
|
|||
// time". The handler will ListPagesBySourceRef again, pick up any
|
||||
// pages that materialised after we looked, and also rebuild the index
|
||||
// so the knowledge's disappearance is reflected in the UI.
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
lang := types.LanguageFromContextOrDefault(ctx)
|
||||
tenantID, _ := types.TenantIDFromContext(ctx)
|
||||
EnqueueWikiRetract(ctx, s.task, s.taskPendingRepo, WikiRetractPayload{
|
||||
TenantID: tenantID,
|
||||
|
|
|
|||
|
|
@ -661,7 +661,7 @@ func (s *knowledgeService) processChunks(ctx context.Context,
|
|||
} else {
|
||||
s.skipStage(ctx, knowledge.ID, types.StageMultimodal, "skipped")
|
||||
// If there are no multimodal tasks, enqueue the post process task immediately
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
lang := types.LanguageFromContextOrDefault(ctx)
|
||||
postProcessPayload := types.KnowledgePostProcessPayload{
|
||||
TenantID: knowledge.TenantID,
|
||||
KnowledgeID: knowledge.ID,
|
||||
|
|
@ -2375,7 +2375,7 @@ func (s *knowledgeService) ReparseKnowledge(
|
|||
questionCount = 3
|
||||
}
|
||||
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
lang := types.LanguageFromContextOrDefault(ctx)
|
||||
taskPayload := types.DocumentProcessPayload{
|
||||
TenantID: tenantID,
|
||||
KnowledgeID: existing.ID,
|
||||
|
|
@ -2429,7 +2429,7 @@ func (s *knowledgeService) ReparseKnowledge(
|
|||
questionCount = 3
|
||||
}
|
||||
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
lang := types.LanguageFromContextOrDefault(ctx)
|
||||
taskPayload := types.DocumentProcessPayload{
|
||||
TenantID: tenantID,
|
||||
KnowledgeID: existing.ID,
|
||||
|
|
@ -2482,7 +2482,7 @@ func (s *knowledgeService) ReparseKnowledge(
|
|||
questionCount = 3
|
||||
}
|
||||
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
lang := types.LanguageFromContextOrDefault(ctx)
|
||||
taskPayload := types.DocumentProcessPayload{
|
||||
TenantID: tenantID,
|
||||
KnowledgeID: existing.ID,
|
||||
|
|
@ -3690,7 +3690,7 @@ func (s *knowledgeService) enqueueImageMultimodalTasks(
|
|||
chunkID = chunks[0].ChunkID
|
||||
}
|
||||
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
lang := types.LanguageFromContextOrDefault(ctx)
|
||||
payload := types.ImageMultimodalPayload{
|
||||
TenantID: knowledge.TenantID,
|
||||
KnowledgeID: knowledge.ID,
|
||||
|
|
|
|||
|
|
@ -112,7 +112,7 @@ func enqueueSummaryRefresh(
|
|||
if tracker == nil {
|
||||
tracker = noopSpanTracker{}
|
||||
}
|
||||
language, _ := types.LanguageFromContext(ctx)
|
||||
language := types.LanguageFromContextOrDefault(ctx)
|
||||
payload := types.SummaryGenerationPayload{
|
||||
TenantID: knowledge.TenantID,
|
||||
KnowledgeBaseID: knowledge.KnowledgeBaseID,
|
||||
|
|
|
|||
|
|
@ -1294,10 +1294,7 @@ func (s *knowledgeBaseService) buildDuplicateKnowledgeBaseName(
|
|||
tenantID uint64,
|
||||
sourceName string,
|
||||
) string {
|
||||
locale, ok := types.LanguageFromContext(ctx)
|
||||
if !ok {
|
||||
locale = types.DefaultLanguage()
|
||||
}
|
||||
locale := types.LanguageFromContextOrDefault(ctx)
|
||||
suffix := duplicateKBCopySuffix(locale)
|
||||
|
||||
baseName := strings.TrimSpace(sourceName)
|
||||
|
|
|
|||
|
|
@ -80,13 +80,7 @@ func (s *messageSuggestionService) EnsureFollowUps(
|
|||
}
|
||||
|
||||
tenantID := types.MustTenantIDFromContext(ctx)
|
||||
locale := message.ExecutionContext.Locale
|
||||
if locale == "" {
|
||||
locale, _ = types.LanguageFromContext(ctx)
|
||||
}
|
||||
if locale == "" {
|
||||
locale = types.DefaultLanguage()
|
||||
}
|
||||
locale := types.ResolveLanguage(ctx, message.ExecutionContext.Locale)
|
||||
configHash := message.ExecutionContext.AgentConfigHash
|
||||
if configHash == "" {
|
||||
configHash = "no-agent-config"
|
||||
|
|
@ -181,13 +175,7 @@ func (s *messageSuggestionService) GetFollowUps(
|
|||
return nil, err
|
||||
}
|
||||
tenantID := types.MustTenantIDFromContext(ctx)
|
||||
locale := message.ExecutionContext.Locale
|
||||
if locale == "" {
|
||||
locale, _ = types.LanguageFromContext(ctx)
|
||||
}
|
||||
if locale == "" {
|
||||
locale = types.DefaultLanguage()
|
||||
}
|
||||
locale := types.ResolveLanguage(ctx, message.ExecutionContext.Locale)
|
||||
configHash := message.ExecutionContext.AgentConfigHash
|
||||
if configHash == "" {
|
||||
configHash = "no-agent-config"
|
||||
|
|
@ -345,7 +333,7 @@ func (s *messageSuggestionService) generateWithModel(
|
|||
if categories == "" {
|
||||
categories = "clarify, deepen, action"
|
||||
}
|
||||
language := types.LanguageLocaleName(message.ExecutionContext.Locale)
|
||||
language := types.ResolveLanguageName(ctx, message.ExecutionContext.Locale)
|
||||
systemPrompt := buildSuggestionSystemPrompt(count, language, categories)
|
||||
if instruction := strings.TrimSpace(config.AdditionalInstruction); instruction != "" {
|
||||
systemPrompt += " Additional agent instruction: " + instruction
|
||||
|
|
|
|||
|
|
@ -496,7 +496,7 @@ func newWikiIngestPendingOp(
|
|||
tenantID uint64,
|
||||
kbID, knowledgeID string,
|
||||
) (*types.TaskPendingOp, error) {
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
lang := types.LanguageFromContextOrDefault(ctx)
|
||||
op := WikiPendingOp{
|
||||
Op: WikiOpIngest,
|
||||
KnowledgeID: knowledgeID,
|
||||
|
|
@ -523,7 +523,7 @@ func enqueueWikiIngestTrigger(
|
|||
tenantID uint64,
|
||||
kbID string,
|
||||
) error {
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
lang := types.LanguageFromContextOrDefault(ctx)
|
||||
trigger := WikiIngestPayload{
|
||||
TenantID: tenantID,
|
||||
KnowledgeBaseID: kbID,
|
||||
|
|
@ -1291,12 +1291,16 @@ type WikiBatchContext struct {
|
|||
|
||||
// SlugUpdate represents a single update operation for a specific slug
|
||||
type SlugUpdate struct {
|
||||
Slug string
|
||||
Type string // "entity", "concept", "summary", "retract", "retractStale"
|
||||
Item extractedItem // For entity/concept
|
||||
DocTitle string
|
||||
KnowledgeID string
|
||||
SourceRef string
|
||||
Slug string
|
||||
Type string // "entity", "concept", "summary", "retract", "retractStale"
|
||||
Item extractedItem // For entity/concept
|
||||
DocTitle string
|
||||
KnowledgeID string
|
||||
SourceRef string
|
||||
// Language is the already-resolved, human-readable language name the
|
||||
// Reduce phase interpolates into the editor prompt (e.g. "Chinese
|
||||
// (Simplified)"), NOT a locale code. Map resolves it once per document
|
||||
// so every page derived from that document shares one language.
|
||||
Language string
|
||||
SummaryBody string // For summary
|
||||
SummaryLine string // For summary
|
||||
|
|
|
|||
|
|
@ -496,7 +496,7 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
|||
RetractDocContent: op.DocSummary,
|
||||
DocTitle: op.DocTitle,
|
||||
KnowledgeID: op.KnowledgeID,
|
||||
Language: types.LanguageLocaleName(op.Language),
|
||||
Language: types.ResolveLanguageName(ctx, op.Language),
|
||||
})
|
||||
}
|
||||
for folderID := range folderSet {
|
||||
|
|
@ -1157,7 +1157,7 @@ func (s *wikiIngestService) mapOneDocument(
|
|||
) (*docIngestResult, []SlugUpdate, error) {
|
||||
docStartedAt := time.Now()
|
||||
knowledgeID := op.KnowledgeID
|
||||
lang := types.LanguageLocaleName(op.Language)
|
||||
lang := types.ResolveLanguageName(ctx, op.Language)
|
||||
|
||||
// Open a postprocess.wiki subspan under the parent attempt's
|
||||
// postprocess stage so the actual per-doc work (LLM extraction +
|
||||
|
|
@ -1662,6 +1662,26 @@ func (s *wikiIngestService) extractEntitiesAndConceptsNoUpsert(
|
|||
return result.Entities, result.Concepts, slugItems, nil
|
||||
}
|
||||
|
||||
// resolveSlugUpdateLanguage picks the language the editor prompt should write
|
||||
// the page in.
|
||||
//
|
||||
// A single page aggregates updates from every document that cites it, and an
|
||||
// update queued before the language field existed — or enqueued from a
|
||||
// background path that never saw the HTTP language middleware — carries none.
|
||||
// Scanning for the first update that resolved a language, rather than indexing
|
||||
// into one bucket, keeps the page localised as long as ANY contributor knew the
|
||||
// language; the deployment default covers the case where none did. Without the
|
||||
// fallback the prompt renders "Write in ." and the model picks a language at
|
||||
// random, which is how single pages ended up in the wrong language.
|
||||
func resolveSlugUpdateLanguage(ctx context.Context, updates []SlugUpdate) string {
|
||||
for _, u := range updates {
|
||||
if u.Language != "" {
|
||||
return u.Language
|
||||
}
|
||||
}
|
||||
return types.LanguageNameFromContext(ctx)
|
||||
}
|
||||
|
||||
// reduceSlugUpdates returns:
|
||||
// - changed: whether the wiki page was created or updated
|
||||
// - affectedType: "ingest" or "retract" — drives downstream bookkeeping
|
||||
|
|
@ -1837,11 +1857,10 @@ func (s *wikiIngestService) reduceSlugUpdates(
|
|||
var newContentBuilder strings.Builder
|
||||
var sharedSourceContexts strings.Builder
|
||||
var docTitles []string
|
||||
var language string
|
||||
|
||||
language := resolveSlugUpdateLanguage(ctx, updates)
|
||||
|
||||
if len(retracts) > 0 {
|
||||
language = retracts[0].Language
|
||||
|
||||
for _, r := range retracts {
|
||||
fmt.Fprintf(&deletedContent, "<document>\n<title>%s</title>\n<content>\n%s\n</content>\n</document>\n\n", r.DocTitle, r.RetractDocContent)
|
||||
}
|
||||
|
|
@ -1891,8 +1910,6 @@ func (s *wikiIngestService) reduceSlugUpdates(
|
|||
}
|
||||
|
||||
if len(additions) > 0 {
|
||||
language = additions[0].Language
|
||||
|
||||
// Resolve SourceChunks → chunk contents in a single batched query per
|
||||
// knowledge ID, so the <new_information> block can quote the chunks
|
||||
// verbatim instead of relying on the short Details paraphrase.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,134 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"text/template"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// Wiki work is enqueued from background paths (clone/move, reparse, internal
|
||||
// retries) that never pass through the HTTP language middleware. Persisting an
|
||||
// empty locale there strands the language for the whole document, because the
|
||||
// worker resolves the prompt language from the queued op.
|
||||
func TestNewWikiIngestPendingOpPersistsResolvedLanguage(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ctx context.Context
|
||||
want string
|
||||
}{
|
||||
{"request locale is preserved", context.WithValue(
|
||||
context.Background(), types.LanguageContextKey, "en-US"), "en-US"},
|
||||
{"language-less background context falls back", context.Background(), types.DefaultLanguage()},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
pendingOp, err := newWikiIngestPendingOp(tt.ctx, 7, "kb-1", "knowledge-1")
|
||||
if err != nil {
|
||||
t.Fatalf("newWikiIngestPendingOp() error = %v", err)
|
||||
}
|
||||
var op WikiPendingOp
|
||||
if err := json.Unmarshal(pendingOp.Payload, &op); err != nil {
|
||||
t.Fatalf("unmarshal pending op payload: %v", err)
|
||||
}
|
||||
if op.Language != tt.want {
|
||||
t.Fatalf("op.Language = %q, want %q", op.Language, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Rows queued before the language field existed still have to produce a
|
||||
// localized page, so the worker resolves the op locale against ctx + default
|
||||
// rather than trusting the payload verbatim.
|
||||
func TestResolveLanguageNameRecoversLegacyPendingOp(t *testing.T) {
|
||||
ctx := context.WithValue(context.Background(), types.LanguageContextKey, "ko-KR")
|
||||
if got := types.ResolveLanguageName(ctx, ""); got != "Korean" {
|
||||
t.Fatalf("legacy op language = %q, want %q", got, "Korean")
|
||||
}
|
||||
if got := types.ResolveLanguageName(context.Background(), ""); got == "" {
|
||||
t.Fatal("legacy op with no ctx language resolved to an empty prompt language")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveSlugUpdateLanguage(t *testing.T) {
|
||||
ctx := context.WithValue(context.Background(), types.LanguageContextKey, "en-US")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
updates []SlugUpdate
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "uses the language carried by the updates",
|
||||
updates: []SlugUpdate{{Language: "Korean"}},
|
||||
want: "Korean",
|
||||
},
|
||||
{
|
||||
// A page aggregates contributions from several documents; the
|
||||
// first one is not guaranteed to carry a language.
|
||||
name: "skips contributors that carry no language",
|
||||
updates: []SlugUpdate{{Type: "retract"}, {Language: "Korean"}},
|
||||
want: "Korean",
|
||||
},
|
||||
{
|
||||
name: "falls back to the request language",
|
||||
updates: []SlugUpdate{{Type: "retract"}, {Type: "entity"}},
|
||||
want: "English",
|
||||
},
|
||||
{
|
||||
name: "falls back for an empty update set",
|
||||
updates: nil,
|
||||
want: "English",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := resolveSlugUpdateLanguage(ctx, tt.updates); got != tt.want {
|
||||
t.Errorf("resolveSlugUpdateLanguage() = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Guards the observable symptom: an unresolved language renders the editor
|
||||
// instruction as "Write in ." and leaves the output language to the model.
|
||||
func TestWikiPromptsNeverRenderAnEmptyLanguage(t *testing.T) {
|
||||
prompts := map[string]string{
|
||||
"WikiPageModifyUserPrompt": agent.WikiPageModifyUserPrompt,
|
||||
"WikiSummaryPrompt": agent.WikiSummaryPrompt,
|
||||
"WikiIndexIntroPrompt": agent.WikiIndexIntroPrompt,
|
||||
"WikiIndexIntroUpdatePrompt": agent.WikiIndexIntroUpdatePrompt,
|
||||
"WikiKnowledgeExtractPrompt": agent.WikiKnowledgeExtractPrompt,
|
||||
"WikiCandidateSlugPrompt": agent.WikiCandidateSlugPrompt,
|
||||
"WikiChunkCitationPrompt": agent.WikiChunkCitationPrompt,
|
||||
"WikiTaxonomyPlanPrompt": agent.WikiTaxonomyPlanPrompt,
|
||||
}
|
||||
|
||||
for name, tpl := range prompts {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
parsed, err := template.New(name).Parse(tpl)
|
||||
if err != nil {
|
||||
t.Fatalf("parse %s: %v", name, err)
|
||||
}
|
||||
var buf strings.Builder
|
||||
data := map[string]string{
|
||||
"HasAdditions": "1",
|
||||
"Language": types.ResolveLanguageName(context.Background(), ""),
|
||||
}
|
||||
if err := parsed.Execute(&buf, data); err != nil {
|
||||
t.Fatalf("execute %s: %v", name, err)
|
||||
}
|
||||
if strings.Contains(buf.String(), "Write in .") ||
|
||||
strings.Contains(buf.String(), "in <no value>") {
|
||||
t.Fatalf("%s rendered without a language", name)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -392,10 +392,7 @@ func buildMessageExecutionContext(
|
|||
skillNames []string,
|
||||
webSearchEnabled bool,
|
||||
) (types.MessageExecutionContext, string, uint64, string) {
|
||||
locale, ok := types.LanguageFromContext(ctx)
|
||||
if !ok {
|
||||
locale = types.DefaultLanguage()
|
||||
}
|
||||
locale := types.LanguageFromContextOrDefault(ctx)
|
||||
|
||||
snapshot := types.MessageExecutionContext{
|
||||
KnowledgeBaseIDs: knowledgeBaseIDs,
|
||||
|
|
|
|||
|
|
@ -1528,7 +1528,7 @@ func (h *TenantHandler) GetPromptTemplates(c *gin.Context) {
|
|||
}
|
||||
|
||||
// Determine user language from context (set by Language middleware)
|
||||
lang, _ := types.LanguageFromContext(c.Request.Context())
|
||||
lang := types.LanguageFromContextOrDefault(c.Request.Context())
|
||||
|
||||
// Build a localized copy so the original config is never mutated
|
||||
localized := &config.PromptTemplatesConfig{
|
||||
|
|
|
|||
|
|
@ -227,15 +227,46 @@ func LanguageFromContext(ctx context.Context) (string, bool) {
|
|||
return v, ok && v != ""
|
||||
}
|
||||
|
||||
// ResolveLanguage resolves the effective locale for work that may carry its own
|
||||
// language, in descending precedence: the explicit locale, the locale in ctx,
|
||||
// then DefaultLanguage().
|
||||
//
|
||||
// Async workers must use this rather than reading a payload field directly: a
|
||||
// task payload persisted before the language field existed, or enqueued from a
|
||||
// background path that never passed through the HTTP language middleware,
|
||||
// carries an empty locale. Interpolating that empty value into a prompt yields
|
||||
// instructions like "Write in ." and lets the model pick a language at random.
|
||||
func ResolveLanguage(ctx context.Context, locale string) string {
|
||||
if locale = strings.TrimSpace(locale); locale != "" {
|
||||
return locale
|
||||
}
|
||||
if ctxLocale, ok := LanguageFromContext(ctx); ok {
|
||||
return ctxLocale
|
||||
}
|
||||
return DefaultLanguage()
|
||||
}
|
||||
|
||||
// ResolveLanguageName is ResolveLanguage rendered as the human-readable name
|
||||
// that prompt templates interpolate (e.g. "Chinese (Simplified)").
|
||||
//
|
||||
// It is idempotent over already-resolved names: LanguageLocaleName passes
|
||||
// unknown values through, so re-resolving a display name returns it unchanged.
|
||||
func ResolveLanguageName(ctx context.Context, locale string) string {
|
||||
return LanguageLocaleName(ResolveLanguage(ctx, locale))
|
||||
}
|
||||
|
||||
// LanguageFromContextOrDefault returns the locale carried by ctx, falling back
|
||||
// to DefaultLanguage(). Use it when persisting a locale onto an async task
|
||||
// payload so downstream workers never inherit an empty language.
|
||||
func LanguageFromContextOrDefault(ctx context.Context) string {
|
||||
return ResolveLanguage(ctx, "")
|
||||
}
|
||||
|
||||
// LanguageNameFromContext returns the human-readable language name for use in prompts.
|
||||
// e.g. "zh-CN" -> "Chinese (Simplified)", "en-US" -> "English", "ko-KR" -> "Korean"
|
||||
// Falls back to DefaultLanguage() (WEKNORA_LANGUAGE env, then "zh-CN").
|
||||
func LanguageNameFromContext(ctx context.Context) string {
|
||||
lang, ok := LanguageFromContext(ctx)
|
||||
if !ok {
|
||||
lang = DefaultLanguage()
|
||||
}
|
||||
return LanguageLocaleName(lang)
|
||||
return ResolveLanguageName(ctx, "")
|
||||
}
|
||||
|
||||
// LanguageLocaleName maps a locale code to a human-readable language name for LLM prompts.
|
||||
|
|
|
|||
|
|
@ -99,6 +99,74 @@ func TestLanguageLocaleName(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestResolveLanguage(t *testing.T) {
|
||||
ctxWithLocale := context.WithValue(context.Background(), LanguageContextKey, "ko-KR")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
ctx context.Context
|
||||
locale string
|
||||
envLang string
|
||||
expected string
|
||||
}{
|
||||
{"explicit locale wins over context", ctxWithLocale, "en-US", "", "en-US"},
|
||||
{"blank locale falls back to context", ctxWithLocale, "", "", "ko-KR"},
|
||||
{"whitespace locale falls back to context", ctxWithLocale, " ", "", "ko-KR"},
|
||||
{"no locale and no context falls back to default", context.Background(), "", "", "zh-CN"},
|
||||
{"empty context value falls back to default", context.WithValue(
|
||||
context.Background(), LanguageContextKey, ""), "", "", "zh-CN"},
|
||||
{"deployment override wins over hardcoded default", context.Background(), "", "ru-RU", "ru-RU"},
|
||||
{"explicit locale wins over deployment override", context.Background(), "ja-JP", "ru-RU", "ja-JP"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if tt.envLang != "" {
|
||||
t.Setenv("WEKNORA_LANGUAGE", tt.envLang)
|
||||
}
|
||||
if got := ResolveLanguage(tt.ctx, tt.locale); got != tt.expected {
|
||||
t.Errorf("ResolveLanguage(_, %q) = %q, want %q", tt.locale, got, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A missing language must never reach a prompt template: "Write in {{.Language}}"
|
||||
// renders as "Write in ." and lets the model choose the output language.
|
||||
func TestResolveLanguageNameNeverReturnsEmpty(t *testing.T) {
|
||||
for _, ctx := range []context.Context{
|
||||
context.Background(),
|
||||
context.WithValue(context.Background(), LanguageContextKey, ""),
|
||||
} {
|
||||
if got := ResolveLanguageName(ctx, ""); got == "" {
|
||||
t.Fatal("ResolveLanguageName returned an empty prompt language")
|
||||
}
|
||||
}
|
||||
if got := ResolveLanguageName(context.Background(), "ko-KR"); got != "Korean" {
|
||||
t.Errorf("ResolveLanguageName(_, %q) = %q, want %q", "ko-KR", got, "Korean")
|
||||
}
|
||||
}
|
||||
|
||||
// Wiki carries an already-resolved display name on each queued update, so
|
||||
// re-resolving it downstream must be a no-op rather than a reset to default.
|
||||
func TestResolveLanguageNameIsIdempotentOverDisplayNames(t *testing.T) {
|
||||
for _, name := range []string{"Chinese (Simplified)", "English", "Korean"} {
|
||||
if got := ResolveLanguageName(context.Background(), name); got != name {
|
||||
t.Errorf("ResolveLanguageName(_, %q) = %q, want it unchanged", name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLanguageFromContextOrDefault(t *testing.T) {
|
||||
if got := LanguageFromContextOrDefault(context.Background()); got != "zh-CN" {
|
||||
t.Errorf("LanguageFromContextOrDefault(empty) = %q, want %q", got, "zh-CN")
|
||||
}
|
||||
ctx := context.WithValue(context.Background(), LanguageContextKey, "en-US")
|
||||
if got := LanguageFromContextOrDefault(ctx); got != "en-US" {
|
||||
t.Errorf("LanguageFromContextOrDefault(en-US) = %q, want %q", got, "en-US")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPOAuthNonInteractive(t *testing.T) {
|
||||
if IsMCPOAuthNonInteractive(nil) {
|
||||
t.Fatal("nil context should not be non-interactive")
|
||||
|
|
|
|||
Loading…
Reference in New Issue